No files found for KieBase defaultKieBase - Drool-8.33.0.Final - drools

xls format`I am developing a spring boot restful service which need to use the Business Rule Management System. I have chosen the drools. Chosen the latest version.
I am using spring boot 2.7.7 version, drools version 8.33.0.Final & java 17 version.
Issue: I am not able to process the rules when I add in the .xlsx or .xls or .csv format.
I have tried with different options, but not working with .xlsx or .xls or .csv format. Any suggestion is welcome.
Warning error message in console:
No files found for KieBase defaultKieBase
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 https://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.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.codeusingjava</groupId>
<artifactId>boot-drools</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>boot-drools</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
<drools.version>8.33.0.Final</drools.version>
<!-- <drools.version>8.15.0.Beta</drools.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>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>${drools.version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-mvel</artifactId>
<version>${drools.version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-decisiontables</artifactId>
<version>${drools.version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>${drools.version}</version>
</dependency>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-ci</artifactId>
<version>${drools.version}</version>
</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>
Drools Configuration:
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.io.ResourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class DroolsConfiguration {
private final KieServices kieServices = KieServices.Factory.get();
#Bean
public KieContainer kieContainer() {
KieContainer kieCont = null;
try {
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
kieFileSystem.write(ResourceFactory.newClassPathResource("rules/discount.xlsx"));
KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
kb.buildAll();
KieModule kieModule = kb.getKieModule();
kieCont = kieServices.newKieContainer(kieModule.getReleaseId());
}catch(Exception exception) {
exception.printStackTrace();
}
return kieCont;
}
}
DepositRateCalculator.java
package com.codeusingjava.bootdrools.controller;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.codeusingjava.bootdrools.model.DepositRequest;
#RestController
public class DepositRateController {
#Autowired
private KieContainer kieContainer;
#RequestMapping(value = "/getInterestRate", method = RequestMethod.GET, produces = "application/json")
public String getInterest(#RequestParam(required = true) String loanType,
#RequestParam(required = true) Integer durationInYear, #RequestParam(required = true) Integer age) {
KieSession kieSession = kieContainer.newKieSession();
DepositRequest depositRequest = new DepositRequest(loanType, durationInYear, age);
kieSession.insert(depositRequest);
kieSession.fireAllRules();
kieSession.dispose();
return "The interest rate for this application is " + depositRequest.getInterestRate();
}
}
DepositRequest.java
package com.codeusingjava.bootdrools.model;
public class DepositRequest {
private String loanType;
private Integer durationInYear;
private Integer age;
private String interestRate;
public DepositRequest(String loanType, Integer durationInYear, Integer age) {
super();
this.loanType = loanType;
this.durationInYear = durationInYear;
this.age = age;
}
public String getLoanType() {
return loanType;
}
public void setLoanType(String loanType) {
this.loanType = loanType;
}
public Integer getDurationInYear() {
return durationInYear;
}
public void setDurationInYear(Integer durationInYear) {
this.durationInYear = durationInYear;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getInterestRate() {
return interestRate;
}
public void setInterestRate(String interestRate) {
this.interestRate = interestRate;
}
}
Console:
Tomcat initialized with port(s): 8080 (http)
2023-02-17 13:20:01.551 INFO 19264 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2023-02-17 13:20:01.551 INFO 19264 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.70]
2023-02-17 13:20:01.955 INFO 19264 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2023-02-17 13:20:01.955 INFO 19264 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1006 ms
**2023-02-17 13:20:02.891 WARN 19264 --- [ restartedMain] o.d.c.kie.builder.impl.KieProject : No files found for KieBase defaultKieBase
2023-02-17 13:20:03.073 INFO 19264 --- [** restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2023-02-17 13:20:03.099 INFO 19264 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2023-02-17 13:20:03.105 INFO 19264 --- [ restartedMain] c.c.bootdrools.BootDroolsApplication : Started BootDroolsApplication in 2.433 seconds (JVM running for 3.26)`
Tested URL: localhost:8080/getInterestRate?loanType=Fixed&age=45&durationInYear=1

