Step 3: Now we need to create company.xml file under project- create one xml file add the below xml to that file.
siva34Male3500001/07/1983PresentBangaloreKarnatakaIndiaPermanentKadapaAndharaPradeshIndiaSanjay27Male5500001/07/1988PresentBangaloreKarnatakaIndiaPermanentHyderabadTelanganaIndiaMadhan34Male80000001/07/1983Present and PermanentBangaloreKarnatakaIndia
Step 4: Create pojo classes , which need to be parsed as per above xml.
i have created 3 classes - Company.java -> List of Employee.java -> List Of Address.java
Company.java - xmlroot elment is company which is there in xml.
package xmltofile;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="company")
public class Company {
private List employee = new ArrayList();
@XmlElement(name="employee")
public List getEmployee() {
return employee;
}
public void setEmployee(List employee) {
this.employee = employee;
}
}
Employee.java
package xmltofile;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
public class Employee {
private String name;
private int age;
private String gender;
private Double salary;
private String dob;
Listaddress = new ArrayList();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
@XmlElement
public ListgetAddress() {
return address;
}
public void setAddress(Listaddress) {
this.address = address;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
}
Address.java
package xmltofile;
import javax.xml.bind.annotation.XmlRootElement;
public class Address {
private String city;
private String type;
private String state;
private String country;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Step 6: Now we need to write test class to Parse the employee.xml using JAXB context and create the Flat file
and write the xml data into file at specified index.
XMLReaderAndWriteToFile.java
package xmltofile;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import com.ancientprogramming.fixedformat4j.format.FixedFormatManager;
import com.ancientprogramming.fixedformat4j.format.impl.FixedFormatManagerImpl;
import xmltofile.fixedformat.CompanyHeader;
import xmltofile.fixedformat.EmployeeHeader;
public class XMLReaderAndWriteToFile {
public static void main(String[] args) {
BufferedWriter bw = null;
try {
JAXBContext context = JAXBContext.newInstance(Company.class);
// Create Unmarshaller using JAXB context
Unmarshaller unmarshaller = context.createUnmarshaller();
System.out.println("xml file started to load...");
Company company = (Company) unmarshaller.unmarshal(new File("employee.xml"));
System.out.println("xml file loaded and parsed successfully..");
// Write to file with fixedformat
System.out.println("Flat file started to create...");
bw = new BufferedWriter(new FileWriter("fixedLength.txt", true));
System.out.println("empty flat file created...");
getCompanyHeader(bw);
System.out.println("company header written successfully to file.");
getEmployeeHeader(bw);
System.out.println("employee header written successfully to file.");
for (Employee employee : company.getEmployee()) {
EmployeeHeader employeeDetails = new EmployeeHeader();
employeeDetails.setNameHeader(employee.getName());
employeeDetails.setAgeHeader(String.valueOf(employee.getAge()));
employeeDetails.setGenderHeader(employee.getGender());
employeeDetails.setDobHeader(String.valueOf(employee.getDob()));
employeeDetails.setSalaryHeader(String.valueOf(employee.getSalary()));
String completeAddress = " ";
for (Address address : employee.getAddress()) {
String addressDetails = address.getCity() + " " + address.getState() + " " + address.getCountry()
+ " - " + address.getType();
completeAddress = completeAddress.concat(addressDetails) + " ";
}
employeeDetails.setAddressHeader(completeAddress);
FixedFormatManager manager1 = new FixedFormatManagerImpl();
String data1 = manager1.export(employeeDetails);
bw.write(data1);
bw.newLine();
}
System.out.println("Employee details written successfully to file.");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void getEmployeeHeader(BufferedWriter bw) throws IOException {
EmployeeHeader employeeHeader = new EmployeeHeader();
employeeHeader.setNameHeader("Employee Name");
employeeHeader.setAgeHeader("Age");
employeeHeader.setGenderHeader("Gender");
employeeHeader.setDobHeader("DOB");
employeeHeader.setSalaryHeader("Salary");
employeeHeader.setAddressHeader("Address");
FixedFormatManager manager = new FixedFormatManagerImpl();
String data = manager.export(employeeHeader);
bw.write(data);
bw.newLine();
bw.newLine();
bw.newLine();
}
private static void getCompanyHeader(BufferedWriter bw) throws IOException {
CompanyHeader companyHeader = new CompanyHeader();
companyHeader.setHeader1("ABC Company");
companyHeader.setHeader2("Bangalore");
companyHeader.setHeader3("India");
FixedFormatManager manager = new FixedFormatManagerImpl();
String data = manager.export(companyHeader);
bw.write(data);
bw.newLine();
bw.newLine();
bw.newLine();
}
}
Output file will be like this.
ABC Company Bangalore
Employee Name Age Gender Salary DOB Address
siva 34 Male 35000.0 01/07/1983 Bangalore Karnataka India - Present Kadapa AndharaPradesh India - Permanent
Sanjay 27 Male 55000.0 01/07/1988 Bangalore Karnataka India - Present Hyderabad Telangana India - Permanent
Madhan 34 Male 800000.0 01/07/1983 Bangalore Karnataka India - Present and Permanent
Thank you verymuch for viewing this post. If you like this don't forget to share.
This Post will explain , how to Deploy Spring Boot Application on Pivotal Cloud Foundry Platform
Now a days Cloud Computing and Microservice have become very popular concept and almost all the organizations are investing and adapting it very fast. Currently there are only
few popular cloud providers in the market and Pivotal Cloud Foundry is one of them. It is a PaaS(Platform AS A Servcie) service where we can easily deploy and manage our
applications and the Cloud Foundry will take care of the rest of the cloud based offerings like scalability, high availability etc.
Today we will learn to deploy spring boot application in Pivotal cloud foundry platform called as Pivotal Web Services.
Step 1: What is Cloud Foundry?
Cloud Foundry is an open-source platform as a service (PaaS) that provides you with a choice of clouds, developer frameworks, and application services. It is open source and it is governed by the Cloud Foundry Foundation. The original Cloud Foundry was developed by VMware and currently it is managed by Pivotal
Step 2: Now we need to install Cloud Foundary on Windows
Step 8: Provide necessary details and sign up the same.
Once sign up is completed, we can log into the Pivotal webservice console through the login screen of the pivotal web service console.
After providing login credentials successfully we will get into the cloud foundry console where we can see all the deployed applications, can monitor the applications and do many more activities. Here we need to add org and space etc...
Step 9: Once we have created org and space successfully.. now we need to deploy the spring boot application in PCF.
Step 10: Before that , Login in to PWS (Pivotal Webservice Console) using CLI
c:/> cf login -a api.run.pivotal.io
Provide username and password which is given , while registering the PWS.
same way we can use Logout
c:/> cf logout
Step 11: Now login and logout is working with out any issues.
Step 12: Now write simple spring boot application and run the same in locally.
If you want to write simple one follow the https://start.spring.io/ - which will create sample spring boot application for you and modify as per your requirment.
i have created one sample arthimetic operations spring boot application.. check in my previous post for the same.
add the below code into bootstrap.properties under src\main\resources
Step 19: This is how we will implement spring boot application and we can deploy the same in Pivotal Cloud Foundary.
Thank you very much for viewing this post. if you like this please share the same
If you face any issues.. write a comment and you will get reply the same
This post will explain you about , how to start pivotal Gemfire on Windows Step 1: What is Gemfire? In-Memory Data Grid powered by Apache Geode Scale your data services on demand to support high-performance, real-time apps you can check more info on Gemfire docs Step 2: Download - pivotal-gemfire-9.1.0.tar.gz using Download Pivotal Gemfire Step 3: Unzip the downloaded file and set the PATH in environement variables. Step 4: check the version of the pivotal gemfire, which is available in your system gfsh version --full Step 5: Now we need to create a locator - Go to the place which ever the location you want to create locator in command prompt. Step 6:Start the gfsh.bat file from command prompt. Step 7: start locator --name=test --J=-Dgemfire.http-service-port=8080 --J=-Dgemfire.http-service.bind-address=localhost or
gfsh>start locator --name=test --J=-Dgemfire.http-service-port=8080 --J=-Dgemfire.http-service-bind-address=LAPTOP-2U8NKC7I
Starting a Geode Locator in F:\softwares\CloudFoundary_apache_gemFire\pivotal-gemfire-9.1.0\bin\test...
.....
Locator in F:\softwares\CloudFoundary_apache_gemFire\pivotal-gemfire-9.1.0\bin\test on LAPTOP-2U8NKC7I[10334] as test is currently online.
Process ID: 11740
Uptime: 3 seconds
Geode Version: 9.1.0
Java Version: 1.8.0_131
Log File: F:\softwares\CloudFoundary_apache_gemFire\pivotal-gemfire-9.1.0\bin\test\test.log
JVM Arguments: -Dgemfire.enable-cluster-configuration=true -Dgemfire.load-cluster-configuration-from-dir=false -Dgemfire.http-service-port=8080 -Dgemfire.http-service-bind-address=LAPTOP-2U8NKC7I -Dgemfire.launcher.registerSignalHandlers=true -Djava.awt.headless=true -Dsun.rmi.dgc.server.gcInterval=9223372036854775806
Class-Path: F:\softwares\CloudFoundary_apache_gemFire\pivotal-gemfire-9.1.0\lib\geode-core-9.1.0.jar;F:\softwares\CloudFoundary_apache_gemFire\pivotal-gemfire-9.1.0\lib\geode-dependencies.jar
Successfully connected to: JMX Manager [host=LAPTOP-2U8NKC7I, port=1099]
Cluster configuration service is up and running.
gfsh>start pulse
Step 8: Open the start pulse
Step 9: Open the browser and enter port as 8080 -> http://laptop-2u8nkc7i:8080/pulse and provide username as admin and password as admin
Step 10 cluster details will display after successful login.
Thank you verymuch for viewing this post. If you like this post please write comment and share.
Step 2: Login into google cloud.
Step 3: Register Cloud application with free trail - Cloud Application Registration
Step 4:Create a new Project -
Provide necessary details and signup the same.
Step 5: Now you are completed signup process . Spring boot application needs to be deployed.
Step 6: Create a maven java project with name - helloworld-springboot and below code to pom.xml file.
4.0.0com.java.gcloud.springboothelloworld-springboot0.0.1-SNAPSHOTjarhelloworld-springbootDemo project for Spring Boot with google cloud1.8${java.version}${java.version}UTF-81.3.1org.springframework.bootspring-boot-starter-web1.5.7.RELEASEorg.springframework.bootspring-boot-maven-plugin1.5.7.RELEASErepackagecom.google.cloud.toolsappengine-maven-plugin${appengine.maven.plugin}
Step 7: Now we need to write controller class name HelloworldApplication.java
package com.java.gcloud.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class HelloworldApplication {
@RequestMapping("/")
public String home() {
return "Hello World.. Welcome to Spring Boot.. which is deployed on Google cloud appengine!";
}
@RequestMapping(value = "/add/{a}/{b}", method = RequestMethod.GET)
public String add(@PathVariable("a") int a,@PathVariable("b") int b) {
return "Addition of a["+a+"] and b ["+b+"]is ====== " + (a+b) ;
}
@RequestMapping(value = "/substract/{a}/{b}", method = RequestMethod.GET)
public String substract(@PathVariable("a") int a,@PathVariable("b") int b) {
return "Substract of a["+a+"] and b ["+b+"]is ====== " + (a-b) ;
}
@RequestMapping(value = "/multiply/{a}/{b}", method = RequestMethod.GET)
public String multiply(@PathVariable("a") int a,@PathVariable("b") int b) {
return "Multiply of a["+a+"] and b ["+b+"]is ====== " + (a*b) ;
}
@RequestMapping(value = "/division/{a}/{b}", method = RequestMethod.GET)
public String division(@PathVariable("a") int a,@PathVariable("b") int b) {
return "Division of a["+a+"] and b ["+b+"]is ====== " + (a/b) ;
}
public static void main(String[] args) {
SpringApplication.run(HelloworldApplication.class, args);
}
}
Step 8: Run the pom.xml file using mvn clean install
Step 9: Now we need to run the application. go to the directory , where jar created and run the
java -jar
another way to execute the application is right click on the HelloWorldApplication Run As- JavaApplication.
Step 10: Once spring boot started successfully then go to browser and hit http://localhost:8080 .
you should get the -Hello World.. Welcome to Spring Boot.. which is deployed on Google cloud appengine!
Step 11: That is done. Now we need to deploy this application on google cloud.
Step 12: Install the Google Cloud SDK for windows version and set the PATH in environment variables.
Step 13: Go to the place where pom.xml file is there in command prompt. gcloud config set project p7259000552 After this command mvn appengine:deploy
Step 14: You will get Build Success message. So application has been deployed successfully.
Step 15: Verify, whether it has been deployed or not - https://.appspot.com/
Step 16: This application will have simple math operations like add,sustarct,multiply,division if you click any of this links you will get appropriate results.
This post will explain you. How to work with Spring boot and Mysql CRUD(create,read,update,delete) operations
Step 1: Open eclipse and create a java project.. more details please check my previous post getting started with spring boot.
Step 2: create a new pom.xml file under project and the below code to that file.
package springboot.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class User {
@Id
@Column
private long id;
@Column
private String name;
@Column
private String gender;
@Column
private String country;
@Column
private String password;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Step 4: Create UserService and UserServiceImpl under package springboot.service
package springboot.service;
import java.util.List;
import springboot.model.User;
public interface UserService {
public List getUsers();
public List createOrUpdateUser( User user);
public List deleteUser( User user);
}
Step 5: Add below code in UserServiceImpl.
package springboot.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import springboot.dao.UserDAO;
import springboot.model.User;
@Component
public class UserServiceImpl implements UserService{
@Autowired
private UserDAO userDAO;
@Override
public List getUsers() {
return userDAO.getUsers();
}
public List createOrUpdateUser( User user){
return userDAO.createOrUpdateUser(user);
}
public List deleteUser( User user){
return userDAO.deleteUser(user);
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
}
Step 6: Create UserDAO and UserDAOImpl under package springboot.dao as mentioned below
package springboot.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.repository.CrudRepository;
import springboot.model.User;
@Transactional
public interface UserDAO {
public List getUsers();
public List createOrUpdateUser( User user);
public List deleteUser( User user);
}
Step 7: Add below code inside UserDAOImpl
package springboot.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import springboot.model.User;
@Component
public class UserDAOImpl implements UserDAO{
@Autowired
private SessionFactory sessionFactory;
public List getUsers(){
Criteria criteria = sessionFactory.openSession().createCriteria(User.class);
return criteria.list();
}
public List createOrUpdateUser( User user){
Session session = sessionFactory.openSession();
User oldUser = session.get(User.class, user.getId() );
//System.out.println("oldUser id["+ oldUser.getId()+"]");
if(oldUser == null){
session.save(user);
session.flush();
System.out.println("Created or Update Successful");
}
Criteria criteria = sessionFactory.openSession().createCriteria(User.class);
return criteria.list();
}
public List deleteUser( User user){
Session session = sessionFactory.openSession();
User oldUser = session.get(User.class, user.getId() );
if(oldUser != null){
session.delete(oldUser);
session.flush();
System.out.println("Deleted successfully");
}
Criteria criteria = sessionFactory.openSession().createCriteria(User.class);
return criteria.list();
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
Step 8: Create BeanConfig class. which will create EntityManagerFactory.
package springboot;
import javax.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BeanConfig {
@Autowired
private EntityManagerFactory entityManagerFactory;
@Bean
public SessionFactory getSessionFactory() {
if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
throw new NullPointerException("factory is not a hibernate factory");
}
return entityManagerFactory.unwrap(SessionFactory.class);
}
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
}
Step 9: Now we need to add code related to database details called application.properties
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
spring.datasource.url = jdbc:mysql://localhost:3306/employee?useSSL=false
# Username and password
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Step 10: Create a RestController class. Name it as UserController
package springboot;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import springboot.model.User;
import springboot.service.UserService;
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ResponseEntity userDetails() {
List userDetails = userService.getUsers();
return new ResponseEntity(userDetails, HttpStatus.OK);
}
@RequestMapping(value = "/create/{id}/{name}/{password}/{gender}/{country}/", method = RequestMethod.GET)
public ResponseEntity createOrUpdateUserDetails(@PathVariable("id") long id, @PathVariable("name") String name,
@PathVariable("password") String password,@PathVariable("gender") String gender,@PathVariable("country") String country) {
User user = new User();
user.setId(id);
user.setName(name);
user.setCountry(country);
user.setGender(gender);
user.setPassword(password);
List userDetails = userService.createOrUpdateUser(user);
return new ResponseEntity(userDetails, HttpStatus.OK);
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public ResponseEntity deleteUserDetails(@PathVariable("id") long id) {
User user = new User();
user.setId(id);
List userDetails = userService.deleteUser(user);
return new ResponseEntity(userDetails, HttpStatus.OK);
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
Step 11: Now we need to run this application through spring boot. So we have to write Application class.
package springboot;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
}
Step 12: Now we need to build and run this application.
Right click on the pom.xml file and Run As - clean install
Once that is done. Right click on the Application.java and Run As-> Java Application. Below details will be printed in Console
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.1.RELEASE)
2017-10-12 17:17:15.600 INFO 13036 --- [ main] springboot.Application : Starting Application on LAPTOP-2U8NKC7I with PID 13036 (F:\eclipse_workspace\spring_boot_first\target\classes started by Siva in F:\eclipse_workspace\spring_boot_first)
2017-10-12 17:17:15.626 INFO 13036 --- [ main] springboot.Application : No active profile set, falling back to default profiles: default
2017-10-12 17:17:16.033 INFO 13036 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@23bb8443: startup date [Thu Oct 12 17:17:15 IST 2017]; root of context hierarchy
Step 13: Use http://localhost:8080/list -- it will display all the records which is there inside user table.
If it askes username and password - then username will be - user and password will be check Using default security password: in console. that is your password.
Step 14: Use http://localhost:8080/create/16/sanju/sam/M/India/ - it will insert record inside DB and will display all the records from user table.
Step 15 : http://localhost:8080/delete/16 - it will delete where id is 16 and display all the results from user table.
Step 16 : Now we will learn how to create database and create a table.
Step 17: Install mysql and create database with name- employee. and create a table name called User with columns as mentioned below.
CREATE TABLE user (
id int(11) NOT NULL,
name varchar(45) DEFAULT NULL,
gender varchar(10) DEFAULT NULL,
password varchar(45) DEFAULT NULL,
country varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`))
Step 18: If you want to use another database. simply change the application.properties respective DB details and dialect along with respective connecter in pom.xml
Thanks for viewing this post. If you like this please share and write comments.