Showing posts with label Spring boot. Show all posts
Showing posts with label Spring boot. Show all posts

Thursday, May 13, 2021

19 - net sf jasperreports engine JRException Error retrieving field valu...

18 - Generate PDF with Jasperreport and Spring Boot SOLVED


In this tutorial, I show you how to generate a PDF with Jasperreport and Spring Boot .
application.properties:
   
 spring.datasource.url=jdbc:mysql://localhost:3306/YOURDATABASE?autoReconnect=true
spring.datasource.username=YOURUSERNAME
spring.datasource.password=YOURPASSWORD
spring.jpa.generate-ddl=true
	
   
  
POM.xml:
   



		<dependency>
    		<groupId>net.sf.jasperreports</groupId>
    		<artifactId>jasperreports</artifactId>
    		<version>6.16.0</version>
		</dependency>
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency> 
		
   
  
Main Java Class:
  
  package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ServiceJpasql001Application {

	public static void main(String[] args) {
		SpringApplication.run(ServiceJpasql001Application.class, args);
	}

}

  
Student Class:
  
  
  package com.example.demo.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="student")
public class Student{
 
	@Id
    @Column(name="stid")
	private int stid;
	
    @Column(name="name")
	private String name;
    
    @Column(name="programme")
	private String Programme;

	public int getStid() {
		return stid;
	}

	public void setStid(int stid) {
		this.stid = stid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getProgramme() {
		return Programme;
	}

	public void setProgramme(String programme) {
		Programme = programme;
	}

	public Student(int stid, String name, String programme) {
		super();
		this.stid = stid;
		this.name = name;
		Programme = programme;
	}

	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	  
}
  
  
StudentRepository :
  
  
  package com.example.demo.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import com.example.demo.model.Student;

public interface StudentRepository extends JpaRepository {
  	List findByName(String name);
}
  
  
StudentService:
  
  
  package com.example.demo.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.model.Student;
import com.example.demo.repository.StudentRepository;

@Service
public class StudentService {

	@Autowired
	private StudentRepository studentRepository;
	
	public Student addStudent(Student student) {
		
		return studentRepository.save(student);
	}
	
	
  public void deleteStudent(Student student) {
		
		 studentRepository.delete(student);
	}
  
	public List getStudent() {
		
		return studentRepository.findAll();
	}
	
    public List getStudentByName(String name) {
		
		return studentRepository.findByName(name);
	}
}
  
  
StudentController:
  
  
  package com.example.demo.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.Student;
import com.example.demo.service.StudentService;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.util.JRLoader;

@RestController
public class StudentController {

	
	@Autowired
	StudentService studentService;
	
	@RequestMapping("/all")
	public List getStudent() {		
		return studentService.getStudent();
	}
	
	@RequestMapping("/studentByName/{name}")
	public List getStudentByName(@PathVariable String name) {		
		return studentService.getStudentByName(name);
	}
	
	@RequestMapping("/save")
	public  Student  saveStudent(@RequestBody Student student) {		
		return studentService.addStudent(student);
	}
	
	@RequestMapping("/delete")
	public  void  deleteStudent(@RequestBody Student student) {		
		 studentService.deleteStudent(student);
	}
	
	
	@RequestMapping("/pdf")
	
	  public void getReportsinPDF(HttpServletResponse response) throws JRException, IOException {
	    	
		 //Compiled report
		InputStream jasperStream = (InputStream) this.getClass().getResourceAsStream("/StudentList.jasper");
	      
	    //Adding attribute names
	    Map params = new HashMap<>();
	    params.put("stid","stid");
	    params.put("name","name");
	    params.put("programme","programme");
	    
	   // Fetching the student from the data database.
        final JRBeanCollectionDataSource source = new JRBeanCollectionDataSource(studentService.getStudent());
        
	    JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperStream);
	    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, source);

	    response.setContentType("application/x-pdf");
	    response.setHeader("Content-disposition", "inline; filename=StudentList.pdf");

	    final ServletOutputStream outStream = response.getOutputStream();
	    JasperExportManager.exportReportToPdfStream(jasperPrint, outStream);
	  }
}

  
  

17 - Unable to locate Attribute with the the given name XXX on this Man...

Dev Tips#64 Connect Jaspersoft Studio to a JDBC Database Data Adapter li...

Saturday, May 25, 2019

13 – Spring boot : connecting to MongoDB


Spring boot connection to mongoDB


application.properties

    
#mongodb
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mongotuto
 
#logging
logging.level.org.springframework.data=debug
logging.level.=error
    
  

POM.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>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.4.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.example</groupId>
 <artifactId>SpringBootMongoDB03</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringBootMongoDB03</name>
 <description>Demo project for Spring Boot</description>

 <properties>
  <java.version>1.8</java.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-mongodb</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>
  
  


Application Main class