Related

vlcj video runs in IDE but not externally

I am using vlcj-4.7.1 and IntelliJ.
I am using the code from https://www.tutorialspoint.com/vlcj/vlcj_play.htm
The code runs and plays the video when I run it inside the IDE, but when I run it using Windows Terminal, I receive:
Error: Unable to initialize main class alan.bartlett.videotester.App
Caused by: java.lang.NoClassDefFoundError: uk/co/caprica/vlcj/player/component/EmbeddedMediaPlayerComponent
Any ideas how to fix this ClassNotFoundError? I have installed VLC 3.0.17.4 if that info is useful.
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>
<groupId>alan.bartlett.videotester</groupId>
<artifactId>video-test-project</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>16</maven.compiler.source>
<maven.compiler.target>16</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>uk.co.caprica</groupId>
<artifactId>vlcj</artifactId>
<version>4.7.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.28</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>
<finalName>VideoPlayer</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.7.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>alan.bartlett.videotester.App</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
App.java
package alan.bartlett.videotester;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.net.URISyntaxException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import uk.co.caprica.vlcj.factory.discovery.NativeDiscovery;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
/**
* This example will open a window with a play button.
* pressing play will play the hardcoded mp4 video.
*/
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
// private static final String VIDEO_PATH = "C:\\Als-data\\asb.mp4";
private static String VIDEO_PATH = getAppPath() + "media\\asb.mp4";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private JButton playButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
System.out.println("Media Path: " + VIDEO_PATH);
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
JPanel controlsPane = new JPanel();
playButton = new JButton("Play");
controlsPane.add(playButton);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static String getAppPath() {
File pto = null;
String str = "";
try {
// pto = new File(App.class.getProtectionDomain().getCodeSource().getLocation().toURI());
pto = new File(App.class.getProtectionDomain().getCodeSource().getLocation().toURI());
if(pto.getAbsolutePath().contains("classes")) {
str = pto.getAbsolutePath();
String toRemove = "classes";
int x = str.indexOf(toRemove);
str = str.substring(0,x) + str.substring(x+toRemove.length(),str.length());
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
System.out.println("Absolute Path: " + pto.getAbsolutePath());
System.out.println("Path : " + pto.getPath());
System.out.println("getName: " + pto.getName());
System.out.println("str: " + str);
// return pto.getAbsolutePath();
return str;
}
public static void main( String[] args ){
boolean found = new NativeDiscovery().discover();
System.out.println(found);
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
}
}

Keycloak ThemeSelectorProviderFactory not a subtype error while adding custom user storage SPI

I’m trying to add a simple custom user storage SPI in keycloak 17.0.0. I have followed the keycloak documentation for creation of custom user storage SPI, But when I try to build kc I’m getting error:
ERROR: Failed to run 'build' command.
ERROR: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
[error]: Build step org.keycloak.quarkus.deployment.KeycloakProcessor#configureProviders threw an exception: java.util.ServiceConfigurationError: org.keycloak.theme.ThemeSelectorProviderFactory: keycloak.spi.test.file.PropertyFileUserStorageProviderFactory not a subtype
at java.base/java.util.ServiceLoader.fail(ServiceLoader.java:589)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNextService(ServiceLoader.java:1237)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNext(ServiceLoader.java:1265)
at java.base/java.util.ServiceLoader$2.hasNext(ServiceLoader.java:1300)
at java.base/java.util.ServiceLoader$3.hasNext(ServiceLoader.java:1385)
at org.keycloak.provider.DefaultProviderLoader.load(DefaultProviderLoader.java:60)
at org.keycloak.provider.ProviderManager.load(ProviderManager.java:94)
at org.keycloak.quarkus.deployment.KeycloakProcessor.loadFactories(KeycloakProcessor.java:456)
at org.keycloak.quarkus.deployment.KeycloakProcessor.configureProviders(KeycloakProcessor.java:254)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:882)
at io.quarkus.builder.BuildContext.run(BuildContext.java:277)
at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
at java.base/java.lang.Thread.run(Thread.java:829)
at org.jboss.threads.JBossThread.run(JBossThread.java:501)
ERROR: Build failure: Build failed due to errors
[error]: Build step org.keycloak.quarkus.deployment.KeycloakProcessor#configureProviders threw an exception: java.util.ServiceConfigurationError: org.keycloak.theme.ThemeSelectorProviderFactory: keycloak.spi.test.file.PropertyFileUserStorageProviderFactory not a subtype
at java.base/java.util.ServiceLoader.fail(ServiceLoader.java:589)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNextService(ServiceLoader.java:1237)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNext(ServiceLoader.java:1265)
at java.base/java.util.ServiceLoader$2.hasNext(ServiceLoader.java:1300)
at java.base/java.util.ServiceLoader$3.hasNext(ServiceLoader.java:1385)
at org.keycloak.provider.DefaultProviderLoader.load(DefaultProviderLoader.java:60)
at org.keycloak.provider.ProviderManager.load(ProviderManager.java:94)
at org.keycloak.quarkus.deployment.KeycloakProcessor.loadFactories(KeycloakProcessor.java:456)
at org.keycloak.quarkus.deployment.KeycloakProcessor.configureProviders(KeycloakProcessor.java:254)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:882)
at io.quarkus.builder.BuildContext.run(BuildContext.java:277)
at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
at java.base/java.lang.Thread.run(Thread.java:829)
at org.jboss.threads.JBossThread.run(JBossThread.java:501)
ERROR: org.keycloak.theme.ThemeSelectorProviderFactory: keycloak.spi.test.file.PropertyFileUserStorageProviderFactory not a subtype
For more details run the same command passing the '--verbose' option. Also you can use '--help' to see the details about the usage of the particular command.
POM.xml content is:
<?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>org.example</groupId>
<artifactId>keycloack-SPI-Demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-core</artifactId>
<version>17.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-server-spi</artifactId>
<version>17.0.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<finalName>my-user-provider</finalName>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<appendAssemblyId>false</appendAssemblyId>
</configuration>
</plugin>
</plugins>
</build>
</project>
I’m creating jar with mvn command mvn clean compile assembly:single and placing that jar in providers directory.
Content of my UserStorageFactory class is given below:
public class PropertyFileUserStorageProviderFactory implements UserStorageProviderFactory<PropertyFileUserStorageProvider> {
private static final String PROVIDER_NAME = "property-file";
protected Properties properties = new Properties();
private static final Logger logger = Logger.getLogger(PropertyFileUserStorageProviderFactory.class.getName());
#Override
public PropertyFileUserStorageProvider create(KeycloakSession keycloakSession, ComponentModel componentModel) {
return new PropertyFileUserStorageProvider(keycloakSession, componentModel, properties);
}
#Override
public String getId() {
return PROVIDER_NAME;
}
#Override
public void init(Config.Scope config) {
String path = config.get("path");
InputStream is = getClass().getClassLoader().getResourceAsStream(path);
if (is == null) {
logger.severe("Could not find users.properties in classpath");
} else {
try {
properties.load(is);
} catch (IOException ex) {
logger.severe("Failed to load users.properties file" + ex);
}
}
}
#Override
public void close() {
UserStorageProviderFactory.super.close();
}
#Override
public void postInit(KeycloakSessionFactory factory) {
UserStorageProviderFactory.super.postInit(factory);
}
#Override
public UserStorageProvider create(KeycloakSession session) {
return UserStorageProviderFactory.super.create(session);
}
#Override
public List<ProviderConfigProperty> getConfigProperties() {
return UserStorageProviderFactory.super.getConfigProperties();
}
#Override
public String getHelpText() {
return UserStorageProviderFactory.super.getHelpText();
}
#Override
public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel config) throws ComponentValidationException {
UserStorageProviderFactory.super.validateConfiguration(session, realm, config);
}
#Override
public void onCreate(KeycloakSession session, RealmModel realm, ComponentModel model) {
UserStorageProviderFactory.super.onCreate(session, realm, model);
}
#Override
public List<ProviderConfigProperty> getCommonProviderConfigProperties() {
return UserStorageProviderFactory.super.getCommonProviderConfigProperties();
}
#Override
public Map<String, Object> getTypeMetadata() {
return UserStorageProviderFactory.super.getTypeMetadata();
}
I'm not sure what I'm doing wrong.
Resolved it.
Just found that my file in META-INF file was name for ThemeSelectorProviderFactory instead of UserStorageProviderFactory.

