Mostrar mensagens com a etiqueta Spring. Mostrar todas as mensagens
Mostrar mensagens com a etiqueta Spring. Mostrar todas as mensagens

29 maio 2024

Building a Generative AI Application with Spring AI





@Service
public class SpringAIService {

    @Autowired
    AiClient aiClient;

    @Value("${spring.ai.openai.apikey}")
    private String apiKey;

    @Value("${spring.ai.openai.imageUrl}")
    private String openAIImageUrl;


    public String getJoke(String topic){
        PromptTemplate promptTemplate = new PromptTemplate("""
                Crafting a compilation of programming jokes for my website. Would you like me to create a joke about {topic}?
                """);
        promptTemplate.add("topic", topic);
        return this.aiClient.generate(promptTemplate.create()).getGeneration().getText();
    }

    public String getBook(String category, String year) {
        PromptTemplate promptTemplate = new PromptTemplate("""
                I would like to research some books. Please give me a book about {category} in {year} to get started?
                But pick the best best you can think of. I'm a book critic. Ratings are great help.
                And who wrote it? And who help it? Can you give me a short plot summary and also it's name?
                But don't give me too much information. I don't want any spoilers.
                And please give me these details in the following JSON format: category, year, bookName, author, review, smallSummary.
                """);
        Map.of("category", category, "year", year).forEach(promptTemplate::add);
        AiResponse generate = this.aiClient.generate(promptTemplate.create());
        return generate.getGeneration().getText();
    }


    public InputStreamResource getImage(@RequestParam(name = "topic") String topic) throws URISyntaxException {
        PromptTemplate promptTemplate = new PromptTemplate("""
                 I am really bored from online memes. Can you create me a prompt about {topic}.
                 Elevate the given topic. Make it sophisticated.
                 Make a resolution of 256x256, but ensure that it is presented in json.
                 I want only one image creation. Give me as JSON format: prompt, n, size.
                """);
        promptTemplate.add("topic", topic);
        String imagePrompt = this.aiClient.generate(promptTemplate.create()).getGeneration().getText();

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + apiKey);
        headers.add("Content-Type", "application/json");
        HttpEntity httpEntity = new HttpEntity<>(imagePrompt,headers);

        String imageUrl = restTemplate.exchange(openAIImageUrl, HttpMethod.POST, httpEntity, GeneratedImage.class)
                .getBody().getData().get(0).getUrl();
        byte[] imageBytes = restTemplate.getForObject(new URI(imageUrl), byte[].class);
        assert imageBytes != null;
        return new InputStreamResource(new java.io.ByteArrayInputStream(imageBytes));
    }
}




@RestController
@RequestMapping("/api/v1")
public class SpringAIController {
@Autowired
SpringAIService aiService;
@GetMapping("/joke")
public String getJoke(@RequestParam String topic) {
return aiService.getJoke(topic);
}
@GetMapping("/book")
public String getBook(@RequestParam(name = "category") String category, @RequestParam(name = "year") String year) {
return aiService.getBook(category, year);
}
@GetMapping(value = "/image", produces = "image/jpeg")
public ResponseEntity getImage(@RequestParam(name = "topic") String topic) throws URISyntaxException {
return ResponseEntity.ok().body(aiService.getImage(topic));
}
}






09 dezembro 2021

Microservices Using Spring Boot and Spring Cloud #1


Text Source: AmigosCode
In this series I will teach you how to build microservices with spring boot, spring cloud and kubernetes. In this first video I will give the microservices architecture overview and will build one microservice that connects to its own database running on docker.

25 novembro 2021

Spring Security | FULL COURSE


Text Source: AmigosCode
Spring Security is a powerful and highly customisable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements In this full course you will learn everything in detail about Spring Security. Before you begin this course you need to at least have a basic knowledge about Java and Spring Boot.
👉🏾Download repo here: http://bit.ly/2PujUEn or git clone git@github.com:amigoscode/spring-boot-security-course.git 👉🏾Full course also available here: https://amigoscode.com/courses/spring... 👉🏾Join private Facebook group: http://bit.ly/2FbuIkx


Other info

17 outubro 2015

Web Article - Spring JMS Example

Java Messaging Service (JMS) is a standard messaging API used to send and receive messages.

Spring simplifies the use of JMS API by providing another layer around the JMS layer.

This layer provides convenience methods for sending and receiving messages, as well as manages the creation and release of resources like the connection object.

The JmsTemplate class is the main class which we will be using often to work with the JMS API.

Dependencies

 4.0.0
 com.javacodegeeks.camel
 springQuartzScheduler
 0.0.1-SNAPSHOT
 
  
   org.springframework
   spring-core
   4.1.5.RELEASE
  
  
   org.springframework
   spring-context
   4.1.5.RELEASE
  
  
   org.springframework
   spring-jms
   4.1.5.RELEASE
  
  
   org.apache.activemq
   activemq-all
   5.12.0
  
 
 

