tag:blogger.com,1999:blog-81366695142029469952024-03-19T11:06:04.816+05:30 Learn and shineSiva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.comBlogger104125tag:blogger.com,1999:blog-8136669514202946995.post-43178783531998592002024-03-18T17:11:00.003+05:302024-03-18T17:11:30.803+05:30What are the best practices for securing communication between microservices in a Java ecosystem<p> </p><p>Securing communication between microservices in a Java ecosystem is crucial to protect sensitive data, prevent unauthorized access, and ensure the integrity and confidentiality of communication. Here are some best practices for achieving secure communication between microservices:</p><p><br /></p><p></p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEiKd2Baf7z-LrBaeK4dIFSROtQ9sIOlfg6M8X_-JqpnW6w65oDBK2PRxLRIH1y2PaMSq-8EH0XFv9BKTMEfmpMYW9J86QfLOMaFJhpzAXlwYV_r4I4utQJ4jOltY06F720wlNssvGBV1ZQCFKuqiv_yPAOF4iB5vFMR5-InnatMx92noDUdTV5fv-eymAA" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="1089" data-original-width="1400" height="240" src="https://blogger.googleusercontent.com/img/a/AVvXsEiKd2Baf7z-LrBaeK4dIFSROtQ9sIOlfg6M8X_-JqpnW6w65oDBK2PRxLRIH1y2PaMSq-8EH0XFv9BKTMEfmpMYW9J86QfLOMaFJhpzAXlwYV_r4I4utQJ4jOltY06F720wlNssvGBV1ZQCFKuqiv_yPAOF4iB5vFMR5-InnatMx92noDUdTV5fv-eymAA" width="309" /></a></div><br /><br /><p></p><p><br /></p><p><br /></p><p><b>1. Transport Layer Security (TLS):</b></p><p>Use TLS/SSL for encrypting data transmitted over the network.</p><p>Enable HTTPS for RESTful APIs to ensure data confidentiality and integrity.</p><p>Configure mutual TLS (mTLS) for two-way authentication between services, where both client and server authenticate each other using certificates.</p><p><b>2. Service-to-Service Authentication:</b></p><p>Implement secure authentication mechanisms between microservices.</p><p>Use tokens (like JWT) or OAuth tokens for authentication and authorization.</p><p>Validate incoming tokens for each request to ensure only authorized services can access endpoints.</p><p><b>3. Role-Based Access Control (RBAC):</b></p><p>Implement RBAC to control access to microservice endpoints.</p><p>Define roles and permissions for each microservice, allowing only authorized users or services to perform specific actions.</p><p><b>4. API Gateway:</b></p><p>Use an API gateway to centralize security concerns and provide a single entry point for microservices.</p><p>Implement authentication, authorization, rate limiting, and request validation at the API gateway level.</p><p><b>5. Secure Service Discovery:</b></p><p>When using service discovery mechanisms like Eureka or Consul, ensure that service registration and discovery are secure.</p><p>Use authentication and encryption for communication between service registry and microservices.</p><p><b>6. Secure Configuration Management:</b></p><p>Store sensitive configuration properties (such as passwords, API keys) securely.</p><p>Use tools like Spring Cloud Config Server with encryption to manage and distribute configuration securely.</p><p><b>7. Secure Logging and Monitoring:</b></p><p>Implement secure logging practices to avoid logging sensitive information.</p><p>Use log encryption and centralized log management tools to monitor and detect security incidents.</p><p><b>8. Implement Content Validation:</b></p><p>Validate and sanitize input data to prevent injection attacks (e.g., SQL injection, XSS).</p><p>Use input validation libraries like Hibernate Validator or Bean Validation.</p><p><b>9. Container Security:</b></p><p>If deploying microservices in containers, ensure container images are scanned for vulnerabilities.</p><p>Implement least privilege principles for container permissions and avoid running containers with unnecessary privileges.</p><p><b>10. Use of Secure Protocols:</b></p><p>Avoid using insecure protocols such as HTTP and use HTTPS/TLS for secure communication.</p><p>Use protocols with strong security features like OAuth 2.0 for authentication and authorization.</p><p><b>11. Secure Message Queues:</b></p><p>If using message brokers (like RabbitMQ, Apache Kafka), ensure they are secured.</p><p>Use TLS/SSL for communication with the message broker.</p><p>Implement message encryption for sensitive data.</p><p><b>12. Data Encryption:</b></p><p>Encrypt sensitive data at rest and in transit.</p><p>Use libraries like Java Cryptography Architecture (JCA) or Bouncy Castle for encryption/decryption.</p><p><b>13. API Versioning and Deprecation:</b></p><p>Implement API versioning to manage changes in microservices.</p><p>Securely deprecate and remove old APIs to prevent security vulnerabilities in outdated endpoints.</p><p><b>14. Regular Security Audits and Penetration Testing:</b></p><p>Conduct regular security audits and vulnerability scans of microservices.</p><p>Perform penetration testing to identify potential security weaknesses and address them proactively.</p><p><b>15. Continuous Security Monitoring:</b></p><p>Implement continuous security monitoring using tools like Prometheus, Grafana, or ELK stack.</p><p>Monitor for suspicious activities, abnormal behaviors, or unauthorized access attempts.</p><p>Implement OAuth 2.0 Authorization Server and Resource Server in your microservices architecture.</p><p>Use JWT tokens for authentication and authorization between microservices.</p><p>Secure endpoints based on roles and scopes defined in JWT tokens.</p><p>Configure OAuth 2.0 clients for microservices to request and validate tokens.</p><p><b>Use Spring Cloud Gateway or Zuul as an API Gateway for centralized security enforcement.</b></p>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com2tag:blogger.com,1999:blog-8136669514202946995.post-11565833694463083022024-03-18T12:57:00.000+05:302024-03-18T12:57:44.294+05:30Explain the SOLID principles and how they influence the design of Java applications.<p> </p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEiWDFmlcznAtpw3NT41Q5XnJeytfHsd4PDvErYMt22DLNZ8XSyYD9dju7m9KqCRiLFM1Fgg75oQDS7jaUBhY-CcH7KGZBveAsdv9uhLEBCQ65f_JjBABWkRwC_qR8JF1XJ8FV6DvVtRblaABUwFbTb_n1rzKowLrwjR044BcF1KGi7KtJtpnYcn7GuV25k" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="120" data-original-width="420" height="91" src="https://blogger.googleusercontent.com/img/a/AVvXsEiWDFmlcznAtpw3NT41Q5XnJeytfHsd4PDvErYMt22DLNZ8XSyYD9dju7m9KqCRiLFM1Fgg75oQDS7jaUBhY-CcH7KGZBveAsdv9uhLEBCQ65f_JjBABWkRwC_qR8JF1XJ8FV6DvVtRblaABUwFbTb_n1rzKowLrwjR044BcF1KGi7KtJtpnYcn7GuV25k" width="320" /></a></div><div class="separator" style="clear: both; text-align: center;"><br /></div><div class="separator" style="clear: both; text-align: center;"><br /></div><div class="separator" style="clear: both; text-align: center;"><br /></div><p></p><p>The SOLID principles are a set of five design principles for writing clean, maintainable, and extensible object-oriented code. </p><p>They were introduced by Robert C. Martin (also known as Uncle Bob) to guide developers in creating software that is easier to understand, modify, and scale. </p><p>Here's an explanation of each principle and how they influence the design of Java applications:</p><p>1. <b>Single Responsibility Principle (SRP):</b></p><p>The SRP states that a class should have only one reason to change, meaning it should have only one job or responsibility. </p><p>This principle aims to keep classes focused and avoid bloated, tightly-coupled designs.</p><p><b>Influence on Java Design:</b></p><p>Helps create smaller, focused classes that are easier to understand and maintain.</p><p>Encourages separating concerns, such as separating business logic from data access or user interface.</p><p>Promotes the use of interfaces and abstractions to define contracts between components.</p><p><b>2. Open/Closed Principle (OCP):</b></p><p>The OCP states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. </p><p>This means that the behavior of a module can be extended without modifying its source code.</p><p><b>Influence on Java Design:</b></p><p>Encourages the use of interfaces and abstract classes to define contracts.</p><p>Allows developers to add new functionality by creating new classes that implement existing interfaces or extend abstract classes.</p><p>Promotes the use of design patterns like Strategy, Decorator, and Factory to achieve extensibility without modifying existing code.</p><p><b>3. Liskov Substitution Principle (LSP):</b></p><p>The LSP states that objects of a superclass should be replaceable with objects of its subclasses without affecting the correctness of the program. In other words, subclasses should be substitutable for their base classes.</p><p><b>Influence on Java Design:</b></p><p>Encourages adherence to contracts defined by interfaces or base classes.</p><p>Promotes polymorphism and inheritance in a way that maintains consistency and behavior across classes.</p><p>Helps prevent unexpected behavior when using subclasses in place of their base classes.</p><p><b>4. Interface Segregation Principle (ISP):</b></p><p>The ISP states that clients should not be forced to depend on interfaces they do not use. It suggests that large interfaces should be broken down into smaller, more specific interfaces so that clients only need to know about the methods that are of interest to them.</p><p><b>Influence on Java Design:</b></p><p>Encourages the creation of cohesive and focused interfaces.</p><p>Helps avoid "fat" interfaces that require implementing unnecessary methods.</p><p>Facilitates easier implementation of interfaces by focusing on specific functionalities.</p><p><b>5. Dependency Inversion Principle (DIP):</b></p><p>The DIP states that high-level modules should not depend on low-level modules. Both should depend on abstractions. Additionally, abstractions should not depend on details; details should depend on abstractions.</p><p><b>Influence on Java Design:</b></p><p>Encourages the use of interfaces or abstract classes to define contracts between components.</p><p>Promotes loose coupling between classes by depending on abstractions rather than concrete implementations.</p><p>Facilitates easier unit testing and the ability to swap implementations without affecting the higher-level modules.</p><p><b>Influence on Java Applications:</b></p><p><b>Modularity</b>: Applying SOLID principles helps create modular Java applications with smaller, more focused components.</p><p><b>Flexibility</b>: Designing with SOLID principles allows for easier changes and extensions to the system without risking unintended side effects.</p><p><b>Readability and Maintainability</b>: By promoting clean, well-structured code, SOLID principles make it easier for developers to understand and maintain Java applications.</p><p><b>Testability</b>: Code designed with SOLID principles is typically easier to unit test, as it often results in classes that are more isolated and decoupled from dependencies.</p><p><br /></p><p>In Java applications, adherence to the SOLID principles often leads to the use of design patterns such as Factory, Strategy, Decorator, and others. </p><p></p><p>These patterns help implement the principles effectively, resulting in code that is more robust, flexible, and easier to maintain over time.</p>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com0tag:blogger.com,1999:blog-8136669514202946995.post-33518907497761786152024-03-09T16:36:00.001+05:302024-03-09T16:36:28.325+05:30what are different types of design patterns used in microservices<p>When designing microservices, there are several architectural patterns that can be used to achieve various goals such as scalability, fault tolerance, maintainability, and ease of deployment. Here are some common patterns used in microservices architecture:</p><p><br /></p><p><b>1. Single Service Instance Pattern</b></p><p>Each microservice instance runs as a single instance. This is the simplest form of microservices architecture, where each service is deployed independently.</p><p><b>2. Service Instance per Container Pattern</b></p><p>Each microservice runs in its own container. Containers provide lightweight, isolated runtime environments for applications, allowing them to run consistently across different environments.</p><p><b>3. Service Instance per Virtual Machine Pattern</b></p><p>Each microservice runs in its own virtual machine (VM). This pattern provides a higher level of isolation compared to containers but comes with the overhead of managing VMs.</p><p><b>4. Shared Database Pattern</b></p><p>Multiple microservices share a common database. While this can simplify some aspects of development, it can also lead to tight coupling between services and make it difficult to evolve the system over time.</p><p><b>5. Database per Service Pattern</b></p><p>Each microservice has its own database. This pattern promotes loose coupling between services but requires careful coordination when data needs to be shared between services.</p><p><b>6. API Gateway Pattern</b></p><p>An API Gateway acts as a single entry point for clients to interact with multiple microservices. It can handle routing, authentication, and other cross-cutting concerns.</p><p><b>7. Aggregator Pattern</b></p><p>Aggregates data from multiple microservices into a single response for the client. This can reduce the number of client-server round trips and improve performance.</p><p><b>8. Saga Pattern</b></p><p>Manages distributed transactions across multiple microservices. A saga is a sequence of local transactions where each local transaction updates the database and publishes a message or event to trigger the next transaction.</p><p><b>9. Event Sourcing Pattern</b></p><p>Each microservice persists events as a log of changes to the system's state. This enables replaying events to rebuild state, auditing, and decoupling between services.</p><p><b>10. CQRS (Command Query Responsibility Segregation) Pattern</b></p><p>Separates read and write operations for a microservice. This pattern can improve scalability by allowing separate optimization for read and write operations.</p><p><b>11. Bulkhead Pattern</b></p><p>Isolates components of a system into separate pools to prevent failures in one component from affecting others. This helps improve fault tolerance and resilience.</p><p><b>12. Circuit Breaker Pattern</b></p><p>Monitors for failures and prevents cascading failures by temporarily blocking requests to a failing service. This pattern helps improve system stability.</p><p><b>13. Sidecar Pattern</b></p><p>Attaches a helper service, known as a "sidecar," to a microservice to provide additional functionality such as monitoring, logging, or security.</p><p><b>14. Strangler Pattern</b></p><p>Gradually replaces a monolithic application with microservices by "strangling" parts of the monolith with new microservices over time.</p><p><b>15. Choreography vs. Orchestration</b></p><p>In microservices, you often need to decide between choreography (decentralized coordination through events) and orchestration (centralized coordination through a service). This decision impacts how services communicate and coordinate their actions.</p><p>These patterns can be used individually or in combination to design a microservices architecture that meets the specific requirements of your application. It's essential to consider factors such as scalability, maintainability, fault tolerance, and team expertise when choosing the appropriate patterns for your system.</p><p><br /></p><p><br /></p><p><br /></p><p><br /></p><p> </p>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com0tag:blogger.com,1999:blog-8136669514202946995.post-48286506044212875582023-12-27T15:46:00.001+05:302023-12-27T15:46:59.871+05:30Getting started with Generative AI prompt engineer Step By Step Guide<p> <span style="color: #374151; font-family: Söhne, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Ubuntu, Cantarell, "Noto Sans", sans-serif, "Helvetica Neue", Arial, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; font-size: 16px; white-space-collapse: preserve;">Generative AI prompt engineering involves crafting effective prompts to elicit desired responses from generative models. </span></p><p><span style="color: #374151; font-family: Söhne, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Ubuntu, Cantarell, "Noto Sans", sans-serif, "Helvetica Neue", Arial, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; font-size: 16px; white-space-collapse: preserve;">Whether you're working with any models, the key is to provide clear and specific instructions. Here's a step-by-step guide to get started:</span></p><ol style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; color: #374151; counter-reset: list-number 0; display: flex; flex-direction: column; font-family: Söhne, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Ubuntu, Cantarell, "Noto Sans", sans-serif, "Helvetica Neue", Arial, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; font-size: 16px; list-style: none; margin: 1.25em 0px; padding: 0px; white-space-collapse: preserve;"><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; counter-increment: list-number 1; display: block; margin-bottom: 0px; margin-top: 0px; min-height: 28px; padding-left: 0.375em;"><p style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; margin: 0px;"><span style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; color: var(--tw-prose-bold); font-weight: 600;">Understand the Model's Capabilities:</span></p><ul style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: flex; flex-direction: column; list-style: disc; margin: 0px 0px 0px 1rem; padding: 0px;"><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: block; margin: 0px; min-height: 28px; padding-left: 0.375em;">Familiarize yourself with the capabilities and limitations of the generative model you're using. Understand the types of tasks it can perform and the formats it accepts.</li></ul></li><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; counter-increment: list-number 1; display: block; margin-bottom: 0px; margin-top: 0px; min-height: 28px; padding-left: 0.375em;"><p style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; margin: 0px;"><span style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; color: var(--tw-prose-bold); font-weight: 600;">Define Your Goal:</span></p><ul style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: flex; flex-direction: column; list-style: disc; margin: 0px 0px 0px 1rem; padding: 0px;"><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: block; margin: 0px; min-height: 28px; padding-left: 0.375em;">Clearly define the goal of your prompt. Are you looking for creative writing, programming code, problem-solving, or something else? The specificity of your goal will guide your prompt creation.</li></ul></li><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; counter-increment: list-number 1; display: block; margin-bottom: 0px; margin-top: 0px; min-height: 28px; padding-left: 0.375em;"><p style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; margin: 0px;"><span style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; color: var(--tw-prose-bold); font-weight: 600;">Start with a Clear Instruction:</span></p><ul style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: flex; flex-direction: column; list-style: disc; margin: 0px 0px 0px 1rem; padding: 0px;"><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: block; margin: 0px; min-height: 28px; padding-left: 0.375em;">Begin your prompt with a clear and concise instruction. Be specific about the type of output you're expecting. For example, if you want a creative story, you might start with "Write a short story about..."</li></ul></li><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; counter-increment: list-number 1; display: block; margin-bottom: 0px; margin-top: 0px; min-height: 28px; padding-left: 0.375em;"><p style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; margin: 0px;"><span style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; color: var(--tw-prose-bold); font-weight: 600;">Provide Context or Constraints:</span></p><ul style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: flex; flex-direction: column; list-style: disc; margin: 0px 0px 0px 1rem; padding: 0px;"><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: block; margin: 0px; min-height: 28px; padding-left: 0.375em;">If necessary, provide additional context or constraints to guide the model. This can include setting, characters, tone, or any specific requirements. Constraints help to narrow down the output and make it more relevant to your needs.</li></ul></li><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; counter-increment: list-number 1; display: block; margin-bottom: 0px; margin-top: 0px; min-height: 28px; padding-left: 0.375em;"><p style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; margin: 0px;"><span style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; color: var(--tw-prose-bold); font-weight: 600;">Experiment with Temperature and Max Tokens:</span></p><ul style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: flex; flex-direction: column; list-style: disc; margin: 0px 0px 0px 1rem; padding: 0px;"><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: block; margin: 0px; min-height: 28px; padding-left: 0.375em;">Generative models often come with parameters like "temperature" and "max tokens." Temperature controls the randomness of the output, and max tokens limit the length of the response. Experiment with these parameters to fine-tune the model's behavior.</li></ul></li><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; counter-increment: list-number 1; display: block; margin-bottom: 0px; margin-top: 0px; min-height: 28px; padding-left: 0.375em;"><p style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; margin: 0px;"><span style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; color: var(--tw-prose-bold); font-weight: 600;">Iterate and Refine:</span></p><ul style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: flex; flex-direction: column; list-style: disc; margin: 0px 0px 0px 1rem; padding: 0px;"><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: block; margin: 0px; min-height: 28px; padding-left: 0.375em;">Don't be afraid to iterate and refine your prompts. Experiment with different instructions, wording, and structures to achieve the desired output. Analyze the model's responses and adjust your prompts accordingly.</li></ul></li><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; counter-increment: list-number 1; display: block; margin-bottom: 0px; margin-top: 0px; min-height: 28px; padding-left: 0.375em;"><p style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; margin: 0px;"><span style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; color: var(--tw-prose-bold); font-weight: 600;">Use System and User Messages:</span></p><ul style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: flex; flex-direction: column; list-style: disc; margin: 0px 0px 0px 1rem; padding: 0px;"><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: block; margin: 0px; min-height: 28px; padding-left: 0.375em;">For interactive conversations with the model, you can use both system and user messages. System messages set the behavior of the assistant, while user messages simulate the user's input. This can be useful for multi-turn interactions.</li></ul></li><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; counter-increment: list-number 1; display: block; margin-bottom: 0px; margin-top: 0px; min-height: 28px; padding-left: 0.375em;"><p style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; margin: 0px;"><span style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; color: var(--tw-prose-bold); font-weight: 600;">Handle Ambiguity:</span></p><ul style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: flex; flex-direction: column; list-style: disc; margin: 0px 0px 0px 1rem; padding: 0px;"><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: block; margin: 0px; min-height: 28px; padding-left: 0.375em;">If your prompt is ambiguous, the model might produce unexpected or undesired results. Clarify your instructions to reduce ambiguity and improve the likelihood of getting the desired output.</li></ul></li><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; counter-increment: list-number 1; display: block; margin-bottom: 0px; margin-top: 0px; min-height: 28px; padding-left: 0.375em;"><p style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; margin: 0px;"><span style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; color: var(--tw-prose-bold); font-weight: 600;">Consider Prompt Engineering Libraries:</span></p><ul style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: flex; flex-direction: column; list-style: disc; margin: 0px 0px 0px 1rem; padding: 0px;"><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: block; margin: 0px; min-height: 28px; padding-left: 0.375em;">Some platforms provide prompt engineering libraries that simplify the process of crafting effective prompts. For example, OpenAI's Playground or other third-party libraries may offer useful tools and examples.</li></ul></li><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; counter-increment: list-number 1; display: block; margin-bottom: 0px; margin-top: 0px; min-height: 28px; padding-left: 0.375em;"><p style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; margin: 0px;"><span style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; color: var(--tw-prose-bold); font-weight: 600;">Stay Ethical:</span></p><ul style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: flex; flex-direction: column; list-style: disc; margin: 0px 0px 0px 1rem; padding: 0px;"><li style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; display: block; margin: 0px; min-height: 28px; padding-left: 0.375em;">Be mindful of ethical considerations when generating content. Avoid prompts that may lead to harmful or inappropriate outputs. Review and filter the generated content to ensure it aligns with ethical guidelines.</li></ul></li></ol><p style="--tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-offset-width: 0px; --tw-ring-shadow: 0 0 transparent; --tw-rotate: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-scroll-snap-strictness: proximity; --tw-shadow-colored: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-skew-x: 0; --tw-skew-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; border: 0px solid rgb(217, 217, 227); box-sizing: border-box; color: #374151; font-family: Söhne, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Ubuntu, Cantarell, "Noto Sans", sans-serif, "Helvetica Neue", Arial, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; font-size: 16px; margin: 1.25em 0px 0px; white-space-collapse: preserve;">Prompt engineering often involves a trial-and-error process. As you experiment and become familiar with the model's behavior, you'll improve your ability to craft effective prompts for generative AI.</p>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com6tag:blogger.com,1999:blog-8136669514202946995.post-7744175545310303962023-12-08T12:19:00.000+05:302023-12-08T12:19:37.250+05:30API rate limiting strategies for Spring Boot applications<p> </p><p><br /></p><p><b>API Rate Limiting</b></p><p> Rate limiting is a strategy to limit access to APIs. </p><p> It restricts the number of API calls that a client can make within a certain time frame. </p><p> This helps defend the API against overuse, both unintentional and malicious.</p><p><br /></p><p>API rate limiting is crucial for maintaining the performance, stability, and security of Spring Boot applications. Here are several rate limiting strategies you can employ:</p><p><br /></p><p><b>1. Fixed Window Counter:</b></p><p>In this strategy, you set a fixed window of time (e.g., 1 minute), and you allow a fixed number of requests within that window. If a client exceeds the limit, further requests are rejected until the window resets. This approach is simple but can be prone to bursts of traffic.</p><p><br /></p><p><b>2. Sliding Window Counter:</b></p><p>A sliding window counter tracks the number of requests within a moving window of time. This allows for a more fine-grained rate limiting mechanism that considers recent activity. You can implement this using a data structure like a sliding window or a queue to track request timestamps.</p><p><br /></p><p><b>3. Token Bucket Algorithm:</b></p><p>The token bucket algorithm issues tokens at a fixed rate. Each token represents permission to make one request. Clients consume tokens for each request, and requests are only allowed if there are available tokens. Google's Guava library provides a RateLimiter class that implements this algorithm.</p><p><br /></p><p><b>4. Leaky Bucket Algorithm:</b></p><p>Similar to the token bucket, the leaky bucket algorithm releases tokens at a constant rate. However, in the leaky bucket, the bucket has a leak, allowing it to empty at a constant rate. Requests are processed as long as there are tokens available. This strategy can help smooth out bursts of traffic.</p><p><b>5. Distributed Rate Limiting with Redis or Memcached:</b></p><p>If your Spring Boot application is distributed, you can use a distributed caching system like Redis or Memcached to store and share rate limiting information among different instances of your application.</p><p><br /></p><p><b>6. Spring Cloud Gateway Rate Limiting:</b></p><p>If you're using Spring Cloud Gateway, it provides built-in support for rate limiting. You can configure rate limiting policies based on various criteria such as the number of requests per second, per user, or per IP address.</p><p><br /></p><p><b>7. User-based Rate Limiting:</b></p><p>Instead of limiting based on the number of requests, you can implement rate limiting on a per-user basis. This is useful for scenarios where different users may have different rate limits based on their subscription level or user type.</p><p><br /></p><p><b>8. Adaptive Rate Limiting:</b></p><p>Implement adaptive rate limiting that dynamically adjusts rate limits based on factors such as server load, response times, or the health of the application. This approach can help handle variations in traffic.</p><p><br /></p><p><b>9.Response Code-based Rate Limiting:</b></p><p>Consider rate limiting based on response codes. For example, if a client is generating a high rate of error responses, you might want to impose stricter rate limits on that client.</p><p><br /></p><p><b>10. API Key-based Rate Limiting:</b></p><p>Tie rate limits to API keys, allowing you to set different limits for different clients or users. This approach is common in scenarios where you have third-party developers using your API.</p>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com3tag:blogger.com,1999:blog-8136669514202946995.post-77399069261761960802023-06-15T14:23:00.002+05:302023-06-15T14:23:31.298+05:30How to install Kong Gateway using Docker
To install Kong Gateway, you can follow these steps: <div><br /></div><div> Step 1: Choose the installation method: </div><div> </div><div> Kong Gateway offers different installation methods depending on your operating system and</div><div> requirements. </div><div><br /></div><div> You can choose from Docker, package managers (e.g., Homebrew, Yum, Apt), or manual installation.</div><div><br /></div><div> For simplicity, let's go with the Docker installation method.</div><div><br /></div><div> Step 2: Install Docker:
If you don't have Docker installed, visit the Docker website</div><div> (https://www.docker.com/)
and follow the instructions to install Docker for your specific</div><div> operating system. </div><div><br /></div><div> Step 3: Pull the Kong Gateway Docker image: </div><div> </div><div> Open a terminal or command prompt.
Run the following command to pull the Kong Gateway</div><div> Docker image from Docker Hub:</div><div><pre class="prettyprint lang-java">docker pull kong/kong-gateway
</pre>
Step 4: Run Kong Gateway container:
Once the image is pulled, run the following command to start a</div><div> Kong Gateway
<pre class="prettyprint lang-java">docker run -d --name kong-gateway \
-e "KONG_DATABASE=off" \
-e "KONG_PROXY_ACCESS_LOG=/dev/stdout" \
-e "KONG_ADMIN_ACCESS_LOG=/dev/stdout" \
-e "KONG_PROXY_ERROR_LOG=/dev/stderr" \
-e "KONG_ADMIN_ERROR_LOG=/dev/stderr" \
-e "KONG_ADMIN_LISTEN=0.0.0.0:8001" \
-e "KONG_PROXY_LISTEN=0.0.0.0:8000" \
-p 8000:8000 \
-p 8001:8001 \
kong/kong-gateway
</pre>
This command starts a Kong Gateway container named "kong-gateway" with the necessary environment variables and port mappings. </div><div><br /></div><div> The -p option maps the container's ports to the host machine, allowing access to Kong Gateway's admin API (port 8001) and proxy API (port 8000). </div><div><br /></div><div> The -e options set various environment variables like the database type (KONG_DATABASE=off disables the database), log configurations, and listen addresses.</div><div><br /></div><div> Step 5: Verify Kong Gateway installation:
After running the container, wait for a few moments to allow</div><div> Kong Gateway to initialize. </div><div><br /></div><div><br /></div><div>You can check the logs of the container using the following command:
<pre class="prettyprint lang-java">docker logs kong-gateway
</pre>
Look for any error messages or indications that Kong Gateway has started successfully. </div><div><br /></div><div><br /></div><div> Step 6: Access Kong Gateway admin API: </div><div><br /></div><div> Once Kong Gateway is running, you can access its admin API to configure and manage your Kong Gateway instance. </div><div><br /></div><div>Open a web browser and go to http://localhost:8001. You should see the Kong Gateway admin API homepage if everything is working correctly.</div><div><br /></div><div> Congratulations! You have successfully installed Kong Gateway using Docker. </div><div><br /></div><div>You can now proceed with configuring Kong Gateway and integrating it with your applications as needed
</div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com0tag:blogger.com,1999:blog-8136669514202946995.post-49294632673592012552023-05-01T12:21:00.005+05:302023-05-01T12:24:17.721+05:30How to Implement Image classification using TensorFlow maven and JavaHere is an example of using TensorFlow with Java and Maven to perform image classification: <div><br /></div><div> 1.Create a new Maven project in your favorite IDE. <div><br /></div><div> 2. Add the TensorFlow Java dependency to your project by adding the following to your pom.xml file:
<pre class="prettyprint lang-java">
<dependencies>
<dependency>
<dependencies>
<dependency>
<groupId>org.tensorflow</groupId>
<artifactId>tensorflow</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
</dependency>
</dependencies>
</pre>
3. Create a new class, for example ImageClassifier.java, and add the following code:
<pre class="prettyprint lang-java">import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.tensorflow.DataType;
import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.TensorFlow;
public class ImageClassifier {
private static byte[] loadImage(String path) throws IOException {
BufferedImage img = ImageIO.read(new File(path));
int height = img.getHeight();
int width = img.getWidth();
int channels = 3;
byte[] data = new byte[height * width * channels];
int pixel = 0;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int rgb = img.getRGB(j, i);
data[pixel++] = (byte) ((rgb >> 16) & 0xFF);
data[pixel++] = (byte) ((rgb >> 8) & 0xFF);
data[pixel++] = (byte) (rgb & 0xFF);
}
}
return data;
}
public static void main(String[] args) throws Exception {
// Load the TensorFlow library
try (Graph g = new Graph()) {
byte[] graphBytes = TensorFlowModelLoader.load("path/to/model.pb");
g.importGraphDef(graphBytes);
// Create a new session to run the graph
try (Session s = new Session(g)) {
// Load the image data
String imagePath = "path/to/image.jpg";
byte[] imageBytes = loadImage(imagePath);
// Create a tensor from the image data
Tensor inputTensor = Tensor.create(new long[]
{1, imageBytes.length}, ByteBuffer.wrap(imageBytes));
// Run the graph on the input tensor
Tensor outputTensor = s.runner()
.feed("input", inputTensor)
.fetch("output")
.run()
.get(0);
// Print the predicted label
DataType outputDataType = outputTensor.dataType();
long[] outputShape = outputTensor.shape();
Object[] output = new Object[outputTensor.numElements()];
outputTensor.copyTo(output);
System.out.println("Prediction: " + output[0]);
}
}
}
}
</pre>
4. Replace the path/to/model.pb and path/to/image.jpg with the actual paths to your model and image files. </div><div><br /></div><div> 5. Run the ImageClassifier class, and it should print out the predicted label for the input image.
</div></div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com2tag:blogger.com,1999:blog-8136669514202946995.post-2161193188636211482023-04-13T11:03:00.002+05:302023-04-13T11:05:22.370+05:30How to create key cloak authentication server and spring bootTo create a Keycloak authentication server, you need to follow these steps: <div><br /></div><div> 1. Download and Install Keycloak: You can download Keycloak from the official website </div><div> <a href="https://www.keycloak.org/downloads.html">https://www.keycloak.org/downloads.html</a>.</div><div><br /></div><div> Follow the installation instructions provided in the documentation. </div><div><br /></div><div> 2. Configure Keycloak: Once installed, you need to configure Keycloak by creating a new realm. </div><div> A realm is a container for all the users, roles, and groups in your application.</div><div><br /></div><div> To create a new realm, log in to the Keycloak admin console using the default credentials</div><div> (admin/admin), then follow these steps:</div><div><br /></div><div> Click on the "Add Realm" button and provide a name for your realm. </div><div><br /></div><div> Configure your realm settings, including themes, email settings, and login settings. </div><div><br /></div><div> Create users and groups within your realm and assign roles to them. </div><div><br /></div><div> 3. Set Up Your Spring Boot Application: You can use the Keycloak Spring Boot Starter dependency to</div><div> add Keycloak authentication to your Spring Boot application.</div><div><br /></div><div> Add the following dependency to your Maven or Gradle build file:
<pre class="prettyprint lang-java"><dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>
</dependency>
</pre>
4. Configure Your Spring Boot Application: You need to configure your Spring Boot application to</div><div> connect to the Keycloak server. </div><div><br /></div><div> You can do this by adding the following properties to your application.properties or application.yml file:
<pre class="prettyprint lang-java">keycloak.auth-server-url=<keycloak-server-url>
keycloak.realm=<keycloak-realm>
keycloak.resource=<keycloak-client-id>
keycloak.credentials.secret=<keycloak-client-secret>
</pre><div><br /></div> Replace <keycloak-server-url>, <keycloak-realm>, <keycloak-client-id>, </div><div> and <keycloak-client-secret> with the appropriate values for your Keycloak instance.</div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret><br /></keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret> 5. Secure Your Spring Boot Application: You can secure your Spring Boot application by adding the</keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret> Keycloak configuration to your Spring Security configuration. </keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret><br /></keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret> You can do this by creating a new class that extends KeycloakWebSecurityConfigurerAdapter and</keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret> override the configure method. </keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret><br /></keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret>Here's an example:
<pre class="prettyprint lang-java">@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(keycloakAuthenticationProvider());
}
@Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests().antMatchers("/admin/**").hasRole("admin")
.antMatchers("/user/**").hasAnyRole("user", "admin")
.anyRequest().permitAll();
}
}
</pre> This configuration class enables Keycloak authentication and authorization for specific URLs in the</keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret> application.</keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret><br /></keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret> 6. Test Your Application: You can test your application by running it and accessing the protected URLs.</keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret> When a user tries to access a protected resource, they will be redirected to the Keycloak login page.</keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret> Once they successfully authenticate, they will be redirected back to the original resource. </keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret><br /></keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div><div><keycloak-server-url><keycloak-realm><keycloak-client-id><keycloak-client-secret>That's it! we have created a Keycloak authentication server and secured your Spring Boot application with it.</keycloak-client-secret></keycloak-client-id></keycloak-realm></keycloak-server-url></div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com4tag:blogger.com,1999:blog-8136669514202946995.post-21264905880982477792023-04-12T19:46:00.001+05:302023-04-12T19:49:28.391+05:30How to build video conference using spring bootTo build a video conference application using Spring Boot, you can follow these steps: <div><br /></div><div> 1. Choose a video conferencing API: There are several video conferencing APIs available such as Twilio, Agora, Zoom, Jitsi, etc. Choose an API that best fits your requirements. </div><div><br /></div><div> 2. Set up a Spring Boot project: Create a new Spring Boot project using your preferred IDE or by using Spring Initializr. </div><div><br /></div><div> 3. Add the video conferencing API dependencies: Add the necessary dependencies for the chosen API in your project's pom.xml file.</div><div><br /></div><div> 4. Configure the video conferencing API: Configure the video conferencing API with the required credentials and other settings in your Spring Boot application's configuration file.</div><div><br /></div><div> 5. Implement the video conferencing features: Use the API's SDK to implement the video conferencing features such as creating a conference room, joining a room, leaving a room, etc. </div><div><br /></div><div> 6. Integrate the video conferencing features with your application: Add the necessary controllers and views to your Spring Boot application to integrate the video conferencing features with your application. </div><div><br /></div><div> 7. Test the application: Test the application thoroughly to ensure that the video conferencing features are working as expected. </div><div><br /></div><div> Here's a sample code for a video conference application using Spring Boot and the Twilio Video API:</div><div> 1. Add the Twilio Video API dependency to your pom.xml file:
<pre class="prettyprint lang-xml"><dependency>
</dependency>
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>7.54.0</version>
</dependency>
</pre>
2. Add the required Twilio credentials and settings to your Spring Boot application's application.properties file
<pre class="prettyprint lang-java">twilio.account.sid=your_account_sid
twilio.auth.token=your_auth_token
twilio.api.key=your_api_key
twilio.api.secret=your_api_secret
twilio.video.room.max-participants=4
</pre>
3. Implement a controller for creating and joining a video conference room:
<pre class="prettyprint lang-java">@RestController
public class VideoConferenceController {
@Autowired
private TwilioConfig twilioConfig;
@PostMapping("/room")
public ResponseEntity<roomresponse> createRoom() throws Exception {
RoomCreator roomCreator = Room.creator()
.setUniqueName(UUID.randomUUID().toString())
.setType(RoomType.PEER_TO_PEER)
.setStatusCallback(twilioConfig.getStatusCallback())
.setMaxParticipants(twilioConfig.getMaxParticipants());
Room room = roomCreator.create();
RoomResponse response = new RoomResponse();
response.setRoomId(room.getSid());
response.setRoomName(room.getUniqueName());
response.setToken(createAccessToken(room.getSid()));
return ResponseEntity.ok(response);
}
@GetMapping("/room/{roomId}/token")
public ResponseEntity<string>
getRoomToken(@PathVariable("roomId") String roomId) {
String accessToken = createAccessToken(roomId);
return ResponseEntity.ok(accessToken);
}
private String createAccessToken(String roomId) {
VideoGrant grant = new VideoGrant();
grant.setRoom(roomId);
AccessToken token = new AccessToken.Builder(
twilioConfig.getAccountSid(),
twilioConfig.getApiKey(),
twilioConfig.getApiSecret()
).identity(UUID.randomUUID().toString())
.grant(grant)
.build();
return token.toJwt();
}
}
</string></roomresponse></pre>
4.Define a configuration class for the Twilio settings:
<pre class="prettyprint lang-java">@ConfigurationProperties(prefix = "twilio")
@Data
public class TwilioConfig {
private String accountSid;
private String authToken;
private String apiKey;
private String apiSecret;
private String statusCallback;
private int maxParticipants;
}
</pre>
5.Configure the Twilio settings in your Spring Boot application's application.yml file:
<pre class="prettyprint lang-java">twilio:
account-sid: your_account_sid
auth-token: your_auth_token
api-key: your_api_key
api-secret: your_api_secret
status-callback: http://localhost:8080/callback
max-participants: 4
</pre>
6. Run your Spring Boot application and test the video conference feature by creating and joining a room using the API endpoints.
</div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com0tag:blogger.com,1999:blog-8136669514202946995.post-31545517097229702792023-03-14T11:05:00.001+05:302023-03-14T11:08:18.463+05:30Oracle Cloud Infrastructure- Object storage exampleThis post will explain, how we can create bucket and configure notification and rules and object storage like create/update object.
Login into OCI using login credentials . if you don't have a account please create the same using this link <a href="https://www.oracle.com/cloud/sign-in.html" target="_blank">https://www.oracle.com/cloud/sign-in.html</a>
Once you create account and successful login, Now we need to create a bucket.
search for bucket and create a bucket
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEghHDFnkSD6oghj8p_gKDcL35zcZYIQrCJlpkCLNFYM3aJ31IREbYRehb42YVBxU3no82cyxk0WbFP2hbPBECRiuX8pniRavdaGbhmrNYVLe-n3sue2Q2Qofs5WGd8BNuFa3UiBemRUKmCeUrObszHLo8RsFfN5aW6XApA0DlRzJeoUlgs8datVcPfr/s1596/bucket_creation.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="" border="0" width="320" data-original-height="827" data-original-width="1596" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEghHDFnkSD6oghj8p_gKDcL35zcZYIQrCJlpkCLNFYM3aJ31IREbYRehb42YVBxU3no82cyxk0WbFP2hbPBECRiuX8pniRavdaGbhmrNYVLe-n3sue2Q2Qofs5WGd8BNuFa3UiBemRUKmCeUrObszHLo8RsFfN5aW6XApA0DlRzJeoUlgs8datVcPfr/s320/bucket_creation.png"/></a></div>
After creating bucket now we can create a topic
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUrnwny-bo0dMjhyyqsskqXaegnBab1ak1zfUeL79rCpvNbQ0BJzygLYo5nclZdcTK_c-XhyNmPQ22MzcVJxhexuwmBF1RRxnxkx97dQTSeT9JXoYz5FZvLII3r09IfQjzAInio664YY4cZ9ocM2_geX_ssYtiDXALvXQEkG4JMnxycCIV8fngHJv1/s1591/topic_create.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="" border="0" width="320" data-original-height="806" data-original-width="1591" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUrnwny-bo0dMjhyyqsskqXaegnBab1ak1zfUeL79rCpvNbQ0BJzygLYo5nclZdcTK_c-XhyNmPQ22MzcVJxhexuwmBF1RRxnxkx97dQTSeT9JXoYz5FZvLII3r09IfQjzAInio664YY4cZ9ocM2_geX_ssYtiDXALvXQEkG4JMnxycCIV8fngHJv1/s320/topic_create.png"/></a></div>
Now we can create notification, after uploading file , we should get email
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjl88K7CSWF5O-StAt6Kp-IiT4B7fUNgh1D7SusCyln8opsZHjGqHJGnwaXeKYSX65x1YYgkMumMDgaE0luvLKkSJGvQmGDuorejej44r32k4BgLN5NAoXPLdyf9eN9YZ6TY6OODs6zkiT19UOLuwamB6mqy_-jSfVuavf99LXfP2NvuUFkEbuTodcW/s1586/notification_create.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="" border="0" width="320" data-original-height="807" data-original-width="1586" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjl88K7CSWF5O-StAt6Kp-IiT4B7fUNgh1D7SusCyln8opsZHjGqHJGnwaXeKYSX65x1YYgkMumMDgaE0luvLKkSJGvQmGDuorejej44r32k4BgLN5NAoXPLdyf9eN9YZ6TY6OODs6zkiT19UOLuwamB6mqy_-jSfVuavf99LXfP2NvuUFkEbuTodcW/s320/notification_create.png"/></a></div>
Create a Rule to process this
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgoPHGHI6kz7pXx2hPHgsJGOgKm6Uajo3eKzTlEg0bH8dtLI1QBcNTK_wb2XpZ5oTiJWlw_7JsG2pO1iKkT8tAgJurrEq7haMglGrf5UHIvcFZBV4piKzSNZS334fzVTtHrhMd6ykvCeDkh_te_PNk703f4KfunqPL_1TtvBWiXopgMjDyzTMuKWgrT/s1589/rule_create.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="" border="0" width="320" data-original-height="794" data-original-width="1589" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgoPHGHI6kz7pXx2hPHgsJGOgKm6Uajo3eKzTlEg0bH8dtLI1QBcNTK_wb2XpZ5oTiJWlw_7JsG2pO1iKkT8tAgJurrEq7haMglGrf5UHIvcFZBV4piKzSNZS334fzVTtHrhMd6ykvCeDkh_te_PNk703f4KfunqPL_1TtvBWiXopgMjDyzTMuKWgrT/s320/rule_create.png"/></a></div>
Once we create all then , once we upload file in object storage , then we should get email like below
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8oWRIUfQvlswR8-xHj1TNZ0y5AiEcESuGWVFv-DqIPdZShvRLAG8SzuPssPG7WCZIdyx7InZTjLNVB7TNiEcCwGXRty9HdktbvKPTHmSjTnYGs0x2ysuw-2RoGe0ftvOuXx6_rMa_4GRbXGIRR0Qe8L1UBsbqO8fBimeyEQ9HM-0shiYVnaLzI7be/s1296/email_response.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="" border="0" width="320" data-original-height="740" data-original-width="1296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8oWRIUfQvlswR8-xHj1TNZ0y5AiEcESuGWVFv-DqIPdZShvRLAG8SzuPssPG7WCZIdyx7InZTjLNVB7TNiEcCwGXRty9HdktbvKPTHmSjTnYGs0x2ysuw-2RoGe0ftvOuXx6_rMa_4GRbXGIRR0Qe8L1UBsbqO8fBimeyEQ9HM-0shiYVnaLzI7be/s320/email_response.png"/></a></div>
This shows we can send email, but we can configure with different ways like queues.
Here we will get the details in mail . But if we want complete object details, then we can use java code to retrieve the object details by calling the API which required namespace details ,bucket name and object name.
<pre class="prettyprint lang-java">
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Paths;
import java.util.List;
import com.oracle.bmc.objectstorage.ObjectStorage;
import com.oracle.bmc.objectstorage.ObjectStorageClient;
import com.oracle.bmc.objectstorage.model.GetObjectRequest;
import com.oracle.bmc.objectstorage.model.ObjectStream;
import com.oracle.bmc.objectstorage.model.Range;
import com.oracle.bmc.objectstorage.requests.GetObjectRequest;
import com.oracle.bmc.objectstorage.responses.GetObjectResponse;
public class LogFileRetriever {
public static void main(String[] args) {
String namespaceName = "mynamespace";
String bucketName = "mybucket";
String objectName = "mylogfile.txt";
// Create a new Object Storage client
ObjectStorage objectStorageClient = ObjectStorageClient.builder()
.build(objectStorageConfig);
GetObjectRequest request = GetObjectRequest.builder()
.namespaceName(namespaceName)
.bucketName(bucketName)
.objectName(objectName)
.build();
GetObjectResponse response = objectStorageClient.getObject(request);
// Get the InputStream from the response
InputStream logFileInputStream = response.getInputStream();
// Write the InputStream to a local file
OutputStream logFileOutputStream =
new FileOutputStream(Paths.get("logfile.txt").toFile());
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = logFileInputStream.read(buffer)) != -1) {
logFileOutputStream.write(buffer, 0, bytesRead);
}
logFileOutputStream.close();
}
}
</pre>
Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com0tag:blogger.com,1999:blog-8136669514202946995.post-74978442359471041452022-03-14T15:35:00.005+05:302022-07-14T11:26:09.688+05:30How to call REST API Using Spring Webflux WebClient set proxy with authorization while calling the external site and Generate base 64 authentication header spring boot
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-6620984457849969"
crossorigin="anonymous"></script>
This post will explain us, how can we call REST API using Webclient.
How to set Proxy username and password to call the external site.
Step 1: Add folllowing dependency in your pom.xml
<pre class="prettyprint lang-java">
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</pre>
Step 2:
<pre class="prettyprint lang-java">
import lombok.extern.slf4j.XSlf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.reactive.ClientHttpConnector;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import reactor.netty.transport.ProxyProvider;
import java.net.URI;
import java.util.Base64;
import java.util.function.Consumer;
import java.util.function.Function;
public static void main(String[] args) {
try {
//Generate HttP client to set proxy details
HttpClient httpClient = HttpClient.create()
.proxy(proxy-> proxy.type(ProxyProvider.Proxy.HTTP)
.host("javaguruonline.com").port(1328)
.username("siva")
.password(new Function<String, String>() {
@Override
public String apply(String s) {
return "test@12!";
}
}));
ClientHttpConnector clientHttpConnector =
new ReactorClientHttpConnector(httpClient);
WebClient webClient = WebClient.builder().build();
String plainCredentials = "username" + ":" + "password";
String base64Credentials = new String(Base64.getEncoder()
.encode(plainCredentials.getBytes()));
String authorizationHeader = "Basic " + base64Credentials;
//input json
String json = "{\n" +
" \"user\": \"siva\"\n" +
"}";
//set http headers
Consumer<HttpHeaders> httpHeaders = new Consumer<HttpHeaders>() {
@Override
public void accept(HttpHeaders httpHeaders) {
httpHeaders.add("Authorization", authorizationHeader);
httpHeaders.add("Content-Type", "application/json");
httpHeaders.add("Proxy-Authorization", authorizationHeader);
}};
//post call to external URL and get ResponseEntity as response like body
//and http status code etc..
ResponseEntity<String> result = webClient.mutate()
.clientConnector(clientHttpConnector)
.build()
.post()
.uri(new URI("https://localhost:8080/test/details"))
.bodyValue(json)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.toEntity(String.class)
.block();
System.out.println(result);
}
catch(Exception ex){
}
</pre>
Hope this post will help some one, while working on the REST API calls
Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com0tag:blogger.com,1999:blog-8136669514202946995.post-69955025371635089482021-03-11T06:41:00.005+05:302022-07-14T11:27:11.510+05:30How to mock ResultSet , NamedParameterJdbcTemplate , RowMapper<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-6620984457849969"
crossorigin="anonymous"></script>
<pre class="prettyprint lang-java">
package com.siva.springboot.javaguruonline.repository;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import com.siva.springboot.javaguruonline.model.EmployeeDetails;
@RunWith(SpringRunner.class)
/**
*
* @author Siva
*
*/
//@SpringBootTest(classes = SpringbootJpaSwaggerSonarqubeApplication.class)
public class EmployeeDaoImplTest {
@InjectMocks
public EmployeeDaoImpl employeeDao;
@Mock
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@SuppressWarnings("unchecked")
@Test
public void testGetAllEmployeeDetails(){
List<EmployeeDetails> list = new ArrayList<EmployeeDetails>();
EmployeeDetails employeeDetails = new EmployeeDetails();
employeeDetails.setEmpId(1);
employeeDetails.setEmpName("siva");
list.add(employeeDetails);
Mockito.when(namedParameterJdbcTemplate.query(Mockito.anyString(),
Mockito.any(RowMapper.class)))
.thenAnswer(new Answer<List<EmployeeDetails>>() {
@Override
public List<EmployeeDetails> answer(InvocationOnMock invocation)
throws Throwable {
// Fetch the method arguments
Object[] args = invocation.getArguments();
// Fetch the row mapper instance from the arguments
RowMapper<EmployeeDetails> rm = (RowMapper<EmployeeDetails>) args[1];
// Create a mock result set and setup an expectation on it
ResultSet rs = Mockito.mock(ResultSet.class);
Mockito.when(rs.getInt("emp_id")).thenReturn(employeeDetails.getEmpId());
Mockito.when(rs.getString("emp_name")).thenReturn(employeeDetails.getEmpName());
// Invoke the row mapper
EmployeeDetails actual = rm.mapRow(rs, 0);
// Assert the result of the row mapper execution
Assert.assertEquals(employeeDetails.getEmpName(), actual.getEmpName());
// Return your created list for the template#query call
return list;
}
});
employeeDao.getEmployeeDetails();
Assert.assertNotNull(list);
}
}
</pre>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com14tag:blogger.com,1999:blog-8136669514202946995.post-74118277833470321792020-08-27T17:35:00.002+05:302022-07-14T11:27:34.560+05:30Getting started with Chatbot using java and response in text to speech -- Java simple chatbot and text to speech<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-6620984457849969"
crossorigin="anonymous"></script>
This will explain you about , how we can write simple chatbot using java and read the bot response into speech <div><br /></div><div> Step 1: Download sample program-ab from the below archive folder
<a href=" https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/program-ab/program-ab-0.0.4.3.zip"><b>Program-ab</b></a> <div><br /></div><div> Step 2: Unzip the downloaded folder. </div><div><br /></div><div> Step 3: Create java maven project using any IDE or console application</div><div><br /></div><div> Step 4: Copy Ab.jar (Which is there in the unzipped folder lib in step 2) add to the classpath </div><div><br /></div><div> Step 5: Copy bots folder (which is available in the unzipped folder) it has all the aiml files, which bot act upon our request and give the response</div><div><br /></div><div> Step 6: Now we need to give bot response in speech</div><div><br /></div><div> Step 7: Download freetss from the given link
<a href="http://sourceforge.net/project/showfiles.php?group_id=42080"><b>FREETTS</b></a> </div><div><br /></div><div> Step 8: Unzip the downloaded folder and go to \freetts-1.2.2-bin\freetts-1.2\lib folder </div><div><br /></div><div> Step 9: Run the <b>jsapi.exe</b> file- It will generate multiple jars</div><div><br /></div><div> Step 10: copy that jars and place it in the classpath of the java project </div><div><br /></div><div> Step 11: Once above steps completed then, we can write simple java program as follows
<pre class="prettyprint lang-java">package com.siva;
import java.io.File;
import java.util.Locale;
import java.util.Scanner;
import javax.speech.Central;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;
import org.alicebot.ab.AB;
import org.alicebot.ab.Bot;
import org.alicebot.ab.Chat;
import org.alicebot.ab.MagicBooleans;
import org.alicebot.ab.utils.IOUtils;
public class TestChatbot {
private static final boolean TRACE_MODE = false;
static String botName = "super";
public static void main(String[] args) {
try {
String aimlResourcesPath = getResourcesPath();
System.out.println(aimlResourcesPath);
MagicBooleans.trace_mode = TRACE_MODE;
Bot bot = new Bot("super", aimlResourcesPath);
Chat chatSession = new Chat(bot);
AB.ab(bot);
Scanner sc=new Scanner(System.in);
String request = "Hai";
do{
request = IOUtils.readInputTextLine();
String response = chatSession.multisentenceRespond(request);
// Set property as Kevin Dictionary
System.setProperty(
"freetts.voices",
"com.sun.speech.freetts.en.us"
+ ".cmu_us_kal.KevinVoiceDirectory");
// Register Engine
Central.registerEngineCentral(
"com.sun.speech.freetts"
+ ".jsapi.FreeTTSEngineCentral");
// Create a Synthesizer
Synthesizer synthesizer
= Central.createSynthesizer(
new SynthesizerModeDesc(Locale.US));
// Allocate synthesizer
synthesizer.allocate();
// Resume Synthesizer
synthesizer.resume();
// Speaks the given text
// until the queue is empty.
synthesizer.speakPlainText(
response, null);
synthesizer.waitEngineState(
Synthesizer.QUEUE_EMPTY);
System.out.println(response);
}while(!request.equals("exit"));
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getResourcesPath() {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
path = path.substring(0, path.length() - 2);
System.out.println(path);
String resourcesPath = path + File.separator + "src"
+ File.separator + "main" + File.separator + "resources";
return resourcesPath;
}
}
</pre>
Step 12: Once code completed , then run the java program , type the input like Hai, hello and date, there are so many QA mentioned in imal files. and we can also write our own aiml file, for reference, you can verify under boats/aiml folder
</div><div><br /></div><div>Step 13: output will print in console and it will read the boat response.. </div><div><br /></div><div> Step 14: Out put will be like below image. </div><div><br /></div><div><br /></div><div> Thanks for viewing this post.
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgcdCtqjBeMUAPm7jpFLTg9VuOPD-Dh3cngaEdGISgK_b5_kuGo2N8jSWtHOhl3rTIVYgShpbu6lPQ8Wrf3lMVct4oD1D20ByZSwFRXOyHgAZy3tzkPCQ7cJzt54J2-AhPo0RsfU5be8Yw/s1599/aimltts.PNG" style="display: block; padding: 1em 0px; text-align: none;"><img alt="" border="0" data-original-height="850" data-original-width="1599" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgcdCtqjBeMUAPm7jpFLTg9VuOPD-Dh3cngaEdGISgK_b5_kuGo2N8jSWtHOhl3rTIVYgShpbu6lPQ8Wrf3lMVct4oD1D20ByZSwFRXOyHgAZy3tzkPCQ7cJzt54J2-AhPo0RsfU5be8Yw/s320/aimltts.PNG" width="320" /></a></div></div></div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com0tag:blogger.com,1999:blog-8136669514202946995.post-45299630072487887982020-07-24T13:14:00.001+05:302020-07-24T13:14:12.815+05:30Angular with Spring boot Getting started with Angular and Spring boot<div dir="ltr" style="text-align: left;" trbidi="on"><br />
This post will explain , how we can integrate spring boot rest api in angular js<br />
<br />
Step 1 : We need to install angular js<br />
<br />
Follow the steps to mention in the angular web site <a href="https://angular.io/guide/setup-local"> Angular set up</a><br />
<br />
Basic commands used in angular application<br />
<b>npm install -g @angular/cli </b><br />
<br />
Create a new angular js application<br />
<br />
ng new employee-crud-client<br />
<br />
<br />
Once application created then, now we need to create components, services, model classes to integrate with spring boot<br />
<br />
Step 2: to create component - Go to src/app folder in command prompt<br />
<br />
<br />
ng g c employee-list<br />
<br />
We can write our entire crud operations logic inside employee-list component or we can create different components for different operations.<br />
<br />
Once we create component , there were 4 files created <br />
<br />
1. employee-list.component.ts - logic related to how to form request and after getting the response from service- spring boot api, how to massage and send it to ui<br />
2. employee-list.component.html - plain html with angular script to display/action with response or user input<br />
3. employee-list.component.spec<br />
4. employee-list.component.css<br />
<br />
Step 3: Once the above files created and now we need to configure these with angular components<br />
<br />
<br />
1. app.module.ts - will have the components, which we created<br />
2. app-routing.module.ts- will have the path details, to which path has to call the which component<br />
3. app.component.html - will have the router-outlet, which internally call the routing-module and which will call the app.modules.ts<br />
<br />
Step 4: This is important step, service to be created, which calls the spring boot api<br />
<br />
<b>ng g s employee</b><br />
<br />
employee.service file will be created<br />
<br />
this service consists of the logic , how we can call the rest api methods, This is called from the employee-list.component.ts <br />
<br />
<br />
Step 5: We will create model class, it should be same like our pojo class in java<br />
<br />
<b> ng g class employee</b><br />
<br />
<br />
Step 6: Once all the steps completed, then now we need to run the angular client.<br />
<br />
<br />
ng serve<br />
ng serve --open If there is no errors, then page directly will open in browser http://localhost:4200<br />
<br />
<br />
Step 7 : For spring boot api application, see my previous employee crud operations with spring boot post.<br />
<br />
<br />
Step 8: This way we can integrate our spring boot application with angular.<br />
<br />
Thanks for viewing this post, if you have any difficulty while integration, please comment the same.<br />
<br />
</div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com0tag:blogger.com,1999:blog-8136669514202946995.post-24457893400556271712020-07-24T12:28:00.001+05:302020-07-24T12:28:33.528+05:30Convert Date to Number and Number to Date in Oracle<div dir="ltr" style="text-align: left;" trbidi="on"><br />
<br />
How we can convert date to number in oracle<br />
<br />
select to_number(to_char(add_months(sysdate,-0),'yyyymm')) from dual;<br />
<br />
How we can convert number to date<br />
<br />
select to_char(to_date(202007,'yyyymm'),'dd-mon-yyyy') from dual;<br />
<br />
<br />
</div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com1tag:blogger.com,1999:blog-8136669514202946995.post-44019534260156899872020-03-22T12:25:00.001+05:302020-07-11T21:08:32.519+05:30Spring Boot with Swagger UI , JPA , MYSQL , Mockito, Integration Test and Sonar Qube<div dir="ltr" style="text-align: left;" trbidi="on"><br />
<br />
This post will expain you about <br />
1. How we will integrate spring boot and swagger api<br />
2. Spring boot with JPA and MySQL (Crud Repository and NamedJdbcTemplate)<br />
3 Spring mockMvc test for controller <br />
4. Integration test for Service and DAO classes<br />
5. Usage of Mockito<br />
6. Sonarqube Code coverage<br />
<br />
Step 1 : create a maven project called - springboot-jpa-swagger-mysql-sonarqube in eclipse<br />
Step 2 : provide groupId,artifactId,version,jar,name and description<br />
Step 3: Replace below pom.xml into your local system<br />
pom.xml will have dependencies related to spring boot,swagger,jdbc,mysql,mockito,sonarqube<br />
<br />
<pre class="brush:xml"><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.siva.springboot.javaguruonline</groupId>
<artifactId>springboot-jpa-swagger-mysql-sonarqube</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-jpa-swagger-mysql-sonarqube</name>
<description>Demo project for Spring Boot PJA MySQL AND Sonarqube</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.sonarsource.scanner.maven/sonar-maven-plugin -->
<dependency>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.0.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.0</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
</pre>Step 4: Now create a Springboot application, which is the starting point to run the Application.<br />
<br />
Step 5: create <b>appliaction.properties</b> under resources folder, add the db related details<br />
<pre class="prettyprint lang-java">## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/employee
spring.datasource.username = root
spring.datasource.password = root
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
logging.level.root = DEBUG
spring.main.banner-mode=off
spring.datasource.platform=h2
</pre><br />
<br />
<br />
<br />
Step 5: Create a SwaggerConfig class, which will have the details , what is controller package and other details<br />
Learn more about Swagger API <a href="https://swagger.io/tools/swagger-ui/">swagger-ui</a><br />
<br />
<pre class="prettyprint lang-java">package com.siva.springboot.javaguruonline.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors
.basePackage("com.siva.springboot.javaguruonline.controller"))
.paths(PathSelectors.regex("/.*"))
.build().apiInfo(apiEndPointsInfo());
}
private ApiInfo apiEndPointsInfo() {
return new ApiInfoBuilder().title("Spring Boot REST API")
.description("Employee Management REST API")
.contact(new Contact("Siva Raju", "http://www.javaguruonline.com", "siva82k@gmail.com"))
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.version("1.0.0")
.build();
}
}
</pre><br />
Step 6 : This project is related to employee management system - like Employee CRUD operations<br />
<br />
Step 7 : Write Model class called Employee and EmployeeDetails<br />
<br />
<pre class="prettyprint lang-java">package com.siva.springboot.javaguruonline.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@Entity
@Table(name = "employee")
@ApiModel(description="All details about the Employee. ")
@ToString
@EqualsAndHashCode
public class Employee implements Serializable{
/**
*
*/
private static final long serialVersionUID = 7407317371057056536L;
@ApiModelProperty(notes = "The database generated employee ID")
private int id;
@ApiModelProperty(notes = "The employee name")
private String name;
@ApiModelProperty(notes = "The employee age")
private int age;
public Employee() {
}
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "emp_id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "emp_name", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "email_age", nullable = false)
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
</pre><pre prettyprint lang-java>package com.siva.springboot.javaguruonline.model;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@ToString
@EqualsAndHashCode
public class EmployeeDetails {
private int empId;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
private String empName;
}
</pre><br />
Step 8: Step 8: service/serviceimpl and repository classes<br />
<br />
In the repository class, It is extending the <b>JpaRepository</b>, which will get all the default methods related to that Model Object.<br />
In the DAO class, <b>NamedParameterJdbcTemplate </b>, to work with native query and how to map using rowmapper<br />
<br />
<pre class="prettyprint lang-java">package com.siva.springboot.javaguruonline.repository;
import java.util.List;
import com.siva.springboot.javaguruonline.model.EmployeeDetails;
public interface EmployeeDao {
public List<employeedetails> getEmployeeDetails();
}
</pre><pre class="prettyprint lang-java">package com.siva.springboot.javaguruonline.repository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import com.siva.springboot.javaguruonline.mapper.EmployeeDetailsMapper;
import com.siva.springboot.javaguruonline.model.EmployeeDetails;
@Repository
public class EmployeeDaoImpl implements EmployeeDao{
String sqlQuery="select emp_id,emp_name from employee";
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Override
public List<employeedetails> getEmployeeDetails() {
return namedParameterJdbcTemplate.query(sqlQuery, new EmployeeDetailsMapper());
}
}
</pre><br />
<pre class="prettyprint lang-java">package com.siva.springboot.javaguruonline.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.siva.springboot.javaguruonline.model.EmployeeDetails;
public class EmployeeDetailsMapper implements RowMapper<employeedetails> {
@Override
public EmployeeDetails mapRow(ResultSet resultset, int count) throws SQLException {
EmployeeDetails employeeDetails = new EmployeeDetails();
employeeDetails.setEmpId(resultset.getInt("emp_id"));
employeeDetails.setEmpName(resultset.getString("emp_name"));
return employeeDetails;
}
}
</pre><br />
<pre class="prettyprint lang-java">package com.siva.springboot.javaguruonline.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.siva.springboot.javaguruonline.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}
</pre><br />
<br />
Step 9: Write Controller class, which will have the all the crud operations<br />
<pre class="prettyprint lang-java">package com.siva.springboot.javaguruonline.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.siva.springboot.javaguruonline.exception.ResourceNotFoundException;
import com.siva.springboot.javaguruonline.model.Employee;
import com.siva.springboot.javaguruonline.model.EmployeeDetails;
import com.siva.springboot.javaguruonline.repository.EmployeeDao;
import com.siva.springboot.javaguruonline.repository.EmployeeRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@RestController
@RequestMapping("/api/v1")
@Api(value="Employee Management System")
public class EmployeeController {
private static final String EMPLOYEE_NOT_FOUND_FOR_THIS_ID = "Employee not found for this id :: ";
@Autowired
private EmployeeRepository employeeRepository;
@Autowired
private EmployeeDao employeeDao;
@ApiOperation(value = "View a list of available employees", response = List.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully retrieved list"),
@ApiResponse(code = 401, message = "You are not authorized to view the resource"),
@ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
@ApiResponse(code = 404, message = "The resource you were trying to reach is not found") })
@GetMapping("/employees")
public List<employee> getAllEmployees() {
return employeeRepository.findAll();
}
@ApiOperation(value = "View a list of available employee details", response = List.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully retrieved list"),
@ApiResponse(code = 401, message = "You are not authorized to view the resource"),
@ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
@ApiResponse(code = 404, message = "The resource you were trying to reach is not found") })
@GetMapping("/employeedetails")
public List<employeedetails> getAllEmployeeDetails() {
return employeeDao.getEmployeeDetails();
}
@ApiOperation(value = "Get an employee by Id")
@GetMapping("/employees/{id}")
public ResponseEntity<employee> getEmployeeById(
@ApiParam(value = "Employee id from which employee object will retrieve", required = true)
@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException(EMPLOYEE_NOT_FOUND_FOR_THIS_ID + employeeId));
return ResponseEntity.ok().body(employee);
}
@ApiOperation(value = "Add an employee")
@PostMapping("/employees")
public Employee createEmployee(
@ApiParam(value = "Employee object store in database table", required = true)
@Valid @RequestBody Employee employee) {
return employeeRepository.save(employee);
}
@ApiOperation(value = "Update an employee")
@PutMapping("/employees/{id}")
public ResponseEntity<employee> updateEmployee(
@ApiParam(value = "Employee Id to update employee object", required = true)
@PathVariable(value = "id") Long employeeId,
@ApiParam(value = "Update employee object", required = true)
@Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException(EMPLOYEE_NOT_FOUND_FOR_THIS_ID + employeeId));
employee.setName(employeeDetails.getName());
employee.setAge(employeeDetails.getAge());
final Employee updatedEmployee = employeeRepository.save(employee);
return ResponseEntity.ok(updatedEmployee);
}
@ApiOperation(value = "Delete an employee")
@DeleteMapping("/employees/{id}")
public Map<String, Boolean> deleteEmployee(
@ApiParam(value = "Employee Id from which employee object will delete from database table", required = true)
@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException(EMPLOYEE_NOT_FOUND_FOR_THIS_ID + employeeId));
employeeRepository.delete(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}
</pre><br />
<br />
Step 10: Once above code has been completed, then you can run the application by right clicking on the Springboot application.<br />
Step 11. Once the application executed successfully, then we need to test this application<br />
<br />
One way is either Using- SOAP UI, Postman - these needs to be installed on our machine, else we can't test the rest service.<br />
To test the REST API, we already configured Swagger UI. So just go to your web browser, then click, <a href="http://localhost:8080/swagger-ui.html">http://localhost:8080/swagger-ui.html</a> - it will display all the operations, which is availabe in controller class.<br />
<br />
<br />
Now you can test those API's by giving request parameters <br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgY1KZmHjgQ0Ek1nnFEjOlh6X03pv5-YXS34NQM7LNnMhYCZ3UA5_OdDfoPO1RzvOPRyIY0-k2AAvFjs_PcHepHcOJ_SGhbhK_Zthe9t99MbomOHID9yWMkirPFXOwb3UuaNCBwJkfrj6s/s1600/swagger_ui.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgY1KZmHjgQ0Ek1nnFEjOlh6X03pv5-YXS34NQM7LNnMhYCZ3UA5_OdDfoPO1RzvOPRyIY0-k2AAvFjs_PcHepHcOJ_SGhbhK_Zthe9t99MbomOHID9yWMkirPFXOwb3UuaNCBwJkfrj6s/s320/swagger_ui.png" width="320" height="180" data-original-width="1600" data-original-height="900" /></a><br />
<br />
Step 12: Once done, we need to write Junit test cases for the all the classes<br />
<br />
<pre class="prettyprint lang-java">package com.siva.springboot.javaguruonline;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJpaSwaggerSonarqubeApplicationTest {
@Test
public void contextLoads() {
}
}
</pre><br />
Controller class test<br />
<br />
<pre class="prettyprint lang-java">package com.siva.springboot.javaguruonline.controller;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.meta.When;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.siva.springboot.javaguruonline.SpringbootJpaSwaggerSonarqubeApplication;
import com.siva.springboot.javaguruonline.model.Employee;
import com.siva.springboot.javaguruonline.model.EmployeeDetails;
import com.siva.springboot.javaguruonline.repository.EmployeeDaoImpl;
import com.siva.springboot.javaguruonline.repository.EmployeeRepository;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes=SpringbootJpaSwaggerSonarqubeApplication.class)
@AutoConfigureMockMvc
public class EmployeeControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private EmployeeRepository employeeRepository;
@Mock
private EmployeeDaoImpl employeeDao;
@Test
public void testGetAllEmployees() throws Exception{
List<employee> employeeList = employeeRepository.findAll();
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(employeeList);
FileWriter file = new FileWriter(new File("employee.json"));
file.write(jsonString);
file.close();
this.mockMvc.perform(get("/api/v1/employees")).andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", hasSize(4)));
}
@Test
public void testGetAllEmployeeDetails() throws Exception {
EmployeeDetails employee = new EmployeeDetails();
employee.setEmpId(123);
employee.setEmpName("Siva");
List<employeedetails> employeeList = new ArrayList<employeedetails>();
employeeList.add(employee);
when(employeeDao.getEmployeeDetails()).thenReturn(employeeList);
this.mockMvc.perform(get("/api/v1/employeedetails")).andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", hasSize(4)));
}
}
</pre><br />
DaoImpl Test<br />
<br />
<pre class="prettyprint lang-java">package com.siva.springboot.javaguruonline.repository;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.siva.springboot.javaguruonline.SpringbootJpaSwaggerSonarqubeApplication;
import com.siva.springboot.javaguruonline.model.EmployeeDetails;
import com.siva.springboot.javaguruonline.repository.EmployeeDao;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJpaSwaggerSonarqubeApplication.class)
public class EmployeeDaoImplTest {
@Autowired
public EmployeeDao employeeDao;
@Test
public void testGetAllEmployeeDetails(){
List<employeedetails> employeeDetails = employeeDao.getEmployeeDetails();
Assert.assertNotNull(employeeDetails);
}
}
</pre><br />
Repository Test<br />
<br />
<pre class="prettyprint lang-java">package com.siva.springboot.javaguruonline.repository;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.siva.springboot.javaguruonline.SpringbootJpaSwaggerSonarqubeApplication;
import com.siva.springboot.javaguruonline.model.Employee;
import com.siva.springboot.javaguruonline.repository.EmployeeRepository;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJpaSwaggerSonarqubeApplication.class)
public class EmployeeRepositoryTest {
@Autowired
EmployeeRepository employeeRepository;
@Test
public void getEmployeeDetails(){
List<employee> employeeList = employeeRepository.findAll();
Assert.assertNotNull("EmployeeListNotEmpty", employeeList);;
}
}
</pre><br />
<br />
Step 13: We need to check the code coverage tool called Sonarqube, required dependencies added in <b>pom.xml</b><br />
<br />
Step 14: Download Sonarqube from <a href="https://www.sonarqube.org/downloads/">SonarQube</a> - and look for <b>Historical Downloads</b>, then download , which ever the version you want to work on.<br />
<br />
<br />
Step 15 : Unzip that file and go to bin folder- <b>StartSonar.bat</b> file <br />
<br />
Step 16 : Once Sonar is up, then go to browser and try <b>http://localhost:9000<a href="http://localhost:9000"></a></b> , login with username -admin and password- admin<br />
<br />
Step 17: Once Sonarqube is up and running, we need to run the code through either sonar scanner or maven<br />
<br />
Before Scanning the code, we need to create properties file called - <b>sonar-project.properties</b> place the inside of the your project<br />
and need to mention src code path , test path, java version.. etc<br />
<br />
<pre class="prettyprint lang-java"># must be unique in a given SonarQube instance
sonar.projectKey=springboot-jpa-swagger-mysql-sonarqube
# this is the name displayed in the SonarQube UI
sonar.projectName=springboot-jpa-swagger-mysql-sonarqube
sonar.projectVersion=1.0
# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
# Since SonarQube 4.2, this property is optional if sonar.modules is set.
# If not set, SonarQube starts looking for source code from the directory containing
# the sonar-project.properties file.
sonar.sources=/src/main/java/
# Encoding of the source code. Default is default system encoding
sonar.sourceEncoding=UTF-8
sonar.junit.reportPaths=./target/surefire-reports
# Generate sonar issues report in html and console
sonar.issuesReport.html.enable=true
sonar.issuesReport.console.enable=true
# Display Jacoco report into SonarQube dashboard
# Comma-separated paths to directories with tests (optional)
sonar.tests=/src/test/java/
# This name depends on the configuration in pom.xml. In this example we have ${project.build.directory}/coverage-reports/jacoco-ut.exec entry in our pom.xml
sonar.jacoco.reportPath=target/surefire-reports/jacoco-ut.exec
sonar.dynamicAnalysis=reuseReports
sonar.java.coveragePlugin=jacoco
sonar.jacoco.reportMissing.force.zero=true
sonar.java.binaries=/target/classes/
sonar.coverage.exclusions=**/*Employee.java,**/*EmployeeDetails.java,**/*ErrorDetails.java,**/*ErrorDetails.java,**/*ResourceNotFoundException.java
</pre><br />
Step 18 : Use the below command to run the code coverage- make sure before running the sonar, sonarqube should up and running<br />
Go to your project location in the command prompt.<br />
<b> />mvn clean install sonar:sonar</b><br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbPUtKnJxnu4xmXMmhW1biTnhL43jAnvO-VLwB8FpteieOgcG8nFXFegMvY5VrTGbT5w3SGPdvvlp2iL2y29tK03KsGoz-aEca3stFgvhlXl0dYkFU9f1RspYhKS60JxIBMH7nsyTFsWI/s1600/sonarqube.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbPUtKnJxnu4xmXMmhW1biTnhL43jAnvO-VLwB8FpteieOgcG8nFXFegMvY5VrTGbT5w3SGPdvvlp2iL2y29tK03KsGoz-aEca3stFgvhlXl0dYkFU9f1RspYhKS60JxIBMH7nsyTFsWI/s320/sonarqube.png" width="320" height="180" data-original-width="1600" data-original-height="900" /></a><br />
<br />
</div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com4tag:blogger.com,1999:blog-8136669514202946995.post-49022084700671885962020-02-29T18:04:00.001+05:302020-02-29T18:05:18.793+05:30Getting Started with Apache Solr on Windows<div dir="ltr" style="text-align: left;" trbidi="on"><br />
This Post will explain about what is Apache Solr and how to do the setup on windows environment, Basic Apache Solr commands<br />
<br />
<b>What is Apache Solr?</b><br />
<br />
Solr is the popular, blazing-fast, open source enterprise search platform built on Apache Lucene<br />
<br />
Solr is highly reliable, scalable and fault tolerant, providing distributed indexing, replication and load-balanced querying, automated failover and recovery, centralized configuration and more. Solr powers the search and navigation features of many of the world's largest internet sites<br />
<br />
We need the Java Runtime Environment (JRE) version 1.8 or higher to install the Apache Solr<br />
<br />
Check the java version using the below command <br />
<br />
<b>Java -version</b><br />
<br />
<b>Step 1:</b><br />
<br />
Download the Apache latest version from this link, either source or binary <br />
<a href="https://lucene.apache.org/solr/downloads.html">Download Apache Solr</a><br />
<br />
<a href="https://www.apache.org/dyn/closer.lua/lucene/solr/8.4.1/solr-8.4.1.zip">Apache solr-8.4.1.zip</a><br />
<br />
<br />
<b>Step 2:</b><br />
<br />
Unzip the downloaded one and set the path, inside environment variables, check my previous post how to set the environment variables<br />
<br />
After Setting the env varibles, use the below command to start the solr<br />
<br />
<br />
<b>Step 3:</b> <br />
<br />
Go to the location, where it has unzipped up to bin folder<br />
<br />
<b>solr start</b><br />
<br />
Will start the solr and give the message stating solr has been started <br />
<br />
Know the status of the solr use the below command<br />
<br />
<b>solr status</b><br />
<br />
create a core that uses a data-driven schema which tries to guess the correct field type when you add documents to the index.<br />
<br />
<b>solr create -c movies</b><br />
<br />
<b>Step 4:</b><br />
<br />
Use the below link in the browser, to check about created core and other details<br />
<br />
try with<a href="http://"> http://localhost:8983/</a><br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgu1EpJ9nn9NimXdzV9v_MAKw_U515JUGDR6CAHqqEQaO3Y6eDTW0SqTzX5Ku0BFtBTeMZQL7Yqhbt4ULq2V-ONW9GGDNMB3uEWiWyPieyABjrXtKHh1V7ty8Zvdyxy2oONv29QYQJO9uA/s1600/SolrAdmin.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgu1EpJ9nn9NimXdzV9v_MAKw_U515JUGDR6CAHqqEQaO3Y6eDTW0SqTzX5Ku0BFtBTeMZQL7Yqhbt4ULq2V-ONW9GGDNMB3uEWiWyPieyABjrXtKHh1V7ty8Zvdyxy2oONv29QYQJO9uA/s320/SolrAdmin.png" width="320" height="172" data-original-width="1600" data-original-height="860" /></a><br />
<br />
<b>Step 5:</b><br />
<br />
Stop the Solr<br />
<br />
<b>solr stop -all</b><br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8p183vPaNDsZKnZsdeWtS6rBht7x4l_fT6gozy7Kn9MmRT-AEobWYZXHE71_S7gDNUgopvIw5vLYyBOZFwEffKCluUP7QWJOMadVvDaMnsbtgmxGcZcf1KlALn4DASA5eYFGTY0WxwiU/s1600/SolrCommands.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8p183vPaNDsZKnZsdeWtS6rBht7x4l_fT6gozy7Kn9MmRT-AEobWYZXHE71_S7gDNUgopvIw5vLYyBOZFwEffKCluUP7QWJOMadVvDaMnsbtgmxGcZcf1KlALn4DASA5eYFGTY0WxwiU/s320/SolrCommands.png" width="320" height="172" data-original-width="1600" data-original-height="860" /></a><br />
Thank you for viewing this post , just we created the core, Next post will explain , how to do the indexing and search and many more features, which is provided by Apache Solr.<br />
<br />
</div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com0tag:blogger.com,1999:blog-8136669514202946995.post-89278818192057879802020-02-23T11:07:00.005+05:302020-02-23T11:07:58.362+05:30How Apache Kafka is Better than any other traditional messaging brokers(Active MQ,JMS,Camel,IBM MQ)<div dir="ltr" style="text-align: left;" trbidi="on"><br />
1. Kafka is a distributed streaming platform<br />
2. Kafka stores all the messages before sending or after successufully received by subscriping applications.<br />
3. Kafka Run as a cluster on one or more servers that can be available on multiple datacenters.<br />
4. Kafka is client centric and it has fair distribution of related messages to consumers and it is extreamly fast and scalable broker<br />
5. Kafka has Horizontally scalable, by adding more partitions<br />
6. Kafka does not degrade performance , adding of new consumers<br />
7. Kafaka uses one destination type called topic, which internally combines both publish-subscribe and point-to-point<br />
8. Kafka message is key-value pair. payload of the message sent as the value.<br />
9. Kafaka cients are responsible for replaying failed messages<br />
10. Kafka retains messages, it is possible for clients to retrieve any message, providing option for re-processing of all messages.<br />
<br />
Traditional messasing brokers either don't persist messages at all. and it will store only until they consumed and acknowledged.<br />
Traditional messaging brokers like imperative programming, An event is occurred and our code is notified of that event. it is tightly coupled.<br />
<br />
You can Read <a href="https://kafka.apache.org/intro">Apache Kafka</a> for more information about apache kafka<br />
<br />
<br />
<br />
<br />
</div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com2tag:blogger.com,1999:blog-8136669514202946995.post-40172386563291895662019-10-28T15:28:00.002+05:302019-10-28T15:34:22.727+05:30Jasper Reports export to EXCEL, CSV and PDF Using JRXML Java and My SQL<div dir="ltr" style="text-align: left;" trbidi="on"><br />
<br />
This Post will explain , How to export different formats using Jasper and Jrxml using java<br />
<br />
Step 1: Download <a href="https://community.jaspersoft.com/download">Download Jasper Studio</a> <br />
or <a href="https://community.jaspersoft.com/project/ireport-designer"> I Report Designer</a><br />
<br />
<br />
Step 2 : Design your page by providing connection details and query details and what columns needs to be display in PDF/excel/CSV<br />
<br />
<br />
Step 3: Your design Page details can be mentioned in Summary Band.<br />
<br />
<pre class="brush:xml">
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 7.3.1.final using JasperReports Library version 6.8.1-3d4b87119c827be13776e451fb3738062f84a87d -->
<jasperreport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="csv_export" pageWidth="842" pageHeight="842" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" isTitleNewPage="true" uuid="4d1ee091-9e9a-4198-9bf6-e77af22cf170">
<property name="com.jaspersoft.studio.data.sql.tables" value=""/>
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="sqldb"/>
<property name="com.jaspersoft.studio.unit." value="pixel"/>
<property name="com.jaspersoft.studio.unit.pageHeight" value="pixel"/>
<property name="com.jaspersoft.studio.unit.pageWidth" value="pixel"/>
<property name="com.jaspersoft.studio.unit.topMargin" value="pixel"/>
<property name="com.jaspersoft.studio.unit.bottomMargin" value="pixel"/>
<property name="com.jaspersoft.studio.unit.leftMargin" value="pixel"/>
<property name="com.jaspersoft.studio.unit.rightMargin" value="pixel"/>
<property name="com.jaspersoft.studio.unit.columnWidth" value="pixel"/>
<property name="com.jaspersoft.studio.unit.columnSpacing" value="pixel"/>
<style name="Table_TH" mode="Opaque" backcolor="#F0F8FF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
<toppen lineWidth="0.5" lineColor="#000000"/>
<leftpen lineWidth="0.5" lineColor="#000000"/>
<bottompen lineWidth="0.5" lineColor="#000000"/>
<rightpen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<style name="Table_CH" mode="Opaque" backcolor="#BFE1FF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
<toppen lineWidth="0.5" lineColor="#000000"/>
<leftpen lineWidth="0.5" lineColor="#000000"/>
<bottompen lineWidth="0.5" lineColor="#000000"/>
<rightpen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<style name="Table_TD" mode="Opaque" backcolor="#FFFFFF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
<toppen lineWidth="0.5" lineColor="#000000"/>
<leftpen lineWidth="0.5" lineColor="#000000"/>
<bottompen lineWidth="0.5" lineColor="#000000"/>
<rightpen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<subdataset name="Dataset1" uuid="23c8f5b2-bc0f-499a-b50e-21fdc9e7ec05">
<property name="com.jaspersoft.studio.data.sql.tables" value=""/>
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="sqldb"/>
<querystring language="SQL">
<![CDATA[select * from employee]]>
</queryString>
<field name="emp_id" class="java.lang.Integer">
<property name="com.jaspersoft.studio.field.label" value="emp_id"/>
<property name="com.jaspersoft.studio.field.tree.path" value="employee"/>
</field>
<field name="emp_name" class="java.lang.String">
<property name="com.jaspersoft.studio.field.label" value="emp_name"/>
<property name="com.jaspersoft.studio.field.tree.path" value="employee"/>
</field>
<field name="emp_age" class="java.lang.Integer">
<property name="com.jaspersoft.studio.field.label" value="emp_age"/>
<property name="com.jaspersoft.studio.field.tree.path" value="employee"/>
</field>
<field name="emp_gender" class="java.lang.String">
<property name="com.jaspersoft.studio.field.label" value="emp_gender"/>
<property name="com.jaspersoft.studio.field.tree.path" value="employee"/>
</field>
<group name="emp_id">
<groupexpression><![CDATA[$F{emp_id}]]></groupExpression>
</group>
<group name="emp_name">
<groupexpression><![CDATA[$F{emp_name}]]></groupExpression>
</group>
<group name="emp_age">
<groupexpression><![CDATA[$F{emp_age}]]></groupExpression>
</group>
<group name="emp_gender">
<groupexpression><![CDATA[$F{emp_gender}]]></groupExpression>
</group>
</subDataset>
<querystring language="SQL">
<![CDATA[select * from employee]]>
</queryString>
<field name="emp_id" class="java.lang.Integer">
<property name="com.jaspersoft.studio.field.label" value="emp_id"/>
<property name="com.jaspersoft.studio.field.tree.path" value="employee"/>
</field>
<field name="emp_name" class="java.lang.String">
<property name="com.jaspersoft.studio.field.label" value="emp_name"/>
<property name="com.jaspersoft.studio.field.tree.path" value="employee"/>
</field>
<field name="emp_age" class="java.lang.Integer">
<property name="com.jaspersoft.studio.field.label" value="emp_age"/>
<property name="com.jaspersoft.studio.field.tree.path" value="employee"/>
</field>
<field name="emp_gender" class="java.lang.String">
<property name="com.jaspersoft.studio.field.label" value="emp_gender"/>
<property name="com.jaspersoft.studio.field.tree.path" value="employee"/>
</field>
<summary>
<band height="170" splitType="Prevent">
<property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.HorizontalRowLayout"/>
<componentelement>
<reportelement stretchType="RelativeToBandHeight" x="5" y="5" width="802" height="165" uuid="97099bcb-12c7-462f-8073-94298b1e71a7">
<property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.HorizontalRowLayout"/>
<property name="com.jaspersoft.studio.table.style.table_header" value="Table_TH"/>
<property name="com.jaspersoft.studio.table.style.column_header" value="Table_CH"/>
<property name="com.jaspersoft.studio.table.style.detail" value="Table_TD"/>
<property name="com.jaspersoft.studio.unit.width" value="px"/>
</reportElement>
<jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
<datasetrun subDataset="Dataset1" uuid="1478f75b-2895-4bbe-9eeb-6fd1a42b03fe">
<connectionexpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
</datasetRun>
<jr:column width="50" uuid="7a5c17c3-8de0-4ec0-8d20-f220b0ebca99">
<jr:tableHeader style="Table_TH" height="30"/>
<jr:tableFooter style="Table_TH" height="30"/>
<jr:columnHeader style="Table_CH" height="30">
<statictext>
<reportelement x="0" y="0" width="50" height="30" uuid="9836c26c-58a6-402b-ad42-6deb9d3959c7"/>
<text><![CDATA[emp_id]]></text>
</staticText>
</jr:columnHeader>
<jr:columnFooter style="Table_CH" height="30"/>
<jr:detailCell style="Table_TD" height="30">
<textfield>
<reportelement x="0" y="0" width="50" height="30" uuid="0af2580a-cf97-4407-bed6-e6a8cc258792"/>
<textfieldexpression><![CDATA[$F{emp_id}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="50" uuid="9632ad8f-3c57-47ce-a7f4-67058926ae34">
<jr:tableHeader style="Table_TH" height="30"/>
<jr:tableFooter style="Table_TH" height="30"/>
<jr:columnHeader style="Table_CH" height="30">
<statictext>
<reportelement x="0" y="0" width="50" height="30" uuid="d1e500c7-25e0-4d22-9aca-7edf0a37a9b2"/>
<text><![CDATA[emp_name]]></text>
</staticText>
</jr:columnHeader>
<jr:columnFooter style="Table_CH" height="30"/>
<jr:detailCell style="Table_TD" height="30">
<textfield>
<reportelement x="0" y="0" width="50" height="30" uuid="d069d4ef-2a03-4a6d-9f94-2c67122094e5"/>
<textfieldexpression><![CDATA[$F{emp_name}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="50" uuid="ed66ca7e-9b2c-4aaa-8347-78441e221416">
<jr:tableHeader style="Table_TH" height="30"/>
<jr:tableFooter style="Table_TH" height="30"/>
<jr:columnHeader style="Table_CH" height="30">
<statictext>
<reportelement x="0" y="0" width="50" height="30" uuid="fe4b2047-c9b5-4403-8f49-2a1232e17337"/>
<text><![CDATA[emp_age]]></text>
</staticText>
</jr:columnHeader>
<jr:columnFooter style="Table_CH" height="30"/>
<jr:detailCell style="Table_TD" height="30">
<textfield>
<reportelement x="0" y="0" width="50" height="30" uuid="de0979e3-96be-4625-b1ba-d80f09a25bca"/>
<textfieldexpression><![CDATA[$F{emp_age}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="50" uuid="36cf5bfd-5aef-41f5-b85d-47c6a5706f04">
<jr:tableHeader style="Table_TH" height="30"/>
<jr:tableFooter style="Table_TH" height="30"/>
<jr:columnHeader style="Table_CH" height="30">
<statictext>
<reportelement x="0" y="0" width="50" height="30" uuid="d95b791e-fae6-4e53-a9eb-35525d6d4ebd"/>
<text><![CDATA[emp_gender]]></text>
</staticText>
</jr:columnHeader>
<jr:columnFooter style="Table_CH" height="30"/>
<jr:detailCell style="Table_TD" height="30">
<textfield>
<reportelement x="0" y="0" width="50" height="30" uuid="3d3da3ad-f9c7-4b08-ad18-5232a39e445d"/>
<textfieldexpression><![CDATA[$F{emp_gender}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
</jr:table>
</componentElement>
</band>
</summary>
</jasperReport>
</pre><br />
<br />
<br />
Step 4: Once design completes , then it is time to write java class to export into different formats<br />
<br />
<br />
Step 5: Excel report Generation<br />
<br />
<br />
<pre class="prettyprint"><code class="language-java">
package arrayListTest;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.export.SimpleCsvExporterConfiguration;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimplePdfExporterConfiguration;
import net.sf.jasperreports.export.SimpleWriterExporterOutput;
import net.sf.jasperreports.export.SimpleXlsReportConfiguration;
public class GenerateMultipleReportsFromJasper {
public static void main(String[] args) {
//Jrxml file source
String sourceFileName = "C:\\Users\\Siva\\JaspersoftWorkspace\\csvpdf\\csv_export.jrxml";
//destination file location
String outXlsName = "C:\\Users\\Siva\\JaspersoftWorkspace\\csvpdf\\test.xls";
//If we want to pass any parameters to jasper report, then we can use this map
HashMap xlsParams = new HashMap();
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// here employee is database name, root is username and password
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root", "root");
JasperReport report = JasperCompileManager.compileReport(sourceFileName );
JasperPrint xlsPrint = JasperFillManager.fillReport(report, xlsParams, con);
JRXlsExporter xlsExporter = new JRXlsExporter();
xlsExporter.setExporterInput(new SimpleExporterInput(xlsPrint));
xlsExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outXlsName));
SimpleXlsReportConfiguration xlsReportConfiguration = new SimpleXlsReportConfiguration();
xlsReportConfiguration.setOnePagePerSheet(false);
xlsReportConfiguration.setRemoveEmptySpaceBetweenRows(true);
xlsReportConfiguration.setDetectCellType(false);
xlsReportConfiguration.setWhitePageBackground(false);
xlsExporter.setConfiguration(xlsReportConfiguration);
xlsExporter.exportReport();
} catch (Exception e) {
System.out.println(e);
}
finally{
try{
if(con != null){
con.close();
}
}
catch(Exception ex){
}
}
}
}
</pre><br />
Step 6: CSV Generation <br />
<br />
<br />
<pre class="prettyprint"><code class="language-java">
HashMap csvParamsMap = new HashMap();
String outcsvName = "C:\\Users\\Siva\\JaspersoftWorkspace\\csvpdf\\test.csv";
JasperReport report1 = JasperCompileManager.compileReport(sourceFileName );
JasperPrint jasperPrint = JasperFillManager.fillReport(report1, csvParamsMap, con);
JRCsvExporter exporter = new JRCsvExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleWriterExporterOutput(new File(outcsvName)));
SimpleCsvExporterConfiguration configuration = new SimpleCsvExporterConfiguration();
configuration.setWriteBOM(Boolean.TRUE);
configuration.setRecordDelimiter("\r\n");
exporter.setConfiguration(configuration);
exporter.exportReport();
</pre><br />
<br />
Step 7: PDF Generation<br />
<br />
<br />
<pre class="prettyprint"><code class="language-java">
HashMap pdfParamsMap = new HashMap();
String outPdfName = "C:\\Users\\Siva\\JaspersoftWorkspace\\csvpdf\\test.pdf";
JasperReport report2 = JasperCompileManager.compileReport(sourceFileName );
JasperPrint jasperPrint2 = JasperFillManager.fillReport(report2, pdfParamsMap, con);
JRPdfExporter pdfExporter = new JRPdfExporter();
pdfExporter.setExporterInput(new SimpleExporterInput(jasperPrint2));
pdfExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outPdfName));
SimplePdfExporterConfiguration pdfConfiguration = new SimplePdfExporterConfiguration();
pdfConfiguration.setCreatingBatchModeBookmarks(true);
pdfExporter.setConfiguration(pdfConfiguration);
</pre><br />
<br />
<br />
<br />
Step 8: Required jar file to execute this program<br />
<br />
<br />
<br />
1. <a href="https://repo1.maven.org/maven2/com/lowagie/itext/2.1.7/itext-2.1.7.jar">Itext 2.1.7.jar</a><br />
2. <a href="https://repo1.maven.org/maven2/commons-beanutils/commons-beanutils/1.9.2/commons-beanutils-1.9.2.jar">commons-beanutils-1.9.2.jar</a><br />
3. <a href="https://repo1.maven.org/maven2/commons-logging/commons-logging/1.2/commons-logging-1.2.jar">commons-logging-1.2.jar</a><br />
4. <a href="https://repo1.maven.org/maven2/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar">commons-collections-3.2.1.jar</a><br />
5. <a href="https://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar">commons-lang-2.6.jar</a><br />
6. <a href="https://repo1.maven.org/maven2/commons-digester/commons-digester/1.6/commons-digester-1.6.jar">commons-digester-1.6.jar</a><br />
7. <a href="https://repo1.maven.org/maven2/net/sf/jasperreports/jasperreports/6.2.0/jasperreports-6.2.0.jar">jasperreports-6.2.0.jar</a><br />
8. <a href="https://repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.40/mysql-connector-java-5.1.40.jar">mysql-connector-java-5.1.40.jar</a><br />
9. <a href="https://repo1.maven.org/maven2/org/apache/poi/poi-ooxml/3.16/poi-ooxml-3.16.jar">poi-ooxml-3.16.jar</a><br />
10. <a href="https://repo1.maven.org/maven2/org/apache/poi/poi/3.12/poi-3.12.jar">poi-3.12.jar</a><br />
<br />
<br />
<br />
Step 9: Once We downloaded all jars then add into java build path.<br />
<br />
Step 10: This is how we can export different format using jasper jrxml and Java.<br />
<br />
<br />
</div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com13tag:blogger.com,1999:blog-8136669514202946995.post-88468393003714046052019-08-10T14:50:00.000+05:302019-08-10T14:58:19.307+05:30Getting started with Kubernetes and Install Kubernetes on Windows , Tools for Kubernetes Cluster<div dir="ltr" style="text-align: left;" trbidi="on"><br />
<br />
1. What is Kubernetes?<br />
It is an open source system for automating deployment, scaling and managing containerized applications<br />
<br />
How to install Kubernetes?<br />
<br />
1. Install Kube control(kubectl) on Windows<br />
2. kubectl (kubernet command control tool) , used to run the commands in kubernetes clusters.<br />
3. Before install, we have to make sure each client version has to work with minor difference with master<br />
For example, a v1.2 client should work with v1.1, v1.2, and v1.3 master<br />
<br />
4. Download from the given link <a href="https://storage.googleapis.com/kubernetes-release/release/v1.15.0/bin/windows/amd64/kubectl.exe">Download Kubernetes</a><br />
5. Add the binary in to your PATH.(System - Environment Variables)<br />
6.Check the version using kubectl version<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgMO1FvO3XyTRnDaC6Rhrehyphenhyphen60ovgodtkThQ2uexE7kXkCUH9PnKAuzxbSid4F9Umoa4GNyajOpTdWws5HCO9az1MBeZ-X2cO24ji6wStJ7Rlct84m0xbicGMljEscAjBJwUU-jgUFu6nE/s1600/version_check.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgMO1FvO3XyTRnDaC6Rhrehyphenhyphen60ovgodtkThQ2uexE7kXkCUH9PnKAuzxbSid4F9Umoa4GNyajOpTdWws5HCO9az1MBeZ-X2cO24ji6wStJ7Rlct84m0xbicGMljEscAjBJwUU-jgUFu6nE/s320/version_check.png" width="320" height="167" data-original-width="979" data-original-height="512" /></a><br />
We can create sample cluster online using following link<br />
<br />
<a href="https://kubernetes.io/docs/tutorials/kubernetes-basics/create-cluster/cluster-interactive/">Online interactive kubernetes cluster</a><br />
<br />
Popular tools for kubernetes clusters<br />
1. <a href="https://kubernetes.io/docs/setup/minikube/">(Mini Kube)</a><br />
2. <a href="https://cloud.google.com/kubernetes-engine/">Google Kubernetes Engine (GKE)</a><br />
3. <a href="https://aws.amazon.com/eks/">Amazon Elastic Kubernetes Service (EKS):</a><br />
4. <a href="https://azure.microsoft.com/en-us/services/kubernetes-service/">Azure Kubernetes Service (AKS)</a><br />
<br />
</div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com0tag:blogger.com,1999:blog-8136669514202946995.post-12840117587841101032018-08-08T11:18:00.000+05:302018-08-08T11:36:53.586+05:30Getting started Machine Learning Using R on Windows environment Step By Step Process.<div dir="ltr" style="text-align: left;" trbidi="on"><br />
This post will explain us, how to install R on windows environment and how to work with Machine learning project using R with simple dataset<br />
<br />
First Download R <a href="https://cran.r-project.org/bin/windows/base/">https://cran.r-project.org/bin/windows/base/</a> from this link. <br />
You can download latest version of R.<br />
1. Once download completes, then install the same in your machine. This is like any other software installation. There is no special instructions required for this.<br />
2. After successful installation we need to setup the path- go to MyComputer-RightClick- environment variables- System variables-<br />
<b> C:\Program Files\R\R-3.5.1\bin</b><br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPWxltlt4v5qNfd55up86A_3U7a46B_VvwEYJKDy938GgAiXticPoAIY0ipSxo07Ob7-8HFGAkaI6CWW0RCF7S3Wa9IBAioz7jw0kqBPDSVaVevNj6qc_9vNJE6JUiLtIigLrrF5xKNZ4/s1600/R_path_setup.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPWxltlt4v5qNfd55up86A_3U7a46B_VvwEYJKDy938GgAiXticPoAIY0ipSxo07Ob7-8HFGAkaI6CWW0RCF7S3Wa9IBAioz7jw0kqBPDSVaVevNj6qc_9vNJE6JUiLtIigLrrF5xKNZ4/s320/R_path_setup.jpg" width="320" height="180" data-original-width="1600" data-original-height="900" /></a></div>3. After setting up the path, Now we need to start the R<br />
4. Go to command prompt and Type R<br />
5. Now we can see the simple R terminal<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKHSuV14KA9Gd8ilbk9TYouRPqT294DN3xckpAiqIr6iggNtMC4MKpYnJ7kqaEmgnOBELLJP4Ugrz8WPcEXgoe3_i0rHDrUmx1ChRXnyWgiqslGkU0Q9HlfRCd6sYQy_GdElW38SDZvNA/s1600/R_start.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKHSuV14KA9Gd8ilbk9TYouRPqT294DN3xckpAiqIr6iggNtMC4MKpYnJ7kqaEmgnOBELLJP4Ugrz8WPcEXgoe3_i0rHDrUmx1ChRXnyWgiqslGkU0Q9HlfRCd6sYQy_GdElW38SDZvNA/s320/R_start.jpg" width="320" height="177" data-original-width="979" data-original-height="540" /></a></div>6. Now we will understand what is machine learning? and what is datasets?<br />
7. When we are applying machine learning to our own datasets, we are working on a project.<br />
The process of a machine learning project may not be linear, but there are a number of well-known steps:<br />
<br />
Define Problem.<br />
Prepare Data.<br />
Evaluate Algorithms.<br />
Improve Results.<br />
Present Results.<br />
<br />
8.The best way to really come in terms with a new platform or tool is to work through a machine learning project end-to-end and cover the key steps. <br />
Namely, from loading data, summarizing your data, evaluating algorithms and making some predictions.<br />
Machine Learning using R Step By Step<br />
Now this the time to work simple machine learning program using R and inbuilt dataset called iris<br />
<br />
We already installed R and it has started.<br />
Install any default packages using following syntax.<br />
<br />
<br />
Packages are third party add-ons or libraries that we can use in R.<br />
<br />
<pre class=”brush:java”>install.packages("caret")
//While installing the package, after typing the above command , it will ask us for select mirror, you can select default one.
install.packages(“caret”,dependencies=c(“Depends”,”Suggests”))
install.packages(“ellipse”)
//Load the package, which we are going to use.
libray(caret)
</pre><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhyCl9B05yJVPgC1EV1su4bjKUcdn8szZICLcketeFmGlNVQjIU0CbBR-_0mIzhtAqxrio0UE2aevaqhovzei7oRCKrF90T4XucZ-NTyXswKIyn8VFwIZYLfXFV26kHzWxUwvVWEVyA85I/s1600/R_commands_Functions.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhyCl9B05yJVPgC1EV1su4bjKUcdn8szZICLcketeFmGlNVQjIU0CbBR-_0mIzhtAqxrio0UE2aevaqhovzei7oRCKrF90T4XucZ-NTyXswKIyn8VFwIZYLfXFV26kHzWxUwvVWEVyA85I/s320/R_commands_Functions.jpg" width="320" height="172" data-original-width="1600" data-original-height="860" /></a></div>Load the data from inbuilt data and rename the same using following syntax.<br />
<pre class=”brush:java”>// Attach iris dataset to the current environment
data(iris)
// Rename iris dataset to dataset
dataset <- iris
</pre>
Now iris data loaded in R and accessible with variable called dataset
Now we will create validation dataset.
We will split the loaded dataset into two, 80% of which we will use to train our models and 20% that we will hold back as a validation dataset.
<pre class=”brush:java”>// We create a list of 80% of the rows in the original dataset we can use for training
validation_index <- createDataPartition(dataset$Species, p=0.80, list=FALSE)
//select 20% of the data for validation
validation <- dataset[-validation_index,]
//use the remaining 80% of data to training and testing the models
dataset <- dataset[validation_index,]
</pre>
Now we have training data in the dataset variable and a validation set we will use later in the validation variable.
Note that we replaced our dataset variable with the 80% sample of the dataset.
1. dim function
We can get a quick idea of how many instances (rows) and how many attributes (columns) the data contains with the dim function.
<pre class=”brush:java”>dim(dataset)
</pre>2. Attribute types - Knowing the types is important as it will give us an idea of how to better summarize the data we have and the types of transforms we might need to use to prepare the data before we model it.
<pre class=”brush:java”>sapply(dataset,class)
</pre>3. head function used to display the first five rows.
<pre class=”brush:java”>head(dataset)
</pre>4. The class variable is a factor. A factor is a class that has multiple class labels or levels
<pre class=”brush:java”>levels(dataset$Species)
</pre>5. Class Distribution
Let’s now take a look at the number of instances (rows) that belong to each class. We can view this as an absolute count and as a percentage.
6. Summary of each Attribute
<pre class=”brush:java”> summary(dataset)
</pre>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgUMguFf4xbulqMCmd2F72hMThZgGas0hxVfTLgtfIutZcO6QRUZT7_arDI5t3ViLaLyr7c-MVZPffCUh_o_rieFR5rBtB-Hiefed1FPse7U1zpFjatVzAoYPu1SVx-GAIBOZ9xd0359Q/s1600/summary.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgUMguFf4xbulqMCmd2F72hMThZgGas0hxVfTLgtfIutZcO6QRUZT7_arDI5t3ViLaLyr7c-MVZPffCUh_o_rieFR5rBtB-Hiefed1FPse7U1zpFjatVzAoYPu1SVx-GAIBOZ9xd0359Q/s320/summary.jpg" width="320" height="180" data-original-width="1600" data-original-height="900" /></a></div>
<b>Visualize Dataset</b>
We now have a seen the basic details about the data. We need to extend that with some visualizations.
We are going to look at two types of plots:
1. Univariate plots to better understand each attribute.
2. Multivariate plots to better understand the relationships between attributes.
First we will see the Univariate plots, this is for each individual variable.
Input attributes x and the output attributes y.
<pre class=”brush:java”> //Split input and output
x <- dataset[,1:4]
y <- dataset[,5]
</pre>
Given that the input variables are numeric, we can create box and whisker plots of each.
<pre class=”brush:java”> par(mfrow=c(1,4))
for(i in 1:4) {
boxplot(x[,i], main=names(iris)[i])
}
</pre>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjM6WSQMC7TT5lFaZhQ26Zptv5XeO0Au4fkD3BEefRBs3EpMqY1ij_fHmW5fkQCBem7Fnovp8TI7-hpBLBgzN_dOq2q2p5F_cAEgXv_8_MOtfWzeVsP0Y0DfCbno6l0qjA88O4BgoR6zrA/s1600/boxplot_R_1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjM6WSQMC7TT5lFaZhQ26Zptv5XeO0Au4fkD3BEefRBs3EpMqY1ij_fHmW5fkQCBem7Fnovp8TI7-hpBLBgzN_dOq2q2p5F_cAEgXv_8_MOtfWzeVsP0Y0DfCbno6l0qjA88O4BgoR6zrA/s320/boxplot_R_1.jpg" width="320" height="180" data-original-width="1600" data-original-height="900" /></a></div>
We can also create a barplot of the Species class variable to get a graphical representation of the class distribution
(generally uninteresting in this case because they’re even).
<pre class=”brush:java”>plot(y)
</pre><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFH54qGF6N9DxK921zOktTi60ahmPUojOtX7Pe3ioUxrsW3LiimKGflWY6-1CFxn2Ny3RzebJRc_eOtyBYtlN6KfYduazjjba_4HsH3HvtKxBJnKZqodDu2UhCH0mMWR_u2LyOA_bQPsk/s1600/boxplot_R.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFH54qGF6N9DxK921zOktTi60ahmPUojOtX7Pe3ioUxrsW3LiimKGflWY6-1CFxn2Ny3RzebJRc_eOtyBYtlN6KfYduazjjba_4HsH3HvtKxBJnKZqodDu2UhCH0mMWR_u2LyOA_bQPsk/s320/boxplot_R.jpg" width="320" height="180" data-original-width="1600" data-original-height="900" /></a></div>
This confirms what we learned in the last section, that the instances are evenly distributed across the three class:
<b>Multivariate Plots</b>
First let’s look at scatterplots of all pairs of attributes and color the points by class.
In addition, because the scatterplots show that points for each class are generally separate, we can draw ellipses around them.
<pre class=”brush:java”>featurePlot(x=x,y=y,plot=”ellipse”)
</pre><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgetFIVDLfAexi0RvDJxLHUyO9vrCW3ACIHO3g2iJBN3M13HM-iLX2SnA6oDd2TiLsiutLEtXJlRUVFhRSIzwRbGAdREghaeXAq3UHQ3zgiKN6KUw6ehFgBmP2nOJ0wT8cpX2-RqqrVdeU/s1600/scatter_plot.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgetFIVDLfAexi0RvDJxLHUyO9vrCW3ACIHO3g2iJBN3M13HM-iLX2SnA6oDd2TiLsiutLEtXJlRUVFhRSIzwRbGAdREghaeXAq3UHQ3zgiKN6KUw6ehFgBmP2nOJ0wT8cpX2-RqqrVdeU/s320/scatter_plot.jpg" width="320" height="180" data-original-width="1600" data-original-height="900" /></a></div>
We can also look at box and whisker plots of each input variable again, but this time broken down into separate plots for each class.
This can help to tease out obvious linear separations between the classes.
<pre class=”brush:java”>featurePlot(x=x,y=y,plot=”box”)
</pre><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTre_djOtbp7nh-Bpdii0ZpXETqFyVryOBRYJ70vV-SnZefspc3_n8_8anFtbaXuzWaVe8YMbun6QYEML9SeK2OcuMTk3eUXzUnt-ML8i2g7CC31pREr6KR7bealCJEFGvscGESwFxEE8/s1600/feature_plot_box.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTre_djOtbp7nh-Bpdii0ZpXETqFyVryOBRYJ70vV-SnZefspc3_n8_8anFtbaXuzWaVe8YMbun6QYEML9SeK2OcuMTk3eUXzUnt-ML8i2g7CC31pREr6KR7bealCJEFGvscGESwFxEE8/s320/feature_plot_box.jpg" width="320" height="180" data-original-width="1600" data-original-height="900" /></a></div>
Next we can get an idea of the distribution of each attribute, again like the box and whisker plots, broken down by class value.
Sometimes histograms are good for this, but in this case we will use some probability density plots to give nice smooth lines for each distribution.
<pre class=”brush:java”>// density plots for each attribute by class value
scales <- list(x=list(relation="free"), y=list(relation="free"))
featurePlot(x=x, y=y, plot="density", scales=scales)
</pre>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkYav3bQgwpxY32eFFh6Ln8WKbCQ7M3UkQmSXtErxYs9iQqCpNK775me0olAZ32xCxQqxpr0-dgXgYxQhS4dFDX3vwhCFC_LU-bhZKE4j5tksO9pglDQgUm5GrS_vudT5ggK-HtZ1A17w/s1600/scale_plot_density.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkYav3bQgwpxY32eFFh6Ln8WKbCQ7M3UkQmSXtErxYs9iQqCpNK775me0olAZ32xCxQqxpr0-dgXgYxQhS4dFDX3vwhCFC_LU-bhZKE4j5tksO9pglDQgUm5GrS_vudT5ggK-HtZ1A17w/s320/scale_plot_density.jpg" width="320" height="180" data-original-width="1600" data-original-height="900" /></a></div><b>Evaluating the Algorithms</b>
Set-up the test harness to use 10-fold cross validation.
We will split our dataset into 10 parts, train in 9 and test on 1 and release for all combinations of train –test splits.
We will also repeat the process 3 times for each algorithm with different splits of the data into 10 groups
We are using the metric of “Accuracy” to evaluate models. This is a ratio of the number of correctly predicted instances in divided by the total number of instances in the
dataset multiplied by 100 to give a percentage (e.g. 95% accurate). We will be using the metric variable when we run build and evaluate each model next.
<pre class=”brush:java”>control <- tarinControl(method=”csv”,number=10)
metric <- “Accuarcy”
</pre>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEja3GjKQk2dlIna0noovvteAh7tcK_2GEDGmavCOneVlunMcQ9AgRJ8wRcDSS0yOa4dPrC-TjJ3vdlcVnGWTAhNoekpCTgGT5rgug0wQTy3vdpkNzpYVfp3RIMIvK-1f6iphSDVzmghP04/s1600/algorithms.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEja3GjKQk2dlIna0noovvteAh7tcK_2GEDGmavCOneVlunMcQ9AgRJ8wRcDSS0yOa4dPrC-TjJ3vdlcVnGWTAhNoekpCTgGT5rgug0wQTy3vdpkNzpYVfp3RIMIvK-1f6iphSDVzmghP04/s320/algorithms.jpg" width="320" height="180" data-original-width="1600" data-original-height="900" /></a></div>Build 5 different models to predict species from flower measurements
Linear Discriminant Analysis (LDA)
Classification and Regression Trees (CART).
k-Nearest Neighbors (kNN).
Support Vector Machines (SVM) with a linear kernel.
Random Forest (RF)
<pre class=”brush:java”>set.seed(7)
fit.lda <- train(Species~., data=dataset, method="lda", metric=metric, trControl=control)
# b) nonlinear algorithms
# CART
set.seed(7)
fit.cart <- train(Species~., data=dataset, method="rpart", metric=metric, trControl=control)
# kNN
set.seed(7)
fit.knn <- train(Species~., data=dataset, method="knn", metric=metric, trControl=control)
# c) advanced algorithms
# SVM
set.seed(7)
fit.svm <- train(Species~., data=dataset, method="svmRadial", metric=metric, trControl=control)
# Random Forest
set.seed(7)
fit.rf <- train(Species~., data=dataset, method="rf", metric=metric, trControl=control)
</pre>
We reset the random number seed before reach run to ensure that the evaluation of each algorithm is performed using exactly the same data splits.
It ensures the results are directly comparable.
Select the best model.
We now have 5 models and accuracy estimations for each. We need to compare the models to each other and select the most accurate.
We can report on the accuracy of each model by first creating a list of the created models and using the summary function.
<pre class=”brush:java”># summarize accuracy of models
results <- resamples(list(lda=fit.lda, cart=fit.cart, knn=fit.knn, svm=fit.svm, rf=fit.rf))
summary(results)
</pre>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg70XonEJycRIEkouFhO4ZSD2-dlY-q5fBOL_JpArbNFaSKV11iLnIFKdTW83c6usz5MIt7Xp9i3u_4a-q30YlBwPUblJSd_eBKC3UVIOnGOTK9N9gYivRgY-opoJWjPNffk3qPLhKOanM/s1600/summary.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg70XonEJycRIEkouFhO4ZSD2-dlY-q5fBOL_JpArbNFaSKV11iLnIFKdTW83c6usz5MIt7Xp9i3u_4a-q30YlBwPUblJSd_eBKC3UVIOnGOTK9N9gYivRgY-opoJWjPNffk3qPLhKOanM/s320/summary.jpg" width="320" height="180" data-original-width="1600" data-original-height="900" /></a></div>We can also create a plot of the model evaluation results and compare the spread and the mean accuracy of each model.
There is a population of accuracy measures for each algorithm because each algorithm was evaluated 10 times (10 fold cross validation)
<pre class=”brush:java”>dotplot(results)
</pre><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjvNOUFyt9UmsdIcxZA6ue2oB3brJZXdc6EzVvkTV1-IOy80mqXzbHBLFZo5HsMDtAx2tlqzIxnkHT-w7Vza8nNKjL70YBE8s2k3Bqz6T8deSEIccttqmf5iGBrjeEkSQFzhDJS8n__T_s/s1600/summary-results_dot_plots.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjvNOUFyt9UmsdIcxZA6ue2oB3brJZXdc6EzVvkTV1-IOy80mqXzbHBLFZo5HsMDtAx2tlqzIxnkHT-w7Vza8nNKjL70YBE8s2k3Bqz6T8deSEIccttqmf5iGBrjeEkSQFzhDJS8n__T_s/s320/summary-results_dot_plots.jpg" width="320" height="180" data-original-width="1600" data-original-height="900" /></a></div>The results can be summarized.
This gives a nice summary of what was used to train the model and the mean and standard deviation (SD) accuracy achieved, specifically 97.5% accuracy +/- 4%
How to Predictions using predict and confusion Matrix
The LDA was the most accurate model. Now we want to get an idea of the accuracy of the model on our validation set.
This will give us an independent final check on the accuracy of the best model.
It is valuable to keep a validation set just in case you made a slip during such as overfitting to the training set or a data leak.
Both will result in an overly optimistic result.
We can run the LDA model directly on the validation set and summarize the results in a confusion matrix.
<pre class=”brush:java”>predictions <- predict(fit.lda,validation)
confusionMatrix(predictions,validation$Species)
</pre>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhIv_l-O5tv7uHUGJ6XNsekfJWGH0uKPo-3tHE8M8IPnDHp87Bqz8AbdXphsGMWBLnJaRQObAP46TA5BRUYY9m5oKSGEux9Q-gqy-ST1o9GydkVPWgjDoQC6GP1EqbyjN1g0xv1NcUuFEA/s1600/prediction_confusion_matrix.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhIv_l-O5tv7uHUGJ6XNsekfJWGH0uKPo-3tHE8M8IPnDHp87Bqz8AbdXphsGMWBLnJaRQObAP46TA5BRUYY9m5oKSGEux9Q-gqy-ST1o9GydkVPWgjDoQC6GP1EqbyjN1g0xv1NcUuFEA/s320/prediction_confusion_matrix.jpg" width="320" height="172" data-original-width="1600" data-original-height="860" /></a></div></div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com46tag:blogger.com,1999:blog-8136669514202946995.post-44804466195671872352018-08-02T19:53:00.000+05:302018-08-03T10:23:55.750+05:30REST, REST Security, REST API Methods, REST annotations<div dir="ltr" style="text-align: left;font-family="Times New Roman";font-size="16px" trbidi="on" ><br />
<br />
REST - Representational State Transfer<br />
<br />
1. REST is Architecture Style implementation<br />
<br />
2. REST implemenation is based on Json Over HTTP<br />
<br />
3. REST implemented based on simple HTTP protocol<br />
<br />
4. REST has better scalability and performance<br />
<br />
5. REST permits more data formats like JSON,XML etc..<br />
<br />
6. REST emphasizes scalability of component interactions, independent deployments of components.<br />
<br />
7. REST is design of HTTP and URI standards<br />
<br />
8. REST is follow http methods like GET,POST,PUT,DELETE,PATCH<br />
<br />
9. HTTP PATCH requests are to make partial update on a resource.<br />
PUT requests also modify a resource entity so to make more clear – <br />
PATCH method is the correct choice for partially updating an existing resource <br />
and PUT should only be used if we are replacing a resource in it’s entirety.<br />
<br />
10. REST impelnetations using JAX-RS and Jersy<br />
<br />
11. Annotations of JAX-RS<br />
<br />
<b>@Context</b><br />
<br />
Injects information into a class field, bean property, or method parameter<br />
<br />
<b>@CookieParam</b><br />
<br />
Extracts information from cookies declared in the cookie request header<br />
<br />
<b>@FormParam</b><br />
<br />
Extracts information from a request representation whose content type is application/x-www-form-urlencoded<br />
<br />
<b>@HeaderParam</b><br />
<br />
Extracts the value of a header<br />
<br />
<b>@MatrixParam</b><br />
<br />
Extracts the value of a URI matrix parameter<br />
<br />
<b>@PathParam</b><br />
<br />
Extracts the value of a URI template parameter<br />
<br />
<b>@QueryParam</b><br />
<br />
Extracts the value of a URI query parameter<br />
<br />
12. HTTP Status codes<br />
<br />
<b>200 OK </b>- Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE.<br />
<b>400 Bad Request </b>- The request is malformed, such as message body format error.<br />
<b>401 Unauthorized </b>- Wrong or no authentication ID/password provided.<br />
<b>403 Forbidden </b>- It's used when the authentication succeeded but authenticated user doesn't have permission to the request resource.<br />
<b>404 Not Found </b>- When a non-existent resource is requested.<br />
<b>405 Method Not Allowed </b> - The error checking for unexpected HTTP method. For example, the RestAPI is expecting HTTP GET, but HTTP PUT is used.<br />
<br />
<br />
13. REST security<br />
<br />
<b>javax.ws.rs.core.SecurityContext interface to implement security programmatically</b><br />
<br />
<pre class="prettyprint"><code class="language-java">
GET
@Produces("text/plain;charset=UTF-8")
@Path("/hello")
public String updateUser(@Context SecurityContext sc) {
if (sc.isUserInRole("admin")) return "User will be updated";
throw new SecurityException("User is unauthorized.");
}
</pre><br />
<b>Applying annotations to your JAX-RS classes</b><br />
<br />
<b>DeclareRoles</b><br />
<br />
Declares roles.<br />
<br />
<b>DenyAll</b><br />
<br />
Specifies that no security roles are allowed to invoke the specified methods.<br />
<br />
<b>PermitAll</b><br />
<br />
Specifies that all security roles are allowed to invoke the specified methods.<br />
<br />
<b>RolesAllowed</b><br />
<br />
Specifies the list of security roles that are allowed to invoke the methods in the application.<br />
<br />
<b>RunAs</b><br />
<br />
Defines the identity of the application during execution in a J2EE container.<br />
<br />
<pre class="prettyprint"><code class="language-java">
@Path("/helloUser")
@RolesAllowed({"ADMIN", "DEV"})
public class helloUser {
@GET
@Path("updateUser")
@Produces("text/plain")
@RolesAllows("ADMIN")
public String updateUser() {
return "User Updated!";
}
}
</pre><br />
<b>Updating the web.xml deployment descriptor to define security configuration</b><br />
<br />
<pre class="brush:java"><security-constraint>
<web-resource-collection>
<web-resource-name>Users</web-resource-name>
<url-pattern>/user</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>default</realm-name>
</login-config>
<security-role>
<role-name>admin</role-name>
</security-role>
</pre><br />
Thanks for viewing this post. If you like it don't forget to provide comments<br />
<br />
<br />
</div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com1tag:blogger.com,1999:blog-8136669514202946995.post-72872223948506551742018-07-19T10:12:00.001+05:302018-07-19T10:12:12.774+05:30Spring<iframe allowfullscreen="" frameborder="0" height="270" src="https://www.youtube.com/embed/Xan_yQi_das" width="480"></iframe>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com1tag:blogger.com,1999:blog-8136669514202946995.post-63144619236925241012018-07-15T15:23:00.004+05:302018-07-15T15:24:11.955+05:30Given Strings are anagrams or not using java<div dir="ltr" style="text-align: left;" trbidi="on"><br />
<br />
What is String Anagram?<br />
<br />
"An anagram is a type of word, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once. <br />
<br />
for Example: 'java' can be rearranged as - 'vaaj' or 'vjaa' -all characters are equal in both the words. So this is called string anagram.<br />
<br />
Now we will see how to write a java program to check whether given strings are anagram or not.<br />
<pre class="prettyprint"><code class="language-java">
package com.siva;
import java.util.Arrays;
public class StringAnagramTest {
public boolean isStringAnagram(String s1, String s2){
char[] charArray1 = s1.toCharArray();
char[] charArray2 = s2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
boolean stringAnagram = Arrays.equals(charArray1, charArray2);
return stringAnagram;
}
public static void main(String[] args) {
StringAnagramTest test = new StringAnagramTest();
String str1 ="test";
String str2 ="sett";
boolean stringAnagram = test.isStringAnagram(str1, str2);
if(stringAnagram){
System.out.println("Given Strings["+str1+"] and ["+str2 +"] are anagrams");
}else{
System.out.println("Given Strings["+str1+"] and ["+str2 +"] are not anagrams");
}
}
}
</code></pre><br />
<br />
We can provide any value as input for both the strings.<br />
<br />
<b>Detailed Explanation:</b><br />
<br />
Step 1: Convert given Strings into character array.<br />
<br />
Step 2: Sort the converted character array using <b>Arrays.sort</b><br />
<br />
Step 3: compare both the strings using <b>Arrays.equals</b><br />
<br />
There are different ways to implement the same logic by writing our own <b>sorting </b>and <b>equals </b>methods. this is simple way to find the result.<br />
<br />
<b>output:</b><br />
<br />
<pre class="prettyprint"><code class="language-java">
Given Strings[test] and [sett] are anagrams
</code></pre><br />
</div>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com0tag:blogger.com,1999:blog-8136669514202946995.post-75090419240190008142018-06-09T15:58:00.001+05:302018-06-09T15:58:07.037+05:30Puppet<iframe allowfullscreen="" frameborder="0" height="270" src="https://www.youtube.com/embed/6f4fp_6Vxuk" width="480"></iframe>Siva Rajuhttp://www.blogger.com/profile/14566222201625959875noreply@blogger.com0