What changes are required to run spring boot project in browser as localhost?

When I run the command for spring boot project:
mvn spring-boot:run
The code shows build success message, and it ends.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 14.084 s
[INFO] Finished at: 2019-06-03T11:28:11+05:30
[INFO] Final Memory: 64M/899M
[INFO] ------------------------------------------------------------------------
But I want to display the working code on browser on http://localhost:8080.
Application stops immediately instead of starting a web server, the project ends.
Does the code need any changes to run on localhost?
Here is my OMSApplication.java class
#EnableScheduling
#SpringBootApplication(exclude=DataSourceAutoConfiguration.class)
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class, UserDetailsServiceAutoConfiguration.class})
#EnableEnvironmentJKS
public class OMSApplication extends SpringBootServletInitializer{
private static final Logger log = LoggerFactory
.getLogger(OMSApplication.class);
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(
OMSApplication.class, args);
log.info(" Application context created: {}" , applicationContext);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(OMSApplication.class);
}
}
And here is pom.xml file:
<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.example.mpms.services</groupId>
<artifactId>oms-services</artifactId>
<!-- <version>0.0.1-SNAPSHOT</version>-->
<packaging>war</packaging>
<name>oms-services</name>
<description>oms services</description>
<parent>
<groupId>com.example.mpms</groupId>
<artifactId>mpms-oms</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.0.0.RELEASE</version>
<configuration>
<skip>true</skip>
<!-- <systemPropertyVariables>
<APIE_PLATFORM>DEV</APIE_PLATFORM>
<APIE_REGION>US</APIE_REGION>
<APIE_ZONE>STL</APIE_ZONE>
</systemPropertyVariables> -->
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>${mvn-site-plugin-version}</version>
</plugin>
</plugins>
</build>
</project>
I have not included all the dependencies here, as they are many.
And here is the controller class:
#RestController
public class OrderController {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
#Autowired
private KYCOrderService kycOrderService;
/**
* Health check URL for application via synapse.
*
* */
#GetMapping(value = "/health",produces = MediaType.TEXT_PLAIN_VALUE)
#ResponseBody
public ResponseEntity<String> healthCheck() {
String output = String.format("Heartbeat :%s", "Cumulus- Order Management Service: I'm healthy!");
LOGGER.info(output);
return new ResponseEntity<>(output,HttpStatus.OK);
}
#PostMapping(path="/oms/order/kyc", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
#ApiOperation(value = "Place an Offline KYC Order", notes = "Order is placed in central oms", response = OfflineKYCOrderResponse.class, tags={ "OfflineKYCOrderResponse", })
#ApiResponses(value = {
#ApiResponse(code = 200, message = "OfflineKYCOrderResponse creation OK", response = OfflineKYCOrderResponse.class),
#ApiResponse(code = 201, message = "Created", response = OfflineKYCOrderResponse.class),
#ApiResponse(code = 400, message = "Bad Request", response = OfflineKYCOrderResponse.class),
#ApiResponse(code = 401, message = "Unauthorized", response = OfflineKYCOrderResponse.class),
#ApiResponse(code = 403, message = "Forbidden", response = OfflineKYCOrderResponse.class),
#ApiResponse(code = 404, message = "Not Found", response = OfflineKYCOrderResponse.class)
})
public OfflineKYCOrderResponse placeOfflineKycOrder(#ApiParam(value = "Details of order to be placed" ,required=true)#RequestBody OfflineKYCOrderRequest offlineKYCOrder) {
LOGGER.info("OfflineKYCOrderRequest: {}" , offlineKYCOrder);
OfflineKYCOrderResponse errorResponse = offlineKYCOrder.validateInput();
if (null != errorResponse) {
LOGGER.info("OfflineKYCOrderResponse: {}" , errorResponse);
return errorResponse;
}
ReasonCodes processStatusCode = ReasonCodes.OMS000;
OfflineKYCOrderResponse offlineKYCOrderResponse = new OfflineKYCOrderResponse();
try {
KYCOrder createdKYCOrder = kycOrderService.saveOrder(new KYCOrder(offlineKYCOrder));
offlineKYCOrderResponse.setOrderNumber(createdKYCOrder.getOrder().getOrderId());
} catch (Exception e) {
processStatusCode = ReasonCodes.OMS001;
LOGGER.error("Failed to store order.", e);
} finally {
offlineKYCOrderResponse.setReasonCode(processStatusCode.toString());
offlineKYCOrderResponse.setReasonDescription(processStatusCode.getDescription());
}
LOGGER.info("OfflineKYCOrderResponse: {}" , offlineKYCOrderResponse);
return offlineKYCOrderResponse;
}
}
Can anyone help solving the problem?
You have not included the spring boot starter package in your pom.xml,
remove the parent dependency from the pom.xml file and replace it with the below depedency
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
Alternatively you can use the war from the target folder and deploy it using tomcat or any server of your choice.