package com.example.discovery;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootMongoDb03Application {

 public static void main(String[] args) {
  SpringApplication.run(SpringBootMongoDb03Application.class, args);
 }

}


  


Entity Car

package com.example.discovery;

import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "Car")
public class Car {

 @Id 
 public ObjectId _id;
 public String brand;
 public String name;
 public String color;
 
 public Car(ObjectId _id, String name, String brand, String color) {
      this._id = _id;
      this.name = name;
      this.brand = brand;
      this.color = color;
    }

 public ObjectId get_id() {
  return _id;
 }

 public void set_id(ObjectId _id) {
  this._id = _id;
 }

 public String getbrand() {
  return brand;
 }

 public void setbrand(String brand) {
  this.brand = brand;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getcolor() {
  return color;
 }

 public void setcolor(String color) {
  this.color = color;
 }
 
 
}

  



CarRepository

package com.example.discovery;

import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface CarRepository extends MongoRepository {
   Car findBy_id(ObjectId _id);
 }
  


CarController

package com.example.discovery;

import java.util.List;

import javax.validation.Valid;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/cars")
public class CarController {
  @Autowired
  private CarRepository repository;
  
  @RequestMapping(value = "/", method = RequestMethod.GET)
  public List getAllCars() {
    return repository.findAll();
  }
  
  @RequestMapping(value = "/{id}", method = RequestMethod.GET)
  public Car getCarById(@PathVariable("id") ObjectId id) {
    return repository.findBy_id(id);
  }
  
  @RequestMapping(value = "/", method = RequestMethod.POST)
  public Car createCar(@Valid @RequestBody Car Cars) {
    Cars.set_id(ObjectId.get());
    repository.save(Cars);
    return Cars;
  }
  
  @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
  public void deleteCar(@PathVariable ObjectId id) {
    repository.delete(repository.findBy_id(id));
  }
  
  @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
  public void modifyCarById(@PathVariable("id") ObjectId id, @Valid @RequestBody Car Cars) {
    Cars.set_id(id);
    repository.save(Cars);
  }
  
 
}

  


This is just a trick, hope it paved your way out. 

Saturday, May 4, 2019

12 - Spring boot Introduction to Unit Testing with JUnit Hello World



POM.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>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.4.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.example</groupId>
 <artifactId>TestingTuto12</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>TestingTuto12</name>
 <description>Demo project for Spring Boot</description>

 <properties>
  <java.version>1.8</java.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>

   
  


TestingTuto12Application


package com.example.testingtuto12;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestingTuto12Application {

 public static void main(String[] args) {
  SpringApplication.run(TestingTuto12Application.class, args);
 }

}

  


GreetingController


package com.example.testingtuto12;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {
 
 @RequestMapping("/greeting")
 public Boolean sendGreeting() {
  
  return true;
 }

}

  


TestingTuto12ApplicationTests


package com.example.testingtuto12;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

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;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestingTuto12ApplicationTests {

 @Test
 public void contextLoads() {
 }
 
 @Autowired
 public GreetingController greetingController;
 @Test
 public void testSendGreeting() {
  
  Boolean greeting = greetingController.sendGreeting();
  //assertEquals(greeting, "Hello World Dude!");
  assertTrue(greeting);
 }
 

}

  


To run the test, right click the testSendGreeting() method and select run as JUnit test as shown below



Wednesday, May 1, 2019

11 - Spring boot Consuming a microservice with RestTemplate and Eureka



Part 1 to install Eureka Server and let it discover the Eureka client


application.properties

  
server.port=8080
spring.application.name=consumer-service

  
  

POM.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>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.4.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.example</groupId>
 <artifactId>Tuto10EurekaClientConsumer</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>Tuto10EurekaClientConsumer</name>
 <description>Demo project for Spring Boot</description>

 <properties>
  <java.version>1.8</java.version>
  <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>

 <dependencyManagement>
  <dependencies>
   <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-dependencies</artifactId>
    <version>${spring-cloud.version}</version>
    <type>pom</type>
    <scope>import</scope>
   </dependency>
  </dependencies>
 </dependencyManagement>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>

  
  


Tuto10EurekaClientConsumerApplication


package com.example.clientConsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
public class Tuto10EurekaClientConsumerApplication {

 public static void main(String[] args) {
  SpringApplication.run(Tuto10EurekaClientConsumerApplication.class, args);
 }
 
    @Bean
    @LoadBalanced
 public RestTemplate restTemplate() {
  
  return new RestTemplate();
 }
}

  


ClientConsumerController


package com.example.clientConsumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ClientConsumerController {
 
 @Autowired
 RestTemplate restTemplate;
 
 @RequestMapping("/consumer")
 public String getClientMessage() {
  
  String url = "http://localhost:8081/hello";
  String url1 = "http://myclient-service/hello";
  String res = restTemplate.getForObject(url1, String.class);
  return "Message : "+res;
 }

}

  


This is just a trick, hope it paved your way out.