I am trying to re-implement Task Assignment Email using camunda-bpm-reactor. I am able to send email when I am using Java classes, but when I try to re-implement it by event bus it does not work.
I added the required dependency as
<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.camunda.bpm.quickstart</groupId>
<artifactId>camunda-quickstart-task-assignment-email</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Task Assignment Email</name>
<properties>
<camunda.version>7.10.0</camunda.version>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<dependency>
<groupId>org.camunda.bpm.extension</groupId>
<artifactId>camunda-bpm-reactor-core</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.camunda.bpm</groupId>
<artifactId>camunda-engine</artifactId>
<version>${camunda.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.171</version>
<scope>test</scope>
</dependency>
<!-- redirect slf4j logging to jdk logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>camunda-bpm-nexus</id>
<name>camunda-bpm-nexus</name>
<url>https://app.camunda.com/nexus/content/groups/public</url>
</repository>
</repositories>
</project>
to the pom.xml file of the project. I created three classes as follows:
TaskAssignmentApplication.java file:
package org.camunda.bpm.quickstart;
import org.camunda.bpm.application.ProcessApplication;
import org.camunda.bpm.application.impl.ServletProcessApplication;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.ProcessEngineConfiguration;
import org.camunda.bpm.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration;
import org.camunda.bpm.extension.reactor.CamundaReactor;
import org.camunda.bpm.extension.reactor.bus.CamundaEventBus;
#ProcessApplication("TaskAssignmentEmail")
public class TaskAssignmentApplication extends ServletProcessApplication {
private static ProcessEngineConfiguration CONFIGURATION = new StandaloneInMemProcessEngineConfiguration() {
{
// register the plugin
this.getProcessEnginePlugins().add(CamundaReactor.plugin());
this.databaseSchemaUpdate = DB_SCHEMA_UPDATE_DROP_CREATE;
this.jobExecutorActivate = false;
this.isDbMetricsReporterActivate = false;
}
};
private static ProcessEngine processEngine;
public static ProcessEngine processEngine() {
if (processEngine == null) {
processEngine = CONFIGURATION.buildProcessEngine();
}
return processEngine;
}
public static void init() {
CamundaEventBus eventBus = CamundaReactor.eventBus();
// create and register listeners
new TaskCreateListener(eventBus);
new TaskAssignmentListener();
}
}
TaskCreateListener.java file:
package org.camunda.bpm.quickstart;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.extension.reactor.bus.CamundaEventBus;
import org.camunda.bpm.extension.reactor.bus.CamundaSelector;
#CamundaSelector(type = "userTask", event = TaskListener.EVENTNAME_CREATE, process = "TaskAssignmentEmail")
public class TaskCreateListener implements TaskListener {
public TaskCreateListener(CamundaEventBus eventBus) {
eventBus.register(this);
}
#Override
public void notify(DelegateTask delegateTask) {
delegateTask.setPriority(97);
delegateTask.addCandidateGroup("IT");
}
}
and TaskAssignmentListener.java file:
package org.camunda.bpm.quickstart;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;
import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.engine.identity.User;
import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.extension.reactor.CamundaReactor;
import org.camunda.bpm.extension.reactor.bus.CamundaSelector;
#CamundaSelector(type = "userTask", event = TaskListener.EVENTNAME_ASSIGNMENT)
public class TaskAssignmentListener implements TaskListener {
private static final String HOST = "smtp.gmail.com";
private static final String USER = "camunda.bp#gmail.com";
private static final String PWD = "";
private final static Logger LOGGER = Logger.getLogger(TaskAssignmentListener.class.getName());
//private final Logger logger = LoggerFactory.getLogger(getClass());
public TaskAssignmentListener() {
CamundaReactor.eventBus().register(this);
}
#Override
public void notify(DelegateTask delegateTask) {
//CamundaReactor.eventBus().register(new TaskCreateListener(null));
String assignee = delegateTask.getAssignee();
String taskId = delegateTask.getId();
if (assignee != null) {
// Get User Profile from User Management
IdentityService identityService = Context.getProcessEngineConfiguration().getIdentityService();
User user = identityService.createUserQuery().userId(assignee).singleResult();
if (user != null) {
// Get Email Address from User Profile
String recipient = user.getEmail();
if (recipient != null && !recipient.isEmpty()) {
Email email = new SimpleEmail();
email.setSmtpPort(587);
email.setSSL(true);
email.setTLS(true);
email.setCharset("utf-8");
email.setHostName(HOST);
email.setAuthentication(USER, PWD);
try {
email.setFrom("noreply#camunda.org");
email.setSubject("Task assigned: " + delegateTask.getName());
email.setMsg("Please complete: http://localhost:8080/camunda/app/tasklist/default/#/task/" + taskId);
email.addTo(recipient);
email.send();
LOGGER.info("Task Assignment Email successfully sent to user '" + assignee + "' with address '" + recipient + "'.");
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Could not send email to assignee", e);
}
} else {
LOGGER.warning("Not sending email to user " + assignee + "', user has no email address.");
}
} else {
LOGGER.warning("Not sending email to user " + assignee + "', user is not enrolled with identity service.");
}
}
}
}
But it does not work. any ideas why?
Related
I wanted to add swagger implementation for below snippet. But couldn't find exact annotation to read url input from swagger.
Tried using,
#ApiOperation(httpMethod = "GET",value = "Get Value",response = String.class)
#ApiImplicitParams({#ApiImplicitParam(name="basePath",paramType = "path")
#GetMapping(value = "/**")
public String getUrlPath(HttpServletRequest request){
return request.getServletPath();
}
above code didn't help.
#GetMapping(value = "/**")
public String getUrlPath(HttpServletRequest request){
return request.getServletPath();
}
Expectation is to get a url as input via swagger-ui and return the same as response.
Let suppose that your controller look like :
package com.sample.controller;
#RestController
#RequestMapping
#Api(value = "GreetingsController", tags = {"Just for greetings"})
Public class GreetingsController{
#ApiOperation(httpMethod = "GET", value = "Get value",notes = "description")
#ApiResponses(value = {
#ApiResponse(code = 200, message = "OK !"),
#ApiResponse(code = 500, message = "Internal Error")
})
#GetMapping(value = "/")
public String getUrlPath(HttpServletRequest request){
return request.getServletPath();
}
}
The Dependency:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version> <!-- maybe there a new version -->
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version> <!-- maybe there a new version -->
</dependency>
Configurations:
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#Configurable
public class AppConfig{
public #Bean Docket restApi() {
return new Docket(DocumentationType.SWAGGER_2).groupName("GroupeName").apiInfo(apiInfo())
.select().paths(PathSelectors.regex(".*controller.*")).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("App title").description("App description")
.termsOfServiceUrl("").license("©Licence").licenseUrl("").version("1.0").build();
}
}
Application.yml:
server:
port: 8111
servlet:
context-path: /exampleApp
Access url : http://localhost:8111/exampleApp/swagger-ui.html
wrote a JAX-WS web service for my project.I use #autowired for inject a class...Then the web service returns null pointer exception... I went to the debug mode and verify the null pointer gives in the #autowired cord... Is the special annotation need for use #autowired in JAX-RS..
This is my Web Service class
package lk.slsi.webService;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.ws.rs.PathParam;
import lk.slsi.domain.CustomsPermit;
import lk.slsi.services.permitServices;
import org.springframework.beans.factory.annotation.Autowired;
#WebService(serviceName = "customsPermit",name = "permitRelease",portName = "nswPort",targetNamespace = "https://nationalsinglewindow.gov.lk/SLSIonNationalSingleWindow/")
#SOAPBinding(style = SOAPBinding.Style.DOCUMENT)
public class webServiceforCustoms {
#Autowired
private permitServices permitServices;
#WebMethod
public List<CustomsPermit> getXmlbyDate(#WebParam(name = "123") String dtIssue) {
List<CustomsPermit> permitRelease = permitServices.getPermitByDate(dtIssue);
return permitRelease;
}
#WebMethod
public CustomsPermit getXmlbyEntryNo(String SNumber) {
CustomsPermit permitRelease = permitServices.getPermitBySNumber(SNumber);
return permitRelease;
}
#WebMethod
public List<CustomsPermit> getXmlbyVATNo(String importerVAT) {
List<CustomsPermit> permitRelease = permitServices.getPermitByImporterVAT(importerVAT);
return permitRelease;
}
}
This is my service class
package lk.slsi.services;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import javax.validation.Valid;
import java.util.List;
import javax.inject.Inject;
import lk.slsi.domain.CustomsPermit;
import lk.slsi.repository.PermitRepository;
import lk.slsi.security.domain.AuthenticatedUser;
import org.springframework.security.core.context.SecurityContextHolder;
#Service
#Scope("session")
public class permitServices{
private static final Logger serviceLogger = LogManager.getLogger(permitServices.class);
#Autowired
private PermitRepository permitRepository;
public boolean registerPermit(#Valid CustomsPermit customsPermit) {
serviceLogger.info("Starting to register new Agent. agent : [{}]", customsPermit);
try {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
long userId = 0;
String agency = "";
String units = "";
List<String> roles;
if (principal != null && principal instanceof AuthenticatedUser) {
AuthenticatedUser auth = (AuthenticatedUser) principal;
userId = auth.getUserId();
agency = auth.getAgency();
roles = auth.getUserRoles();
String pattern = "yyyy-MM-dd HH:mm:ss";
String pattern2 = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat(pattern2);
String date = simpleDateFormat.format(new Date());
String date2 = simpleDateFormat2.format(new Date());
String userandTime = "UserID " + Long.toString(userId) + " in " + date;
customsPermit.setAppPostdate(userandTime);
customsPermit.setUserID(Long.toString(userId));
customsPermit.setDtIssue(date2);
permitRepository.save(customsPermit);
serviceLogger.info("Successfully saved the agent in db");
return true;
}
} catch (Exception e) {
serviceLogger.error("Error occurred while registering agent. [{}]", e);
}
return false;
}
public CustomsPermit getFromId(Long id) {
serviceLogger.info("Fetching the agent by nic number : [{}]", id);
try {
return permitRepository.getFromId(id);
} catch (Exception e) {
serviceLogger.error("Error while retrieving the permit for id number [{}], [{}]", id, e);
return null;
}
}
public List<CustomsPermit> findAll() {
serviceLogger.info("Fetching Permit List");
return permitRepository.findAll();
}
public List<CustomsPermit> getPermitByImporterVAT(String importerVAT) {
serviceLogger.info("Fetching Permit List");
return permitRepository.getPermitByImporterVAT(importerVAT);
}
public List<CustomsPermit> getPermitByDate(String dtIssue) {
serviceLogger.info("Fetching Permit List");
return permitRepository.getPermitByDate(dtIssue);
}
public CustomsPermit getPermitBySNumber(String SNumber) {
return permitRepository.getPermitBySNumber(SNumber);
}
}
This is my repository class
package lk.slsi.repository;
import lk.slsi.domain.Agent;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
import lk.slsi.domain.CustomsPermit;
public interface PermitRepository extends CrudRepository<CustomsPermit, Long> {
#Override
CustomsPermit save(CustomsPermit customsPermit);
#Override
CustomsPermit findOne(Long id);
#Override
List<CustomsPermit> findAll();
#Query("select a from CustomsPermit a where a.id = :id")
CustomsPermit getFromId(#Param("id") Long id);
#Query("select a from CustomsPermit a where a.SNumber = :SNumber")
CustomsPermit getPermitBySNumber(#Param("SNumber") String SNumber);
#Query("select a from CustomsPermit a where a.importerVAT = :importerVAT")
List<CustomsPermit> getPermitByImporterVAT(#Param("importerVAT") String importerVAT);
#Query("select a from CustomsPermit a where a.dtIssue = :dtIssue")
List<CustomsPermit> getPermitByDate(#Param("dtIssue") String dtIssue);
}
This is my 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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>lk.slsi</groupId>
<artifactId>SLSIonNationalSingleWindow</artifactId>
<packaging>war</packaging>
<version>slsi-1.1.0-SNAPSHOT</version>
<name>SLSIonNationalSingleWindow Maven Webapp</name>
<url>http://maven.apache.org</url>
<scm>
<connection>scm:git:git#bitbucket.org:mof_SriLanka/SLSIonNationalSingleWindow.git</connection>
<url>scm:git:git#bitbucket.org:mof_SriLanka/SLSIonNationalSingleWindow.git</url>
<developerConnection>scm:git:git#bitbucket.org:mof_SriLanka/SLSIonNationalSingleWindow.git</developerConnection>
<tag>1.0.0</tag>
</scm>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<sonar.exclusions>**/public/**/*</sonar.exclusions>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
<!--<scope>provided</scope>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<!--handle servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--<Email Dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>1.4.3.RELEASE</version>
</dependency>
<!--Add mysql dependency-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!--jasper-->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>3.7.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.5</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.bundles</groupId>
<artifactId>jaxrs-ri</artifactId>
<version>2.25</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
<type>jar</type>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-moxy -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.ext/jersey-spring3 -->
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring4</artifactId>
<version>2.26</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.ws/jaxws-ri-bom-ext -->
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-ri-bom-ext</artifactId>
<version>2.2.10</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.xml.ws/jaxws-api -->
<dependency>
<groupId>javax.xml.ws</groupId>
<artifactId>jaxws-api</artifactId>
<version>2.2.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.bundles.repackaged/jersey-guava -->
<dependency>
<groupId>org.glassfish.jersey.bundles.repackaged</groupId>
<artifactId>jersey-guava</artifactId>
<version>2.26-b03</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.activation/activation -->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.metro</groupId>
<artifactId>webservices-rt</artifactId>
<version>2.3</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.jsr-330/core -->
<dependency>
<groupId>com.github.jsr-330</groupId>
<artifactId>core</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>2.2.8</version>
</dependency>
<dependency>
<groupId>org.jvnet.jax-ws-commons.spring</groupId>
<artifactId>jaxws-spring</artifactId>
<version>1.9</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.xml.stream.buffer</groupId>
<artifactId>streambuffer</artifactId>
</exclusion>
<exclusion>
<groupId>org.jvnet.staxex</groupId>
<artifactId>stax-ex</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<finalName>SLSIonNationalSingleWindow</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.2</version>
<configuration>
<tagNameFormat>#{project.version}</tagNameFormat>
<autoVersionSubmodules>true</autoVersionSubmodules>
</configuration>
</plugin>
</plugins>
</build>
</project>
This is my configuration class
package lk.slsi;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import javax.annotation.PreDestroy;
/**
* Created by ignotus on 1/22/2017.
*/
#SpringBootApplication
#ComponentScan(basePackages = "lk.slsi")
#EnableWebMvc
#ImportResource(locations = "classpath:slsi-servlet-config.xml")
public class SLSIStarter extends SpringBootServletInitializer {
private static final Logger slsiLogger = LogManager.getLogger(SLSIStarter.class);
private static ConfigurableApplicationContext context;
public static void main(String[] args) {
slsiLogger.info("Starting application");
SpringApplication application = new SpringApplication(SLSIStarter.class);
context = application.run(args);
application.setRegisterShutdownHook(true);
}
#PreDestroy
private static void closeAppContext(){
context.close();
}
#Override
protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
return application.sources(SLSIStarter.class);
}
}
What is the error in my cord.
Create another class like this
#Service
public class PermitRepositoryImpl implements PermitRepository {
#Override
CustomsPermit save(CustomsPermit customsPermit){
//implement the code, returning null for now
return null;
}
#Override
CustomsPermit findOne(Long id){
//implement the code, returning null for now
return null;
}
#Override
List<CustomsPermit> findAll(){
//implement the code, returning null for now
return null;
}
#Query("select a from CustomsPermit a where a.id = :id")
CustomsPermit getFromId(#Param("id") Long id){
//implement the code, returning null for now
return null;
}
#Query("select a from CustomsPermit a where a.SNumber = :SNumber")
CustomsPermit getPermitBySNumber(#Param("SNumber") String SNumber){
//implement the code, returning null for now
return null;
}
#Query("select a from CustomsPermit a where a.importerVAT = :importerVAT")
List<CustomsPermit> getPermitByImporterVAT(#Param("importerVAT") String importerVAT){
//implement the code, returning null for now
return null;
}
#Query("select a from CustomsPermit a where a.dtIssue = :dtIssue")
List<CustomsPermit> getPermitByDate(#Param("dtIssue") String dtIssue){
//implement the code, returning null for now
return null;
}
}
Adding this class should solve your issue.
I cannot found any example for jax-rs testing with arquillian. I use a wildfly 10 managed container.
I am trying to do it by my own, this is my sample code:
#RunWith(Arquillian.class)
public class DeploymentTest {
#Deployment(testable = false)
public static Archive<?> deploy() {
return ShrinkWrap.create(WebArchive.class, "cos-arq-test.war")
.addClasses(MANUEJB.class, HelloWorld.class, HelloWorldRESTImpl.class)
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
#ArquillianResource
private URL base;
private static WebTarget target;
#Before
public void setUpClass() throws MalformedURLException {
Client client = ClientBuilder.newClient();
target = client.target(URI.create(new URL(base, "rest/helloWorldREST").toExternalForm()));
}
#Test
#RunAsClient
public void testResponse(#ArquillianResource URL base) throws InterruptedException, ExecutionException {
System.out.println("====================================================");
System.out.println("This test should run inside the Wildfly 10 container");
System.out.println("====================================================");
try {
System.out.println("URL TARGET: " + target.getUri().toURL().toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
assertEquals("Hello", target.request().get().readEntity(String.class));
/*
Future<Response> r1 = target.request().async().get();
Response response = r1.get();
if (null != response) {
assertEquals(HttpStatus.OK, response.getStatus());
assertNotNull(response.getEntity());
assertEquals("Hello " + "manuel" + "!", response.readEntity(String.class));
}
*/
}
}
And this is my service code:
#Path("/helloWorldREST")
public class HelloWorldRESTImpl implements HelloWorld {
#GET
public Response sayHi() {
return Response.ok("Hello").build();
}
#Override
#GET
#Path("/sayHi/{name}")
#Produces(MediaType.APPLICATION_JSON)
public Response sayHi(#PathParam("name") String name) {
MANUEJB ejb = null;
javax.naming.Context initialContext = null;
try {
initialContext = new InitialContext();
} catch (NamingException e) {
e.printStackTrace();
}
try {
ejb = (MANUEJB) initialContext.lookup("java:app/cos-arq-test/MANUEJB");
} catch (NamingException e) {
e.printStackTrace();
}
String result = ejb.method(name);
return Response.ok(result).build();
}
}
But I get an error, and it does not find the service.
I use arquillian libraries with a managed wildfly 10 container:
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>1.1.11.Final</version>
<scope>import</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.arquillian</groupId>
<artifactId>wildfly-arquillian-container-managed</artifactId>
<version>2.0.0.Final</version>
</dependency>
And this is my arquillian config for the container:
<arquillian xmlns="http://jboss.org/schema/arquillian"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<container qualifier="wildfly10" default="true">
<configuration>
<property name="jbossHome">/home/manumg/test-containers/wildfly-10.1.0.Final</property>
</configuration>
</container>
For a starter example, you can see https://github.com/arquillian/arquillian-extension-rest/blob/master/rest-client/README.md.
The code described in the readme is in the same repository at https://github.com/arquillian/arquillian-extension-rest/tree/master/rest-client/test-app.
For a starter maven project, I suggest you using the maven archetype wildfly-jakartaee-webapp-archetype, related to Wildfly 21 (jakarta ee 8 container).
To run the test you have to:
Activate the profile arq-managed
Download Wildfly 21 (from https://www.wildfly.org/downloads/)
Define the JBOSS_HOME variable (pointing to the local Wildfly directory)
I'm working on Neo4j Spring Data project and have started using a "RelationshipEntity" and the "#RelatedToVia" relationship to better model some relationships.
The problem I'm having is if I run an embedded database everything is fine but when I run with a SpringCypherRestGraphDatabase I keep getting the error "Error adding element... to index __rel_types__":
Any pointers would be great!!
Stacktrace:
Caused by: java.lang.RuntimeException: Error adding element 52 className AlsoKnownAs to index __rel_types__
at org.neo4j.rest.graphdb.RestAPIImpl.addToIndex(RestAPIImpl.java:703)
at org.neo4j.rest.graphdb.RestAPICypherImpl.addToIndex(RestAPICypherImpl.java:683)
at org.neo4j.rest.graphdb.index.RestIndex.add(RestIndex.java:58)
at org.springframework.data.neo4j.support.typerepresentation.AbstractIndexBasedTypeRepresentationStrategy.add(AbstractIndexBasedTypeRepresentationStrategy.java:139)
at org.springframework.data.neo4j.support.typerepresentation.AbstractIndexBasedTypeRepresentationStrategy.addToTypesIndex(AbstractIndexBasedTypeRepresentationStrategy.java:131)
at org.springframework.data.neo4j.support.typerepresentation.AbstractIndexBasedTypeRepresentationStrategy.writeTypeTo(AbstractIndexBasedTypeRepresentationStrategy.java:74)
at org.springframework.data.neo4j.support.mapping.TRSTypeAliasAccessor.writeTypeTo(TRSTypeAliasAccessor.java:46)
at org.springframework.data.neo4j.support.mapping.TRSTypeAliasAccessor.writeTypeTo(TRSTypeAliasAccessor.java:26)
at org.springframework.data.convert.DefaultTypeMapper.writeType(DefaultTypeMapper.java:199)
at org.springframework.data.convert.DefaultTypeMapper.writeType(DefaultTypeMapper.java:186)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.write(Neo4jEntityConverterImpl.java:168)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister$CachedConverter.write(Neo4jEntityPersister.java:179)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:254)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:235)
at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:365)
at org.springframework.data.neo4j.fieldaccess.RelatedToViaCollectionFieldAccessorFactory$RelatedToViaCollectionFieldAccessor.persistEntities(RelatedToViaCollectionFieldAccessorFactory.java:99)
at org.springframework.data.neo4j.fieldaccess.RelatedToViaCollectionFieldAccessorFactory$RelatedToViaCollectionFieldAccessor.setValue(RelatedToViaCollectionFieldAccessorFactory.java:93)
at org.springframework.data.neo4j.fieldaccess.ManagedFieldAccessorSet.updateValue(ManagedFieldAccessorSet.java:112)
at org.springframework.data.neo4j.fieldaccess.ManagedFieldAccessorSet.update(ManagedFieldAccessorSet.java:100)
at org.springframework.data.neo4j.fieldaccess.ManagedFieldAccessorSet.add(ManagedFieldAccessorSet.java:126)
RelationshipEntity
import org.springframework.data.neo4j.annotation.EndNode;
import org.springframework.data.neo4j.annotation.Fetch;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.RelationshipEntity;
import org.springframework.data.neo4j.annotation.StartNode;
#RelationshipEntity(type = "AKA")
public class AlsoKnownAs {
#GraphId Long id;
String name;
#Fetch #StartNode private Person identity;
#Fetch #EndNode private Person pseudenom;
public AlsoKnownAs setNickname(String nickName){
this.name = nickName;
return this;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person getIdentity() {
return identity;
}
public void setIdentity(Person identity) {
this.identity = identity;
}
public Person getPseudenom() {
return pseudenom;
}
public void setPseudenom(Person pseudenom) {
this.pseudenom = pseudenom;
}
}
Node Entity
import java.util.HashSet;
import java.util.Set;
import org.neo4j.graphdb.Direction;
import org.springframework.data.neo4j.annotation.Fetch;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedTo;
import org.springframework.data.neo4j.annotation.RelatedToVia;
#NodeEntity
public class Person {
#GraphId Long id;
public String name;
public Person() {}
public Person(String name) { this.name = name; }
#RelatedTo(type="TEAMMATE", direction=Direction.BOTH)
public #Fetch Set<Person> teammates;
#RelatedToVia(type="AKA")
Set<AlsoKnownAs> identities;
public void worksWith(Person person) {
if (teammates == null) {
teammates = new HashSet<Person>();
}
teammates.add(person);
}
public String toString() {
String results = name + "'s teammates include\n";
if (teammates != null) {
for (Person person : teammates) {
results += "\t- " + person.name + "\n";
}
}
return results;
}
public void identify(Person person, String nickName) {
AlsoKnownAs aka = new AlsoKnownAs();
aka.setIdentity(this);
aka.setPseudenom(person);
aka.setName(nickName);
this.identities.add(aka);
}
}
POM:
<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.teralitic</groupId>
<artifactId>geonames</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
</parent>
<properties>
<spring-data-releasetrain.version>Fowler-RELEASE</spring-data-releasetrain.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
<version>3.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-rest</artifactId>
<version>3.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<jvmArguments>
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005
</jvmArguments>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>neo4j</id>
<name>Neo4j</name>
<url>http://m2.neo4j.org/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
Edited
I can see the same issue was happening on an old Spring Data build:
https://build.spring.io/browse/SPRINGDATA-NIGHTLY-JOB1-697/test/case/92176623;jsessionid=5EE45702C67548804FEF985C00F5DAD2
Still investigating what might have caused that.
Still can't figure a way to fix this issue cleanly.
My only workaround so far was to replace
org.springframework.data.neo4j.rest.SpringCypherRestGraphDatabase
by the now deprecated
org.springframework.data.neo4j.rest.SpringRestGraphDatabase
I am now able to save #RelatedToVia relationships.
I'm having the exact same problem here.
I use spring-data-neo4j 3.3.0.RELEASE and spring-data-neo4j-rest 3.3.0.RELEASE, i had also to add manually spring-data-commons 1.10 (https://jira.spring.io/browse/DATAGRAPH-635)
Using the deprecated class solved the issue, but i'm not sure on my configuration since Michael Hunger said (here http://java.dzone.com/articles/spring-data-neo4j-330) to use the SpringCypherRestGraphDatabase....
I've published JAX-WS web services with Endpoint.publish during development. Is there any such utility class exists (in JAX-RS) for publishing REST web services in jersey? I referred couple of articles, and majority of them are based on publishing the web services in some containers like Jetty, Grizzly etc.
Jersey-Grizzly has a very simple solution. From https://github.com/jesperfj/jax-rs-heroku:
package embedded.rest.server;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory;
#Path("/hello")
public class Main {
public static void main(String[] args) {
final String baseUri = "http://localhost:7080/";
final Map<String, String> initParams = new HashMap<String, String>();
// Register the package that contains your javax.ws.rs-annotated beans here
initParams.put("com.sun.jersey.config.property.packages","embedded.rest.server");
System.out.println("Starting grizzly...");
try {
SelectorThread threadSelector =
GrizzlyWebContainerFactory.create(baseUri, initParams);
System.out.println(String.format("Jersey started with WADL "
+ "available at %sapplication.wadl.", baseUri));
}
catch(Exception e) {
e.printStackTrace();
}
}
#GET
#Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Well, this was easy!";
}
}
If you're using Maven, you'll need the following three dependencies:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-grizzly</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>com.sun.grizzly</groupId>
<artifactId>grizzly-servlet-webserver</artifactId>
<version>1.9.18-i</version>
</dependency>
To test it, just open http://localhost:7080/hello in a browser.
I think you can use Provider interface to publishing a RESTful Web Service with JAX-WS.
The example class:
#WebServiceProvider
#BindingType(value=HTTPBinding.HTTP_BINDING)
public class AddNumbersImpl implements Provider {
#Resource
protected WebServiceContext wsContext;
public Source invoke(Source source) {
try {
MessageContext mc = wsContext.getMessageContext();
// check for a PATH_INFO request
String path = (String)mc.get(MessageContext.PATH_INFO);
if (path != null && path.contains("/num1") &&
path.contains("/num2")) {
return createResultSource(path);
}
String query = (String)mc.get(MessageContext.QUERY_STRING);
System.out.println("Query String = "+query);
ServletRequest req = (ServletRequest)mc.get(MessageContext.SERVLET_REQUEST);
int num1 = Integer.parseInt(req.getParameter("num1"));
int num2 = Integer.parseInt(req.getParameter("num2"));
return createResultSource(num1+num2);
} catch(Exception e) {
e.printStackTrace();
throw new HTTPException(500);
}
}
private Source createResultSource(String str) {
StringTokenizer st = new StringTokenizer(str, "=&/");
String token = st.nextToken();
int number1 = Integer.parseInt(st.nextToken());
st.nextToken();
int number2 = Integer.parseInt(st.nextToken());
int sum = number1+number2;
return createResultSource(sum);
}
private Source createResultSource(int sum) {
String body =
"<ns:addNumbersResponse xmlns:ns="http://java.duke.org"><ns:return>"
+sum
+"</ns:return></ns:addNumbersResponse>";
Source source = new StreamSource(
new ByteArrayInputStream(body.getBytes()));
return source;
}
}
To deploy our endpoint on a servlet container running with the JAX-WS
RI we need to create a WAR file.
The adjusted web.xml:
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee">
<listener>
<listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener
</listener>
<servlet>
<servlet-name>restful-addnumbers</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>restful-addnumbers</servlet-name>
<url-pattern>/addnumbers/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
</web-app>
and need to add sun-jaxws.xml deployment descriptor to the WAR file.
<endpoints
xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
version="2.0">
<endpoint
name="restful-addnumbers"
implementation="restful.server.AddNumbersImpl"
wsdl="WEB-INF/wsdl/AddNumbers.wsdl"
url-pattern="/addnumbers/*" />
</endpoints>
Or could be create simple HttpServer
import java.io.IOException;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.net.httpserver.HttpServer;
public class YourREST {
static final String BASE_URI = "http://localhost:9999/yourrest/";
public static void main(String[] args) {
try {
HttpServer server = HttpServerFactory.create(BASE_URI);
server.start();
System.out.println("Press Enter to stop the server. ");
System.in.read();
server.stop(0);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}