How to test jersey restful api using jetty?

When I run test using grizzly2 follow steps here . Everything works fine. Then I tried jersey-test-framework-provider-jetty, exception happend:
MessageBodyReader not found for media type=text/html;charset=iso-8859-1, type=class com.example.resource.GenericPair, genericType=com.example.resource.GenericPair<java.lang.Integer, java.lang.String>.
HTTP 500 Server Error.
Response is:
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/>
<title>Error 500 </title>
</head>
<body>
<h2>HTTP ERROR: 500</h2>
<p>Problem accessing /test. Reason:
<pre> java.lang.NoSuchMethodError: org.eclipse.jetty.server.Response.getResponse(Ljavax/servlet/http/HttpServletResponse;)Lorg/eclipse/jetty/server/Response;</pre></p>
<hr />Powered by Jetty:// 9.3.10.v20160621<hr/>
</body>
</html>
May be It need some more configure using jetty. Here is my configure
#Override
protected Application configure() {
return new ResourceConfig(TestApi.class)
.register(JacksonFeature.class)
.register(JacksonJsonProvider.class)
.packages("com.example.api");
}
UPDATE
--------pom.xml---------
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-jetty</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<jersey.version>2.23.1</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jetty.version>9.3.10.v20160621</jetty.version>
</properties>
-------TestApiTest.java--------
public class TestApiTest extends JerseyTest {
#Override
protected Application configure() {
return new ResourceConfig(TestApi.class)
.register(JacksonFeature.class)
.register(JacksonJsonProvider.class)
.packages("com.example.api");
}
#Override
protected URI getBaseUri() {
return URI.create(super.getBaseUri().toString() + "");
}
#Override
protected void configureClient(ClientConfig config) {
super.configureClient(config);
}
#Test
public void testIndex() throws Exception {
Response response = target().path("test").request().get();
String responseMsg = response.readEntity(String.class);
assertEquals("this is test api", responseMsg);
}
#Test
public void testList() throws Exception {
Response response = target().path("test/list").request().get();
List<Pair> pairs = response.readEntity(new GenericType<List<Pair>>(){});//从response中读取泛型集合
assertEquals(3, pairs.size());
}
}
-----------ApiTest.java------------
#Path("test")
public class TestApi {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String index() {
System.out.println("-------------");
return "this is test api";
}
#GET
#Path("/list")
#Produces(MediaType.APPLICATION_JSON)
public List<Pair> list() {
List<Pair> pairs = new ArrayList<Pair>();
pairs.add(new Pair(1, "pair1"));
pairs.add(new Pair(2, "pair2"));
pairs.add(new Pair(3, "pair3"));
return pairs;
}
}

