Consuming REST API and getting 404 ErrorCode - rest

Here is the information for my REST Service.
EndPoint https://spectrumcore.myCompany.com
Resources : /spectrum-core/services/customer/ept/getSoloIdentifiersV1x0
Here is my code.
package com.spectrum.biller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class BillerApplication {
private static final Logger log = LoggerFactory.getLogger(BillerApplication.class);
public static void main(String[] args) {
SpringApplication.run(BillerApplication.class, args);
}
}
package com.spectrum.biller.controllers;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.spectrum.biller.exception.BillerException;
import com.spectrum.biller.model.SoloIdentifiersRequest;
import com.spectrum.biller.model.SoloIdentifiersResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
#RestController
#RequestMapping("/biller")
#ComponentScan("com.spectrum.biller")
public class BillerControllers {
private static final Logger log = LoggerFactory.getLogger(BillerControllers.class);
#Value("${biller.service.url}")
private String billerServiceUrl;
#GetMapping(value = "/soloIdentifiers", produces= {"application/json"})
#ResponseBody
public SoloIdentifiersResponse getSoloIdentifiers(
//#ModelAttribute SoloIdentifiersRequest soloIdentifiersRequest
#RequestParam String systemID,
#RequestParam String divisionID,
#RequestParam String accountNumber
) {
try {
RestTemplate restTemplate = new RestTemplate();
SoloIdentifiersRequest soloIdentifiersRequest = new SoloIdentifiersRequest();
soloIdentifiersRequest.setSystemID(systemID);
soloIdentifiersRequest.setDivisionID(divisionID);
soloIdentifiersRequest.setAccountNumber(accountNumber);
SoloIdentifiersResponse soloIdentifiersResponse =
restTemplate.getForObject(billerServiceUrl, SoloIdentifiersResponse.class, soloIdentifiersRequest);
return soloIdentifiersResponse;
} catch ( Exception e) {
throw new BillerException("Error in Biller Client " + e.getMessage() + e);
}
}
}
My application.yml file
server:
port : 8080
biller.service:
url: https://spectrumcore.myCompany.com/spectrum-core/services/customer/ept/getSoloIdentifiersV1x0
package com.spectrum.biller.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties
public class SoloIdentifiersRequest {
private String systemID;
private String divisionID;
private String accountNumber;
public String getSystemID() {
return systemID;
}
public void setSystemID(String systemID) {
this.systemID = systemID;
}
public String getDivisionID() {
return divisionID;
}
public void setDivisionID(String divisionID) {
this.divisionID = divisionID;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
#Override
public String toString() {
return "SoloIdentifiersRequest [systemID=" + systemID + ", divisionID=" + divisionID + ", accountNumber="
+ accountNumber + "]";
}
}
package com.spectrum.biller.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties
public class SoloIdentifiersResponse {
private String uCAN;
private String divisionID;
private String accountNumber;
private String locationNumber;
private String customerNumber;
private String soloAccountNumber;
private String soloLocationNumber;
private String soloPartyID;
private String billingStationLevel1Code;
private String billingStationLevel2Code;
private String billingStationID;
private String sourceFTACode;
public String getuCAN() {
return uCAN;
}
public void setuCAN(String uCAN) {
this.uCAN = uCAN;
}
public String getDivisionID() {
return divisionID;
}
public void setDivisionID(String divisionID) {
this.divisionID = divisionID;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getLocationNumber() {
return locationNumber;
}
public void setLocationNumber(String locationNumber) {
this.locationNumber = locationNumber;
}
public String getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber(String customerNumber) {
this.customerNumber = customerNumber;
}
public String getSoloAccountNumber() {
return soloAccountNumber;
}
public void setSoloAccountNumber(String soloAccountNumber) {
this.soloAccountNumber = soloAccountNumber;
}
public String getSoloLocationNumber() {
return soloLocationNumber;
}
public void setSoloLocationNumber(String soloLocationNumber) {
this.soloLocationNumber = soloLocationNumber;
}
public String getSoloPartyID() {
return soloPartyID;
}
public void setSoloPartyID(String soloPartyID) {
this.soloPartyID = soloPartyID;
}
public String getBillingStationLevel1Code() {
return billingStationLevel1Code;
}
public void setBillingStationLevel1Code(String billingStationLevel1Code) {
this.billingStationLevel1Code = billingStationLevel1Code;
}
public String getBillingStationLevel2Code() {
return billingStationLevel2Code;
}
public void setBillingStationLevel2Code(String billingStationLevel2Code) {
this.billingStationLevel2Code = billingStationLevel2Code;
}
public String getBillingStationID() {
return billingStationID;
}
public void setBillingStationID(String billingStationID) {
this.billingStationID = billingStationID;
}
public String getSourceFTACode() {
return sourceFTACode;
}
public void setSourceFTACode(String sourceFTACode) {
this.sourceFTACode = sourceFTACode;
}
#Override
public String toString() {
return "SoloIdentifiersResponse [uCAN=" + uCAN + ", divisionID=" + divisionID + ", accountNumber="
+ accountNumber + ", locationNumber=" + locationNumber + ", customerNumber=" + customerNumber
+ ", soloAccountNumber=" + soloAccountNumber + ", soloLocationNumber=" + soloLocationNumber
+ ", soloPartyID=" + soloPartyID + ", billingStationLevel1Code=" + billingStationLevel1Code
+ ", billingStationLevel2Code=" + billingStationLevel2Code + ", billingStationID=" + billingStationID
+ ", sourceFTACode=" + sourceFTACode + "]";
}
}
My url to test the app.
http://localhost:8080/biller/soloIdentifiers?systemID=ProvSvcs&divisionID=LBT.8150&accountNumber=8150300010008485
I am getting
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Jan 27 15:18:19 MST 2020
There was an unexpected error (type=Internal Server Error, status=500).
Error in Biller Client 400 : [{ "errorResponse" : { "errors" : [ { "code" : "1000", "description" : "Invalid Request Exception", "source" : "SPECTRUM_CORE" } ] } }]org.springframework.web.client.HttpClientErrorException$BadRequest: 400 : [{ "errorResponse" : { "errors" : [ { "code" : "1000", "description" : "Invalid Request Exception", "source" : "SPECTRUM_CORE" } ] } }]
Here is the input I am adding in soapUI and getting below response as well.
<GetSoloIdentifiersRequest>
<systemID>ProvSvcs</systemID>
<divisionID>LBT.8150</divisionID>
<accountNumber>8150300010008485</accountNumber>
</GetSoloIdentifiersRequest> <getSoloIdentifiersResponse>
<uCAN>57922705670</uCAN>
<divisionID>LBT.8150</divisionID>
<accountNumber>8150300010008485</accountNumber>
<locationNumber>10992150205033</locationNumber>
<customerNumber>1104018630888</customerNumber>
<soloAccountNumber>71694273</soloAccountNumber>
<soloLocationNumber>235342534</soloLocationNumber>
<soloPartyID>55379641</soloPartyID>
<billingStationLevel1Code>8150</billingStationLevel1Code>
<billingStationLevel2Code>3000</billingStationLevel2Code>
<billingStationID>32455613</billingStationID>
<sourceFTACode>0010</sourceFTACode>
</getSoloIdentifiersResponse>

Related

Multiple MongoDB Connectors with SpringBoot REST api

I have three databases and I used MongoTemplate to have possibility connect to these databases from my application.
but when I use for example POST Method in Postman, I have error 404, not found.
In the console anything is fine and when I try http://localhost:8080/, also I have this error There was an unexpected error (type=Not Found, status=404).
No message available.
I searched too much and read so many things for example like https://dzone.com/articles/multiple-mongodb-connectors-with-spring-boot, but I could not undesrtood how can I define multiple MongoDB Connectors and fix this problem.
The MultipleMongoConfige:
package spring.mongo.thesis.config;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import com.mongodb.MongoClient;
import lombok.RequiredArgsConstructor;
#Configuration
#RequiredArgsConstructor
#EnableConfigurationProperties(MultipleMongoProperties.class)
public class MultipleMongoConfig {
private final MultipleMongoProperties mongoProperties = new MultipleMongoProperties();
#Primary
#Bean(name = "primaryMongoTemplate")
public MongoTemplate primaryMongoTemplate() throws Exception {
return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
}
#Bean(name = "secondaryMongoTemplate")
public MongoTemplate secondaryMongoTemplate() throws Exception {
return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));
}
#Bean(name = "thirdMongoTemplate")
public MongoTemplate thirdMongoTemplate() throws Exception {
return new MongoTemplate(thirdFactory(this.mongoProperties.getThird()));
}
#Bean
#Primary
public MongoDbFactory primaryFactory(final MongoProperties mongo) throws Exception {
return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
mongo.getDatabase());
}
#Bean
public MongoDbFactory secondaryFactory(final MongoProperties mongo) throws Exception {
return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
mongo.getDatabase());
}
#Bean
public MongoDbFactory thirdFactory(final MongoProperties mongo) throws Exception {
return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
mongo.getDatabase());
}
}
The PrimaryMongoConfig:
package spring.mongo.thesis.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
#Configuration
#EnableMongoRepositories(basePackages = "spring.mongo.thesis.repository.primary",
mongoTemplateRef = "primaryMongoTemplate")
public class PrimaryMongoConfig {
}
The MultipleMongoProperty:
package spring.mongo.thesis.config;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
#ConfigurationProperties(prefix = "mongodb")
public class MultipleMongoProperties {
private MongoProperties primary = new MongoProperties();
private MongoProperties secondary = new MongoProperties();
private MongoProperties third = new MongoProperties();
public MongoProperties getPrimary() {
return primary;
}
public void setPrimary(MongoProperties primary) {
this.primary = primary;
}
public MongoProperties getSecondary() {
return secondary;
}
public void setSecondary(MongoProperties secondary) {
this.secondary = secondary;
}
public MongoProperties getThird() {
return third;
}
public void setThird(MongoProperties third) {
this.third = third;
}
}
The PlayerController:
package spring.mongo.thesis.controller.primary;
import java.util.List;
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 spring.mongo.thesis.repository.primary.PlayerModel;
import spring.mongo.thesis.repository.primary.PlayerRepository;
#RestController
#RequestMapping("/player")
public class PlayerController {
#Autowired
private PlayerRepository repo;
//Getting Player ID
#GetMapping("/{nickname}")
public ResponseEntity<?> getPlayerByID(#PathVariable String nickname){
try {
PlayerModel p = repo.findById(nickname).get();
return ResponseEntity.ok(p);
} catch (Exception e) {
return ResponseEntity.status(404).body("Not Found!");
}
}
//Get All Players
#GetMapping
public List<PlayerModel> getAllPlayers() {
return repo.findAll();
}
//Delete Players
#DeleteMapping
public String deleteAllPlayers(){
repo.deleteAll();
return "Deleted!";
}
//#ExceptionHandler(MethodArgumentNotValidException.class)
//public void handleMissingParams(MissingServletRequestParameterException ex) {
// String name = ex.getParameterName();
//System.out.println(name + " parameter is missing");
// Actual exception handling
//}
//Create Player
#PostMapping
public ResponseEntity<?> createPlayer(#RequestBody #Valid PlayerModel player) {
PlayerModel findplayer = repo.findByNickname(player.getNickname());
if(findplayer != null) {
return ResponseEntity.status(409).body("Conflict!");
}
repo.save(player);
return ResponseEntity.status(201).body("Created!");
}
//Delete player By ID
#DeleteMapping("/{nickname}")
public ResponseEntity<?> deletePlayerByID(#PathVariable String nickname){
try {
PlayerModel p = repo.findById(nickname).get();
repo.deleteById(nickname);
return ResponseEntity.ok(p);
} catch (Exception e) {
return ResponseEntity.status(404).body("Not Found!");
}
}
//Update Player By ID
#PutMapping("/{nickname}")
public ResponseEntity<?> updatePlayerByID(
#PathVariable("nickname")String nickname,
#RequestBody #Valid PlayerModel player){
PlayerModel findplayer = repo.findByNickname(player.getNickname());
if(findplayer == null)
return ResponseEntity.status(404).
body("There is not Player with indicated Nickname!");
else
player.setNickname(nickname);
repo.save(player);
return ResponseEntity.ok(player);
}
}
The PlayerRepository:
package spring.mongo.thesis.repository.primary;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface PlayerRepository extends MongoRepository<PlayerModel, String>{
PlayerModel findByNickname(String nickname);
}
The PrimaryMongoConfig:
package spring.mongo.thesis.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
#Configuration
#EnableMongoRepositories(basePackages = "spring.mongo.thesis.repository.primary",
mongoTemplateRef = "primaryMongoTemplate")
public class PrimaryMongoConfig {
}
and my Application:
package spring.mongo.thesis.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
System.out.println("Hello World!");
}
}
The Player Class:
package spring.mongo.thesis.repository.primary;
import javax.validation.constraints.NotBlank;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Document(collection = "player")
public class PlayerModel {
#Id
#NotBlank
private String nickname;
#NotBlank
private String firstname;
#NotBlank
private String lastname;
#NotBlank
private String email;
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "PlayerModel [nickname=" + nickname + ", firstname=" + firstname + ", lastname=" + lastname + ", email="
+ email + "]";
}
}
The application.yml:
spring:
autoconfigure:
exclude: org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration
mongodb:
primary:
host: localhost
port: 27017
database: player-db
secondary:
host: localhost
port: 27017
database: game-db
third:
host: localhost
port: 27017
database: score-db