Read full atricle here.

15 julho 2015

Security for Microservices with Spring and OAuth2



OAuth 2 Developers Guide

Introduction 
This is the user guide for the support for OAuth 2.0. For OAuth 1.0, everything is different, so see its user guide. This user guide is divided into two parts, the first for the OAuth 2.0 provider, the second for the OAuth 2.0 client. For both the provider and the client, the best source of sample code is the integration tests and sample apps.

20 fevereiro 2014

Web Article - Spring 3 and JPA with Hibernate

This article shows how to set up Spring with JPA, using Hibernate as a persistence provider.

The JPA Spring Configuration with Java
@Configuration
@EnableTransactionManagement
public class PersistenceJPAConfig{
 
   @Bean
   public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
      LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
      em.setDataSource(dataSource());
      em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
 
      JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
      em.setJpaVendorAdapter(vendorAdapter);
      em.setJpaProperties(additionalProperties());
 
      return em;
   }
 
   @Bean
   public DataSource dataSource(){
      DriverManagerDataSource dataSource = new DriverManagerDataSource();
      dataSource.setDriverClassName("com.mysql.jdbc.Driver");
      dataSource.setUrl("jdbc:mysql://localhost:3306/spring_jpa");
      dataSource.setUsername( "tutorialuser" );
      dataSource.setPassword( "tutorialmy5ql" );
      return dataSource;
   }
 
   @Bean
   public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
      JpaTransactionManager transactionManager = new JpaTransactionManager();
      transactionManager.setEntityManagerFactory(emf);
 
      return transactionManager;
   }
 
   @Bean
   public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
      return new PersistenceExceptionTranslationPostProcessor();
   }
 
   Properties additionalProperties() {
      return new Properties() {
         {  // Hibernate Specific: 
            setProperty("hibernate.hbm2ddl.auto", "create-drop");
            setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
         }
      };
   }
}
The JPA Spring Configuration with XML

 
   
      
      
      
         
      
      
         
            create-drop
            org.hibernate.dialect.MySQL5Dialect
         
      
   
 
   
      
      
      
      
   
 
   
      
   
   
 
   
 

This Spring JPA Tutorial can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.
Source and full article in Baeldung.com


03 fevereiro 2014

Spring Framework 4 - A Guided Tour


About:
Spring Framework 4 builds the foundation for the next major generation of the Java application framework. The talk gives a practical overview about fundamental infrastructure improvements such as Java 8 support and the integration with the latest Java EE APIs. It also covers major enhancements all across the framework such as advanced support for Groovy, hypermedia aspects for REST web services as well as WebSockets support. Filmed at JAX London 2013.

More information in http://spring.io/

17 novembro 2013

Web Tutorials

Web Tutorials

JAVA
Simple Java Database Swing Application
How to Send Email from Java Program with Example
Java ResourceBundle Example

Creating Maven Projects
Hibernate 3 with Maven 2 and MySQL 5 Example (XML Mapping and Annotation)
How to create a EJB 3.x project using Maven in Eclipse – Part 1
Setup of Dynamic Web Project using Maven
Create Web Application Project with Maven Example

JMS
Spring JMS Example

Java EE7 and Maven
Java EE7 and Maven project for newbies - part1 part2 part3 part4 part5 part6 part7 part8
Spring JPA Data + Hibernate + MySQL + MAVEN
Spring MVC Hello World Example
Spring MVC File Upload Example
Spring MVC beginner tutorial with Spring Tool Suite IDE
Upload Files to Database with Spring MVC and Hibernate

Logging 
Logback
Logback Configuration Example

WELD - Java Contexts and Dependency Injection for the Java EE platform (CDI)
DI (Dependency Injection) / CDI – Basics
Writing JSR-352 style jobs with Spring Batch Part 2: Dependency injection

Spring Data MongoDB
Spring Data MongoDB with Java config

JPA
JPA Tutorial: Setting Up JPA in a Java SE Environment
JPA Tutorial: Mapping Entities – Part 1 - Part 2 - Part 3

Hibernate
Hibernate annotations example
Hibernate tutorial with Eclipse

Persistence
The DAO with JPA and Spring
How to maintain history of tables in Hibernate

Android Tutorials
Android Development Tutorial

01 junho 2013

Setup of Dynamic Web Project using Maven

Good article that show how to create a Dynamic Web Project using Maven.
Full article here.

In same blog i found other interesting article about
Spring JPA Data + Hibernate + MySQL + MAVEN that show how we can develop a web-applications with the help of Spring MVC.