Where should i get all Jax-rs java implementation code in single place

I am planing to perform benchmark analysis on all Java JAX-RS implementations.
Looking single place(link/git) where i get code example to save my time.
I have created example long back may be it will help -
1. Sun Jersey 1.8 RestWebservice –
pom.xml
<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>WebservicePrj</groupId>
<artifactId>WebservicePrj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>WebservicePrj</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.example.rest</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
HelloWorldService.java
package com.example.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
#Path("/hello")
public class HelloWorldService {
#GET
#Path("/{param}")
public Response getMsg(#PathParam("param") String msg) {
String output = "Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
}
Track.java
package com.example;
import java.io.Serializable;
public class Track implements Serializable{
String title;
String singer;
//create getter & setter and override equals, hashcode & toString method
}
JSONService.java
package com.example.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.example.Track;
#Path("/json/metallica")
public class JSONService {
#GET
#Path("/get")
#Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON() {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
return track;
}
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
public Response createTrackInJSON(Track track) {
String result = "Track saved : " + track;
return Response.status(201).entity(result).build();
}
}
JerseyClientGet.java
package com.example.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientGet {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client
.resource("http://localhost:8080/WebservicePrj/rest/json/metallica/get");
ClientResponse response = webResource.accept("application/json")
.get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
//
webResource = client
.resource("http://localhost:8080/WebservicePrj/rest/hello/skhan");
response = webResource.accept("application/json")
.get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
JerseyClientPost.java
package com.example.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientPost {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client
.resource("http://localhost:8080/WebservicePrj/rest/json/metallica/post");
String input = "{\"singer\":\"Metallica\",\"title\":\"Fade To Black\"}";
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. Jboss RestEasy 2.2.1.GA RestWebservice –
pom.xml
<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>WebservicePrjResrEasy</groupId>
<artifactId>WebservicePrjResrEasy</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>WebservicePrjResrEasyName</name>
<description>WebservicePrjResrEasy des</description>
<repositories>
<repository>
<id>JBoss repository</id>
<url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>2.2.1.GA</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>2.2.1.GA</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>WebservicePrj</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- <context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param> -->
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>com.example.rest.JSONService</param-value>
</context-param>
<!-- this need same with resteasy servlet url-pattern -->
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
MessageRestService.java
package com.example.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
#Path("/message")
public class MessageRestService {
#GET
#Path("/{param}")
public Response printMessage(#PathParam("param") String msg) {
String result = "Restful example : " + msg;
return Response.status(200).entity(result).build();
}
}
Product.java
package com.example.rest;
import java.io.Serializable;
public class Product implements Serializable {
String name;
int qty;
//create getter & setter and override equals, hashcode & toString method
}
JSONService.java
package com.example.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
#Path("/json/product")
public class JSONService {
#GET
#Path("/get")
#Produces("application/json")
public Product getProductInJSON() {
Product product = new Product();
product.setName("iPad 3");
product.setQty(999);
return product;
}
#POST
#Path("/post")
#Consumes("application/json")
public Response createProductInJSON(Product product) {
String result = "Product created : " + product;
return Response.status(201).entity(result).build();
}
}
RESTEasyClientGet.java
package com.example.client;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.client.ClientProtocolException;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
public class RESTEasyClientGet {
public static void main(String[] args) {
try {
ClientRequest request = new ClientRequest(
"http://localhost:8080/WebservicePrjResrEasy/rest/json/product/get");
request.accept("application/json");
ClientResponse<String> response = request.get(String.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(response.getEntity().getBytes())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
RESTEasyClientPost.java
package com.example.client;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
public class RESTEasyClientPost {
public static void main(String[] args) {
try {
ClientRequest request = new ClientRequest(
"http://localhost:8080/WebservicePrjResrEasy/rest/json/product/post");
request.accept("application/json");
String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
request.body("application/json", input);
ClientResponse<String> response = request.post(String.class);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(response.getEntity().getBytes())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. Spring 3.2.2 RestWebservice –
pom.xml
<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>WebservicePrjSpring</groupId>
<artifactId>WebservicePrjSpring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>3.2.2.RELEASE</spring.version>
<jackson.version>1.9.10</jackson.version>
<jdk.version>1.7</jdk.version>
</properties>
<dependencies>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Jackson JSON Mapper -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>WebservicePrjSpring</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.example.common.controller" />
<mvc:annotation-driven />
</beans>
Shop.java
package com.example.common.model;
import java.util.Date;
public class Shop {
private Integer id;
private String name;
private String staffName[];
private Date createdTS;
//create getter & setter and override equals, hashcode & toString method
}
JSONController.java
package com.example.common.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.jackson.map.ObjectMapper;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.common.model.Shop;
#Controller
#RequestMapping("/kfc/brands")
public class JSONController {
Map<Integer, Shop> shopData = new HashMap<Integer, Shop>();
#RequestMapping(value="{name}", method = RequestMethod.GET)
public #ResponseBody Shop getShopInJSON(#PathVariable String name) {
Shop shop = new Shop();
shop.setId(100);
shop.setName(name);
shop.setStaffName(new String[]{"DON1", "DON2"});
shop.setCreatedTS(new Date());
shopData.put(shop.getId(), shop);
return shop;
}
#RequestMapping(value="/shop/get/onjson", method = RequestMethod.GET,headers="Accept=application/json")
public #ResponseBody Shop getUpdatedShopInJSON(#RequestParam(value="json",required=true) String json,
#RequestParam(value="name",required=false) String name) {
ObjectMapper objectMapper = new ObjectMapper();
Shop shop =null;
try {
shop = objectMapper.readValue(json, Shop.class);
if(name!=null && !name.equals("") && !name.equalsIgnoreCase("null")) {
shop.setName(name);
}
shop.setCreatedTS(new Date());
shopData.put(shop.getId(), shop);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return shop;
}
#RequestMapping(value ="/shop/create", method = RequestMethod.POST)
public// #ResponseBody Shop
ResponseEntity<?>
createShop(#RequestBody Shop shop) {
System.out.println("Start createShop.");
// shop.setId(101);
// shop.setName("DAN");
//shop.setStaffName(new String[]{"DON5", "DON5"});
shop.setCreatedTS(new Date());
shopData.put(shop.getId(), shop);
//return shop;
return new ResponseEntity<>(shop, HttpStatus.CREATED);
}
#RequestMapping(value = "/shop/all", method = RequestMethod.GET)
public #ResponseBody List<Shop> getAllShops() {
System.out.println("Start getAllShops.");
List<Shop> shops = new ArrayList<Shop>();
Set<Integer> shopIdKeys = shopData.keySet();
for(Integer i : shopIdKeys){
shops.add(shopData.get(i));
}
return shops;
}
}
NetClientGet.java
package com.example.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientGet {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/WebservicePrjSpring/rest/kfc/brands/kfc-kampar");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
NetClientPost.java
package com.example.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientPost {
// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/WebservicePrjSpring/rest/kfc/brands/shop/create");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"id\":105,\"name\":\"kfc-din\",\"staffName\":[\"DON9\",\"DON9\"]}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}