Rest Services - Tomcat able to start , homepage working fine but can't do any GET

`
https://www.pegaxchange.com/2016/08/11/jax-rs-java-rest-service-eclipse-tomcat/
I was trying to build working rest service by this guide.
And so far I am struggling.
I'm able to see Tomcat homepage via http://localhost:8080
But can't see any GET searches etc.
Tried to get by below URL
http://localhost:8080/SampleWebProject/search?name=
http://localhost:8080/SampleWebProject/productcatalog/search?name=
http://localhost:8080/SampleWebProject/myRestServices/search?name=
I'm still getting 404
Type Status Report
Message /SampleWebProject/search
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
What am I doing wrong?
Tried to build it 4 times from scratch, on different PC, doubled checked libraries, used Postman and Insomnia.
package com.pegaxchange.java.web.rest;
import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.server.ResourceConfig;
#ApplicationPath("restservices")
public class MyRESTServices extends ResourceConfig {
public MyRESTServices() {
packages("com.fasterxml.jackson.jaxrs.json");
packages("com.pegaxchange.java.web.rest");
}
}
----------
package com.pegaxchange.java.web.rest;
import java.util.*;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.pegaxchange.java.bean.Product;
import com.pegaxchange.java.bean.Status;
#Path("productcatalog")
public class ProductCatalogResource {
private static List<Product> productCatalog;
public ProductCatalogResource() {
initializeProductCatalog();
}
#GET
#Path("search")
#Produces(MediaType.APPLICATION_JSON)
public Product[] searchByName(#QueryParam("name") String name) {
List<Product> products = new ArrayList<Product>();
for (Product p : productCatalog) {
if (name != null && p.getName().toLowerCase().startsWith(name.toLowerCase())) {
products.add(p);
}
}
return products.toArray(new Product[products.size()]);
}
#POST
#Path("insert")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Status insert(Product product) {
productCatalog.add(product);
return new Status("SUCCESS", "Inserted " + product.getName());
}
#GET
#Path("getId")
#Produces(MediaType.APPLICATION_JSON)
public Product get(#QueryParam("id") int id) {
Product product = null;
for (Product p: productCatalog) {
if (id == p.getId() ) {
product = p;
break;
}
}
return product;
}
#POST
#Path("update")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Status update(Product product) {
Status stat = new Status("ERROR", "No ID " + product.getId());
Product prod = get(product.getId());
if (prod != null) {
if (product.getName() != null) {
prod.setName(product.getName());
}
if (product.getUnitPrice() != null) {
prod.setUnitPrice(product.getUnitPrice());
}
stat = new Status("Success", "updated ID " + product.getId());
}
return stat;
}
#DELETE
#Path("delete")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Status delete(#QueryParam("id") int id) {
Status stat = new Status("ERROR", "No ID " + id);
Product product = get(id);
if (product != null) {
productCatalog.remove(product);
stat = new Status("Success", "deleted" + product.getId());
}
return stat;
}
private void initializeProductCatalog() {
if (productCatalog == null) {
productCatalog = new ArrayList<Product>();
productCatalog.add(new Product(1, "Keyboard", 29.99D));
productCatalog.add(new Product(2, "Mouse", 9.95D));
productCatalog.add(new Product(3, "17\" Monitor", 159.49D));
productCatalog.add(new Product(4, "Hammer", 9.95D));
productCatalog.add(new Product(5, "Screwdriver", 7.95D));
productCatalog.add(new Product(6, "English Dictionary", 11.39D));
productCatalog.add(new Product(7, "A House in Bali", 15.99D));
productCatalog.add(new Product(8, "An Alaskan Odyssey", 799.99D));
productCatalog.add(new Product(9, "LCD Projector", 1199.19D));
productCatalog.add(new Product(10, "Smart Thermostat", 1199.19D));
}
}
}
---
package com.pegaxchange.java.bean;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Status implements Serializable {
private static final long serialVersionUID = -9130603850117689481L;
private String status;
private String message;
public Status() {} // needed for JAXB
public Status(String status, String message) {
this.status = status;
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
--
package com.pegaxchange.java.bean;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Product implements Serializable {
private static final long serialVersionUID = 6826191735682596960L;
private int id;
private String name;
private Double unitPrice;
public Product() {} // needed for JAXB
public Product(int id, String name, double unitPrice) {
this.id = id;
this.name = name;
this.unitPrice = unitPrice;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getUnitPrice() {
return unitPrice;
}`enter code here`
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
}
Just after i posted i founded a solution.
Because its clearly visible...
Wrong URLs
http://localhost:8080/SampleWebProject/restservices/productcatalog/search?name=Hammer
and now working fine.

Field vehicleRepository required a bean of type ..VehicleInterface that could not be found

I'm trying to #autowire repository reference from Service implementation class but still I'm getting bean not found error
I've already tried moving App.java file in the parent
App.java
package com.trucker;
import org.springframework.context.ApplicationContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class App
{
public static void main( String[] args ){
ApplicationContext applicationContext = SpringApplication.run(App.class,args);
}
}
VehicleService.java
package com.trucker.service;
import com.trucker.entity.Vehicle;
import com.trucker.repository.VehicleRepositoryInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class VehicleService implements VehicleServiceI {
#Autowired
VehicleRepositoryInterface vehicleRepository;
#Override
public Vehicle addVehicles(Vehicle vehicle) {
System.out.println(vehicle);
return vehicleRepository.save(vehicle);
}
}
VehicleRepositoryInterface.java
package com.trucker.repository;
import com.trucker.entity.Vehicle;
import org.springframework.context.annotation.Bean;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
public interface VehicleRepositoryInterface extends CrudRepository<Vehicle,String> {
}
VehicleController.java
package com.trucker.controller;
import com.trucker.entity.Vehicle;
import com.trucker.service.VehicleServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class VehicleController {
#Autowired
VehicleServiceI vehicleService;
#RequestMapping(path = "/vehicles", method = RequestMethod.PUT)
public String addVehicles(#RequestBody Vehicle vehicle) {
System.out.println("************IN THE CONTROLLER************"+vehicle);
vehicleService.addVehicles(vehicle);
return "";
}
}
Vehicle.java
package com.trucker.entity;
import javax.persistence.Entity;
import java.sql.Timestamp;
import javax.persistence.Id;
#Entity
public class Vehicle {
#Id
String vin;
String make;
String model;
int year;
int redlineRpm;
int maxFuelVolume;
Timestamp lastServiceDate;
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getRedlineRpm() {
return redlineRpm;
}
public void setRedlineRpm(int redlineRpm) {
this.redlineRpm = redlineRpm;
}
public int getMaxFuelVolume() {
return maxFuelVolume;
}
public void setMaxFuelVolume(int maxFuelVolume) {
this.maxFuelVolume = maxFuelVolume;
}
public Timestamp getLastServiceDate() {
return lastServiceDate;
}
public void setLastServiceDate(Timestamp lastServiceDate) {
this.lastServiceDate = lastServiceDate;
}
#Override
public String toString() {
return "Vehicle{" +
"vin='" + vin + '\'' +
", make='" + make + '\'' +
", model='" + model + '\'' +
", year=" + year +
", redlineRpm=" + redlineRpm +
", maxFuelVolume=" + maxFuelVolume +
", lastServiceDate=" + lastServiceDate +
'}';
}
}
application.properties
application.properties
server.port=8084
spring.datasource.url=jdbc:oracle:thin:#localhost:1521:xe
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.datasource.driver-class=oracle.jdbc.driver.OracleDriver
spring.datasource.username=system
spring.datasource.password=system
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
Directory Structure:
src
src/main
src/main/resources/application.properties
src/main/java
src/main/java/com.trucker
src/main/java/com.trucker/App.java
src/main/java/com.trucker.controller
src/main/java/com.trucker.controller.VehicleController
src/main/java/com.trucker.entity.Vehicle
src/main/java/com.trucker.repository
src/main/java/com.trucker.repository.VehicleRepositoryInterface
src/main/java/com.trucker.service
src/main/java/com.trucker.service.vehicleService
Take a look at this post it has clear answers
Spring boot autowiring an interface with multiple implementations
or
Spring autowire interface

JavaFx: Table view with different cell data type by row on the same column, HOW TO?

How to get different data class type on each row of the same column for a JavaFx table view?
Based on this post, here is a simple example that demonstrate how to get different data class type by row on the same column in a javaFx table view:
package application;
import java.time.LocalDateTime;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
public class Main extends Application {
private final TableView<Person<?>> tableView = new TableView<>();
private Person<Integer> person1 = new Person<>("Jacob", "Smith", 28, 4);
private Person<Integer> person2 = new Person<>("Isabella", "Johnson", 19, 5);
private Person<String> person3 = new Person<>("Bob", "The Sponge", 13, "Say Hi!");
private Person<LocalDateTime> person4 = new Person<>("Time", "Is Money", 45, LocalDateTime.now());
private Person<Double> person5 = new Person<>("John", "Doe", 32, 457.89);
private final ObservableList<Person<?>> data = FXCollections.observableArrayList(person1, person2, person3, person4,
person5);
#SuppressWarnings("unchecked")
#Override
public void start(Stage primaryStage) {
TableColumn<Person<?>, String> firstNameCol = new TableColumn<>("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));
TableColumn<Person<?>, String> lastNameCol = new TableColumn<>("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));
TableColumn<Person<?>, Integer> ageCol = new TableColumn<>("Age");
ageCol.setMinWidth(50);
ageCol.setCellValueFactory(new PropertyValueFactory<>("age"));
TableColumn<Person<?>, ?> particularValueCol = new TableColumn<>("Particular Value");
particularValueCol.setMinWidth(200);
particularValueCol.setCellValueFactory(new PropertyValueFactory<>("particularValue"));
tableView.setItems(data);
// Type safety: A generic array of Table... is created for a varargs
// parameter
// -> #SuppressWarnings("unchecked") to start method!
tableView.getColumns().addAll(firstNameCol, lastNameCol, ageCol, particularValueCol);
// Output in console the selected table view's cell value/class to check
// that the data type is correct.
SystemOutTableViewSelectedCell.set(tableView);
// To check that table view is correctly refreshed on data changed..
final Button agePlusOneButton = new Button("Age +1");
agePlusOneButton.setOnAction((ActionEvent e) -> {
Person<?> person = tableView.getSelectionModel().getSelectedItem();
try {
person.setAge(person.getAge() + 1);
} catch (NullPointerException npe) {
//
}
});
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(tableView, agePlusOneButton);
Scene scene = new Scene(new Group());
((Group) scene.getRoot()).getChildren().addAll(vbox);
primaryStage.setWidth(600);
primaryStage.setHeight(750);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public static class Person<T> {
private final StringProperty firstName;
private final StringProperty lastName;
private final IntegerProperty age;
private final ObjectProperty<T> particularValue;
private Person(String firstName, String lastName, Integer age, T particularValue) {
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
this.age = new SimpleIntegerProperty(age);
this.particularValue = new SimpleObjectProperty<T>(particularValue);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public StringProperty firstNameProperty() {
return firstName;
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
public StringProperty lastNameProperty() {
return lastName;
}
public Integer getAge() {
return age.get();
}
public void setAge(Integer age) {
this.age.set(age);
}
public IntegerProperty ageProperty() {
return age;
}
public T getParticularValue() {
return particularValue.get();
}
public void setParticularValue(T particularValue) {
this.particularValue.set(particularValue);
}
public ObjectProperty<T> particularValueProperty() {
return particularValue;
}
}
public static final class SystemOutTableViewSelectedCell {
#SuppressWarnings({ "rawtypes", "unchecked" })
public static void set(TableView tableView) {
tableView.getSelectionModel().setCellSelectionEnabled(true);
ObservableList selectedCells = tableView.getSelectionModel().getSelectedCells();
selectedCells.addListener(new ListChangeListener() {
#Override
public void onChanged(Change c) {
TablePosition tablePosition = (TablePosition) selectedCells.get(0);
Object val = tablePosition.getTableColumn().getCellData(tablePosition.getRow());
System.out.println("Selected Cell (Row: " + tablePosition.getRow() + " / Col: "
+ tablePosition.getColumn() + ") Value: " + val + " / " + val.getClass());
}
});
}
}
}

Error in annoting camel swagger Rest Service

I have created a rest Service using Apache Camel Swagger component. The rest service works fine but the request and response schema is not what i intended of.
The schema that i am trying to create is :
{
"GetStudentData": [
{
"RollNumber": "1",
"Name": "ABC",
"ClassName": "VII",
"Grade": "A"
}]
}
For this i have created a model as:
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "GetStudentData")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name="", propOrder={"studentInfo"})
public class StudentInfoWrapper {
#XmlElement(required=true)
private List<Student> studentInfo;
private double visiteddate;
public double getVisiteddate() {
return visiteddate;
}
public void setVisiteddate(double visiteddate) {
this.visiteddate = visiteddate;
}
public List<Student> getStudentInfo() {
return studentInfo;
}
public void setStudentInfo(List<Student> studentInfo) {
studentInfo = studentInfo;
}
}
And my student class is:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name="", propOrder={"RollNumber", "Name", "ClassName", "Grade"})
public class Student {
private String RollNumber;
private String Name;
private String ClassName;
private String Grade;
public String getRollNumber() {
return RollNumber;
}
public void setRollNumber(String rollNumber) {
RollNumber = rollNumber;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getClassName() {
return ClassName;
}
public void setClassName(String className) {
ClassName = className;
}
public String getGrade() {
return Grade;
}
public void setGrade(String grade) {
Grade = grade;
}
}
So when i load the above service into the swaggerUI it doesn't show the schema that i want.
How can i i get the desired schema. Looking forward to your answers.
Thanks in advance.