List all exposed/available endpoints of RestEasy service? - jboss

Is it possible to list all exposed/available endpoints of RestEasy service in a simple way?

There is a RestEasy plugin, "stats", which exposes .../resteasy/registry.
It needs to be registered in web.xml:
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>org.jboss.resteasy.plugins.stats.RegistryStatsResource</param-value>
</context-param>
Example response:
<registry>
<resource uriTemplate="/resource">
<delete class="org.jboss.resteasy.test.providers.jaxb.resource.StatsResource" method="delete"
invocations="0"/>
<head class="org.jboss.resteasy.test.providers.jaxb.resource.StatsResource" method="head" invocations="0"/>
</resource>
<resource uriTemplate="/locator">
<locator class="org.jboss.resteasy.test.providers.jaxb.resource.StatsResource" method="getLocator"/>
</resource>
<resource uriTemplate="/resteasy/registry">
<get class="org.jboss.resteasy.plugins.stats.RegistryStatsResource" method="get" invocations="2">
<produces>application/xml</produces>
<produces>application/json</produces>
</get>
</resource>
<resource uriTemplate="/entry/{foo:.*}">
<post class="org.jboss.resteasy.test.providers.jaxb.resource.StatsResource" method="post" invocations="0">
<produces>text/xml</produces>
<consumes>application/json</consumes>
</post>
<put class="org.jboss.resteasy.test.providers.jaxb.resource.StatsResource" method="put" invocations="0">
<produces>text/xml</produces>
<consumes>application/json</consumes>
</put>
</resource>
</registry>
Maven dependency:
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>3.0.8.Final</version>
</dependency>
See eg. EAP docs and this EAP 7 Jira

I had to adjust the "cleaner" example which was excellent to begin with. I'm using RestEasy 3.07 and wanted to also have each method's Path annotation value. I hope this modification can be of help to others.
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.core.ResourceInvoker;
import org.jboss.resteasy.core.ResourceMethodInvoker;
import org.jboss.resteasy.core.ResourceMethodRegistry;
import org.springframework.stereotype.Component;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
#Component
#Path("/overview")
public class OverviewResource
{
private static final class MethodDescription
{
private String method;
private String fullPath;
private String produces;
private String consumes;
public MethodDescription(String method, String fullPath, String produces, String consumes)
{
super();
this.method = method;
this.fullPath = fullPath;
this.produces = produces;
this.consumes = consumes;
}
}
private static final class ResourceDescription
{
private String basePath;
private List<MethodDescription> calls;
public ResourceDescription(String basePath)
{
this.basePath = basePath;
this.calls = Lists.newArrayList();
}
public void addMethod(String path, ResourceMethodInvoker method)
{
String produces = mostPreferredOrNull(method.getProduces());
String consumes = mostPreferredOrNull(method.getConsumes());
for (String verb : method.getHttpMethods())
{
calls.add(new MethodDescription(verb, path, produces, consumes));
}
}
private static String mostPreferredOrNull(MediaType[] mediaTypes)
{
if (mediaTypes == null || mediaTypes.length < 1)
{
return null;
}
else
{
return mediaTypes[0].toString();
}
}
public static List<ResourceDescription> fromBoundResourceInvokers(
Set<Map.Entry<String, List<ResourceInvoker>>> bound)
{
Map<String, ResourceDescription> descriptions = Maps.newHashMap();
for (Map.Entry<String, List<ResourceInvoker>> entry : bound)
{
Method aMethod = ((ResourceMethodInvoker) entry.getValue().get(0)).getMethod();
String basePath = aMethod.getDeclaringClass().getAnnotation(Path.class).value();
if (!descriptions.containsKey(basePath))
{
descriptions.put(basePath, new ResourceDescription(basePath));
}
for (ResourceInvoker invoker : entry.getValue())
{
ResourceMethodInvoker method = (ResourceMethodInvoker) invoker;
String subPath = null;
for(Annotation annotation : method.getMethodAnnotations())
{
if(annotation.annotationType().equals(Path.class))
{
subPath = ((Path) annotation).value();
break;
}
}
descriptions.get(basePath).addMethod(basePath + subPath, method);
}
}
return Lists.newLinkedList(descriptions.values());
}
}
#GET
#Path("/")
#Produces(MediaType.APPLICATION_JSON)
public List<ResourceDescription> getAvailableEndpoints(#Context Dispatcher dispatcher)
{
ResourceMethodRegistry registry = (ResourceMethodRegistry) dispatcher.getRegistry();
return ResourceDescription.fromBoundResourceInvokers(registry.getBounded().entrySet());
}
#GET
#Path("/")
#Produces(MediaType.TEXT_HTML)
public Response getAvailableEndpointsHtml(#Context Dispatcher dispatcher)
{
StringBuilder sb = new StringBuilder();
ResourceMethodRegistry registry = (ResourceMethodRegistry) dispatcher.getRegistry();
List<ResourceDescription> descriptions = ResourceDescription.fromBoundResourceInvokers(registry.getBounded()
.entrySet());
sb.append("<h1>").append("REST interface overview").append("</h1>");
for (ResourceDescription resource : descriptions)
{
sb.append("<h2>").append(resource.basePath).append("</h2>");
sb.append("<ul>");
for (MethodDescription method : resource.calls)
{
sb.append("<li> ").append(method.method).append(" ");
sb.append("<strong>").append(method.fullPath).append("</strong>");
sb.append("<ul>");
if (method.consumes != null)
{
sb.append("<li>").append("Consumes: ").append(method.consumes).append("</li>");
}
if (method.produces != null)
{
sb.append("<li>").append("Produces: ").append(method.produces).append("</li>");
}
sb.append("</ul>");
}
sb.append("</ul>");
}
return Response.ok(sb.toString()).build();
}
}
(On another note, perhaps there is something available, or I can begin work on, to model the resource listing and description that ServiceStack does so nicely: http://mono.servicestack.net/Content/Images/MetadataIndex.png)

EDIT:
See this gist for a "cleaner" example:
https://gist.github.com/wonderb0lt/10731371
Yes, it's possible. Perhaps you would like to know how? :)
Here's a "quick-n-dirty" example:
import org.jboss.resteasy.annotations.providers.jaxb.Formatted;
import org.jboss.resteasy.annotations.providers.jaxb.Wrapped;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.core.ResourceInvoker;
import org.jboss.resteasy.core.ResourceMethod;
import org.jboss.resteasy.core.ResourceMethodRegistry;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.junit.Test;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class PrintAllResourcesTest {
#Test
public void name_StateUnderTest_ExpectedBehavior() throws Exception {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(new MetaService());
dispatcher.getRegistry().addSingletonResource(new Service());
MockHttpResponse response = new MockHttpResponse();
MockHttpRequest request = MockHttpRequest.get("/meta")
.accept(MediaType.APPLICATION_XML);
dispatcher.invoke(request, response);
/*<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<resources>
<resource method="GET">/service/</resource>
<resource method="POST">/service/</resource>
</resources>*/
String result = response.getContentAsString();
}
#XmlRootElement(name = "resource")
public static final class JaxRsResource {
#XmlAttribute String method;
#XmlValue String uri;
public JaxRsResource() {}
public JaxRsResource(String method, String uri) {
this.method = method;
this.uri = uri;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JaxRsResource that = (JaxRsResource) o;
if (method != null ? !method.equals(that.method) : that.method != null) return false;
if (uri != null ? !uri.equals(that.uri) : that.uri != null) return false;
return true;
}
#Override
public int hashCode() {
int result = method != null ? method.hashCode() : 0;
result = 31 * result + (uri != null ? uri.hashCode() : 0);
return result;
}
}
#Path("/service")
public static final class Service {
#GET
#Path("/")
public String getStuff(){
return "";
}
#POST
#Path("/")
public String postStuff(){
return "";
}
}
#Path("/meta")
public static final class MetaService {
#Context Dispatcher dispatcher;
#GET
#Path("/")
#Wrapped(element = "resources")
#Formatted
public Set<JaxRsResource> getAllResources(){
Set<JaxRsResource> resources = new HashSet<JaxRsResource>();
ResourceMethodRegistry registry = (ResourceMethodRegistry) dispatcher.getRegistry();
for (Map.Entry<String, List<ResourceInvoker>> entry : registry.getRoot().getBounded().entrySet()) {
for (ResourceInvoker invoker : entry.getValue()) {
ResourceMethod method = (ResourceMethod) invoker;
if(method.getMethod().getDeclaringClass() == getClass()){
continue;
}
for (String verb : method.getHttpMethods()) {
String uri = entry.getKey();
resources.add(new JaxRsResource(verb, uri));
}
}
}
return resources;
}
}
}

Even it is an old post, I give my answer here.
Here is the implementation from RestEasy shipped with JBoss. You can use it, or you can write your own.
The implementation returns an object with an array property where you can find a uriTemplate String for each RestEasy Resource.
You need to iterate over all entries and get the info you need:
RegistryData.entries.get(index).uriTemplate
The implementation of org.jboss.resteasy.plugins.stats.RegistryStatsResource.get method:
public RegistryData get() throws JAXBException {
ResourceMethodRegistry registry = (ResourceMethodRegistry)ResteasyProviderFactory.getContextData(Registry.class);
RegistryData data = new RegistryData();
Iterator i$ = registry.getRoot().getBounded().keySet().iterator();
label85:
while(i$.hasNext()) {
String key = (String)i$.next();
List<ResourceInvoker> invokers = (List)registry.getRoot().getBounded().get(key);
RegistryEntry entry = new RegistryEntry();
data.getEntries().add(entry);
entry.setUriTemplate(key);
Iterator i$ = invokers.iterator();
while(true) {
while(true) {
if (!i$.hasNext()) {
continue label85;
}
ResourceInvoker invoker = (ResourceInvoker)i$.next();
if (invoker instanceof ResourceMethod) {
ResourceMethod rm = (ResourceMethod)invoker;
Object method;
for(Iterator i$ = rm.getHttpMethods().iterator(); i$.hasNext(); entry.getMethods().add(method)) {
String httpMethod = (String)i$.next();
method = null;
if (httpMethod.equals("GET")) {
method = new GetResourceMethod();
} else if (httpMethod.equals("PUT")) {
method = new PutResourceMethod();
} else if (httpMethod.equals("DELETE")) {
method = new DeleteResourceMethod();
} else if (httpMethod.equals("POST")) {
method = new PostResourceMethod();
} else if (httpMethod.equals("OPTIONS")) {
method = new OptionsResourceMethod();
} else if (httpMethod.equals("TRACE")) {
method = new TraceResourceMethod();
} else if (httpMethod.equals("HEAD")) {
method = new HeadResourceMethod();
}
((ResourceMethodEntry)method).setClazz(rm.getResourceClass().getName());
((ResourceMethodEntry)method).setMethod(rm.getMethod().getName());
AtomicLong stat = (AtomicLong)rm.getStats().get(httpMethod);
if (stat != null) {
((ResourceMethodEntry)method).setInvocations(stat.longValue());
} else {
((ResourceMethodEntry)method).setInvocations(0L);
}
MediaType[] arr$;
int len$;
int i$;
MediaType mediaType;
if (rm.getProduces() != null) {
arr$ = rm.getProduces();
len$ = arr$.length;
for(i$ = 0; i$ < len$; ++i$) {
mediaType = arr$[i$];
((ResourceMethodEntry)method).getProduces().add(mediaType.toString());
}
}
if (rm.getConsumes() != null) {
arr$ = rm.getConsumes();
len$ = arr$.length;
for(i$ = 0; i$ < len$; ++i$) {
mediaType = arr$[i$];
((ResourceMethodEntry)method).getConsumes().add(mediaType.toString());
}
}
}
} else {
ResourceLocator rl = (ResourceLocator)invoker;
SubresourceLocator locator = new SubresourceLocator();
locator.setClazz(rl.getMethod().getDeclaringClass().getName());
locator.setMethod(rl.getMethod().getName());
entry.setLocator(locator);
}
}
}
}
return data;
}
See also: WildFly management - list/detect REST endpoints deployed in WildFly

In Resteasy 6.2 the above by Ondra Žižka mentioned solution caused a ClassCastException:
[2022-10-13 02:45:58,640] Artifact RegistryStatsResource:war: java.lang.Exception: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"xyz.war\".undertow-deployment" => "java.lang.RuntimeException: java.lang.ClassNotFoundException: org.jboss.resteasy.plugins.stats.RegistryStatsResource from [Module \"deployment.xyz.war\" from Service Module Loader]
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: org.jboss.resteasy.plugins.stats.RegistryStatsResource from [Module \"deployment.xyz.war\" from Service Module Loader]
Caused by: java.lang.ClassNotFoundException: org.jboss.resteasy.plugins.stats.RegistryStatsResource from [Module \"deployment.xyz.war\" from Service Module Loader]"}}
I was able to resolve the issue by adding the resteasy-stats dependency:
<!-- pom.xml -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-stats</artifactId>
<version>6.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>6.2.0.Final</version>
</dependency>
For completeness, the web.xml
<web-app>
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>org.jboss.resteasy.plugins.stats.RegistryStatsResource</param-value>
</context-param>
</web-app>
The services can be accessed via:
curl http://<AS-ip>:<AS-port>/<web context>/<rest activator>/resteasy/registry

In case anyone is still looking
hit "/resteasy/registry" on your app and it
provides XML output of all registered endpoints, associated classes/methods etc
FYI resteasy-jaxb-provider provides this functionality

Related

Joss eap 6.4 upgrade to 7.2 :javax.persistence.spi.PersistenceProvider: Provider org.eclipse.persistence.jpa.PersistenceProvider not a subtype

Jboss eap 6.4 upgrade to 7.2 deploy ear error
{"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"WLS_DOM_SPS.ear\".FIRST_MODULE_USE" => "WFLYSRV0153: Failed to process phase FIRST_MODULE_USE of deployment \"WLS_DOM_SPS.ear\"
Caused by: java.util.ServiceConfigurationError: javax.persistence.spi.PersistenceProvider: Provider org.eclipse.persistence.jpa.PersistenceProvider not a subtype"}}
eclipse link module config :
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.eclipse.persistence">
<resources>
<resource-root path="javax.persistence_1.1.0.0_2-0.jar"/>
<resource-root path="eclipselink-2.1.2_TMSModified1.jar">
<filter>
<exclude path="javax/**" />
</filter>
</resource-root>
</resources>
<dependencies>
<module name="asm.asm"/>
<module name="javax.api"/>
<module name="javax.annotation.api"/>
<module name="javax.enterprise.api"/>
<module name="javax.persistence.api"/>
<module name="javax.transaction.api"/>
<module name="javax.validation.api"/>
<module name="javax.xml.bind.api"/>
<module name="org.antlr"/>
<module name="org.apache.commons.collections"/>
<module name="org.dom4j"/>
<module name="org.javassist"/>
<module name="org.jboss.as.jpa.spi"/>
<module name="org.jboss.logging"/>
<module name="org.jboss.vfs"/>
</dependencies>
</module>
jboss eap 6.4 can deploy success. Don't know where the problem is.
javax.persistence.jar-javax.persistence.spi.PersistenceProvider
package javax.persistence.spi;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
public interface PersistenceProvider {
EntityManagerFactory createEntityManagerFactory(String var1, Map var2);
EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo var1, Map var2);
ProviderUtil getProviderUtil();
}
eclipselink-org.eclipse.persistence.jpa.PersistenceProvider
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.eclipse.persistence.jpa;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.LoadState;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.ProviderUtil;
import org.eclipse.persistence.exceptions.PersistenceUnitLoadingException;
import org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl;
import org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider;
import org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl;
import org.eclipse.persistence.internal.jpa.deployment.JPAInitializer;
import org.eclipse.persistence.internal.jpa.deployment.PersistenceInitializationHelper;
import org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor;
import org.eclipse.persistence.internal.jpa.deployment.SEPersistenceUnitInfo;
import org.eclipse.persistence.internal.weaving.PersistenceWeaved;
public class PersistenceProvider implements javax.persistence.spi.PersistenceProvider, ProviderUtil {
protected PersistenceInitializationHelper initializationHelper = null;
public PersistenceProvider() {
this.initializationHelper = new PersistenceInitializationHelper();
}
public EntityManagerFactory createEntityManagerFactory(String emName, Map properties) {
ClassLoader classloader = this.initializationHelper.getClassLoader(emName, properties);
return this.createEntityManagerFactory(emName, properties, classloader);
}
protected EntityManagerFactory createEntityManagerFactory(String emName, Map properties, ClassLoader classLoader) {
Map nonNullProperties = properties == null ? new HashMap() : properties;
String name = emName;
if (emName == null) {
name = "";
}
JPAInitializer initializer = this.initializationHelper.getInitializer(classLoader, (Map)nonNullProperties);
EntityManagerSetupImpl emSetupImpl = null;
boolean isNew = false;
String uniqueName;
String sessionName;
SEPersistenceUnitInfo factory;
try {
factory = initializer.findPersistenceUnitInfo(name, (Map)nonNullProperties, this.initializationHelper);
if (factory == null) {
return null;
}
if (initializer.isPersistenceUnitUniquelyDefinedByName()) {
uniqueName = name;
} else {
uniqueName = initializer.createUniquePersistenceUnitName(factory);
}
sessionName = EntityManagerSetupImpl.getOrBuildSessionName((Map)nonNullProperties, factory, uniqueName);
synchronized(EntityManagerFactoryProvider.emSetupImpls) {
emSetupImpl = EntityManagerFactoryProvider.getEntityManagerSetupImpl(sessionName);
if (emSetupImpl == null) {
if (EntityManagerFactoryProvider.initialEmSetupImpls != null) {
emSetupImpl = (EntityManagerSetupImpl)EntityManagerFactoryProvider.initialEmSetupImpls.remove(uniqueName);
if (emSetupImpl != null) {
emSetupImpl.changeSessionName(sessionName);
factory.setClassLoader(classLoader);
}
}
if (emSetupImpl == null) {
emSetupImpl = initializer.callPredeploy(factory, (Map)nonNullProperties, this.initializationHelper, uniqueName, sessionName);
}
emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), (Map)nonNullProperties);
EntityManagerFactoryProvider.addEntityManagerSetupImpl(sessionName, emSetupImpl);
isNew = true;
}
}
} catch (Exception var18) {
throw PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(classLoader, var18);
}
if (!isNew) {
if (!uniqueName.equals(emSetupImpl.getPersistenceUnitUniqueName())) {
throw PersistenceUnitLoadingException.sessionNameAlreadyInUse(sessionName, uniqueName, emSetupImpl.getPersistenceUnitUniqueName());
}
boolean undeployed = false;
synchronized(emSetupImpl) {
if (emSetupImpl.isUndeployed()) {
undeployed = true;
}
emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), (Map)nonNullProperties);
}
if (undeployed) {
return this.createEntityManagerFactory(emName, properties, classLoader);
}
}
factory = null;
try {
EntityManagerFactoryImpl factory = new EntityManagerFactoryImpl(emSetupImpl, (Map)nonNullProperties);
if (emSetupImpl.shouldGetSessionOnCreateFactory((Map)nonNullProperties)) {
factory.getServerSession();
}
return factory;
} catch (RuntimeException var15) {
if (factory != null) {
factory.close();
} else {
emSetupImpl.undeploy();
}
throw var15;
}
}
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
Map nonNullProperties = properties == null ? new HashMap() : properties;
EntityManagerSetupImpl emSetupImpl = null;
boolean isNew = false;
ClassTransformer transformer = null;
String uniqueName = PersistenceUnitProcessor.buildPersistenceUnitName(info.getPersistenceUnitRootUrl(), info.getPersistenceUnitName());
String sessionName = EntityManagerSetupImpl.getOrBuildSessionName((Map)nonNullProperties, info, uniqueName);
synchronized(EntityManagerFactoryProvider.emSetupImpls) {
emSetupImpl = EntityManagerFactoryProvider.getEntityManagerSetupImpl(sessionName);
if (emSetupImpl == null) {
emSetupImpl = new EntityManagerSetupImpl(uniqueName, sessionName);
isNew = true;
emSetupImpl.setIsInContainerMode(true);
transformer = emSetupImpl.predeploy(info, (Map)nonNullProperties);
EntityManagerFactoryProvider.addEntityManagerSetupImpl(sessionName, emSetupImpl);
}
}
if (!isNew) {
if (!uniqueName.equals(emSetupImpl.getPersistenceUnitUniqueName())) {
throw PersistenceUnitLoadingException.sessionNameAlreadyInUse(sessionName, uniqueName, emSetupImpl.getPersistenceUnitUniqueName());
}
boolean undeployed = false;
synchronized(emSetupImpl) {
if (emSetupImpl.isUndeployed()) {
undeployed = true;
}
transformer = emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), (Map)nonNullProperties);
}
if (undeployed) {
return this.createContainerEntityManagerFactory(info, properties);
}
}
if (transformer != null) {
info.addTransformer(transformer);
}
EntityManagerFactoryImpl factory = new EntityManagerFactoryImpl(emSetupImpl, (Map)nonNullProperties);
if (emSetupImpl.shouldGetSessionOnCreateFactory((Map)nonNullProperties)) {
factory.getServerSession();
}
return factory;
}
public ProviderUtil getProviderUtil() {
return this;
}
public LoadState isLoadedWithoutReference(Object entity, String attributeName) {
return entity instanceof PersistenceWeaved ? this.isLoadedWithReference(entity, attributeName) : LoadState.UNKNOWN;
}
public LoadState isLoadedWithReference(Object entity, String attributeName) {
Iterator setups = EntityManagerFactoryProvider.getEmSetupImpls().values().iterator();
while(setups.hasNext()) {
EntityManagerSetupImpl setup = (EntityManagerSetupImpl)setups.next();
if (setup.isDeployed()) {
Boolean isLoaded = EntityManagerFactoryImpl.isLoaded(entity, setup.getSession());
if (isLoaded != null) {
if (isLoaded && attributeName != null) {
isLoaded = EntityManagerFactoryImpl.isLoaded(entity, attributeName, setup.getSession());
}
if (isLoaded != null) {
return isLoaded ? LoadState.LOADED : LoadState.NOT_LOADED;
}
}
}
}
return LoadState.UNKNOWN;
}
public LoadState isLoaded(Object entity) {
return entity instanceof PersistenceWeaved ? this.isLoadedWithReference(entity, (String)null) : LoadState.UNKNOWN;
}
}
The above is the interface and implementation of PersistenceProvider.
Can't see any mismatch

JERSEY: java.lang.IllegalStateException: The output stream has already been closed

I can access the data from browser using "localhost". But if I mention my system IP address the app is showing below error:
SEVERE: An I/O error has occurred while writing a response message entity to the container output stream.
java.lang.IllegalStateException: The output stream has already been closed.
at org.glassfish.jersey.message.internal.CommittingOutputStream.setStreamProvider(CommittingOutputStream.java:142)
at org.glassfish.jersey.message.internal.OutboundMessageContext.setStreamProvider(OutboundMessageContext.java:812)
at org.glassfish.jersey.server.ContainerResponse.setStreamProvider(ContainerResponse.java:373)
at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:645)
at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:395)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:385)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:280)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:272)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:268)
at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
at org.glassfish.jersey.internal.Errors.process(Errors.java:268)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:289)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:256)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:703)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:416)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:412)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1385)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
This is my AuthenticationFilter class:
package com.howtodoinjava.jersey.provider;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import org.glassfish.jersey.internal.util.Base64;
/**
* This filter verify the access permissions for a user
* based on username and passowrd provided in request
* */
#Provider
public class AuthenticationFilter implements javax.ws.rs.container.ContainerRequestFilter
{
#Context
private ResourceInfo resourceInfo;
private static final String AUTHORIZATION_PROPERTY = "Authorization";
private static final String AUTHENTICATION_SCHEME = "Basic";
private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED)
.entity("You cannot access this resource").build();
private static final Response ACCESS_FORBIDDEN = Response.status(Response.Status.FORBIDDEN)
.entity("Access blocked for all users !!").build();
#Override
public void filter(ContainerRequestContext requestContext)
{
Method method = resourceInfo.getResourceMethod();
//Access allowed for all
if( ! method.isAnnotationPresent(PermitAll.class))
{
//Access denied for all
if(method.isAnnotationPresent(DenyAll.class))
{
requestContext.abortWith(ACCESS_FORBIDDEN);
return;
}
//Get request headers
final MultivaluedMap<String, String> headers = requestContext.getHeaders();
//Fetch authorization header
final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY);
//If no authorization information present; block access
if(authorization == null || authorization.isEmpty())
{
requestContext.abortWith(ACCESS_DENIED);
return;
}
//Get encoded username and password
final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", "");
//Decode username and password
String usernameAndPassword = new String(Base64.decode(encodedUserPassword.getBytes()));;
//Split username and password tokens
final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
final String username = tokenizer.nextToken();
final String password = tokenizer.nextToken();
//Verifying Username and password
System.out.println(username);
System.out.println(password);
//Verify user access
if(method.isAnnotationPresent(RolesAllowed.class))
{
RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));
//Is user valid?
if( ! isUserAllowed(username, password, rolesSet))
{
requestContext.abortWith(ACCESS_DENIED);
return;
}
}
}
}
private boolean isUserAllowed(final String username, final String password, final Set<String> rolesSet)
{
boolean isAllowed = false;
//Step 1. Fetch password from database and match with password in argument
//If both match then get the defined role for user from database and continue; else return isAllowed [false]
//Access the database and do this part yourself
//String userRole = userMgr.getUserRole(username);
if(username.equals("howtodoinjava") && password.equals("password"))
{
String userRole = "ADMIN";
//Step 2. Verify user role
if(rolesSet.contains(userRole))
{
isAllowed = true;
}
}
return isAllowed;
}
}
This is my JerseyService class
package com.howtodoinjava.jersey.provider;
import java.util.ArrayList;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/employees")
public class JerseyService
{
#SuppressWarnings("unchecked")
#RolesAllowed("ADMIN")
#GET
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Employees getAllEmployees()
{
Employees list = new Employees();
list.setEmployeeList(new ArrayList<Employees>());
list.getEmployeeList().add(new Employees(1, "Lokesh Gupta"));
list.getEmployeeList().add(new Employees(2, "Alex Kolenchiskey"));
list.getEmployeeList().add(new Employees(3, "David Kameron"));
return list;
}
}
This is my GsonMessageBodyHandler class:
package com.howtodoinjava.jersey.provider;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonMessageBodyHandler implements MessageBodyWriter<Object>,
MessageBodyReader<Object> {
private static final String UTF_8 = "UTF-8";
private Gson gson;
//Customize the gson behavior here
private Gson getGson() {
if (gson == null) {
final GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.disableHtmlEscaping()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.setPrettyPrinting()
.serializeNulls()
.create();
}
return gson;
}
#Override
public boolean isReadable(Class<?> type, Type genericType,
java.lang.annotation.Annotation[] annotations, MediaType mediaType) {
return true;
}
#Override
public Object readFrom(Class<Object> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream) {
InputStreamReader streamReader = null;
try {
streamReader = new InputStreamReader(entityStream, UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
Type jsonType;
if (type.equals(genericType)) {
jsonType = type;
} else {
jsonType = genericType;
}
return getGson().fromJson(streamReader, jsonType);
} finally {
try {
streamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return true;
}
#Override
public long getSize(Object object, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
#Override
public void writeTo(Object object, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException,
WebApplicationException {
OutputStreamWriter writer = new OutputStreamWriter(entityStream, UTF_8);
try {
Type jsonType;
if (type.equals(genericType)) {
jsonType = type;
} else {
jsonType = genericType;
}
getGson().toJson(object, jsonType, writer);
} finally {
writer.close();
}
}
}
I could not identifying the issue. Please help to resolve the above error.
The problem is the use of a static Response
private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED).entity("You cannot access this resource").build();
The first time you get no error but trying to access the resource a second time trows the error you mentioned. The error has nothing to do with using localhost or the IP of the related host. So modify the code in your AuthenticationFilter like so:
#Provider
public class AuthenticationFilter implements javax.ws.rs.container.ContainerRequestFilter
{
#Context
private ResourceInfo resourceInfo;
private static final String AUTHORIZATION_PROPERTY = "Authorization";
private static final String AUTHENTICATION_SCHEME = "Basic";
#Override
public void filter(ContainerRequestContext requestContext)
{
Method method = resourceInfo.getResourceMethod();
//Access allowed for all
if( ! method.isAnnotationPresent(PermitAll.class))
{
//Access denied for all
if(method.isAnnotationPresent(DenyAll.class))
{
requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity("Access blocked for all users !!").build(););
return;
}
//Get request headers
final MultivaluedMap<String, String> headers = equestContext.getHeaders();
//Fetch authorization header
final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY);
//If no authorization information present; block access
if(authorization == null || authorization.isEmpty())
{
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity("You cannot access this resource").build(););
return;
}
//Get encoded username and password
final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", "");
//Decode username and password
String usernameAndPassword = new String(Base64.decode(encodedUserPassword.getBytes()));;
//Split username and password tokens
final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
final String username = tokenizer.nextToken();
final String password = tokenizer.nextToken();
//Verifying Username and password
System.out.println(username);
System.out.println(password);
//Verify user access
if(method.isAnnotationPresent(RolesAllowed.class))
{
RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));
//Is user valid?
if( ! isUserAllowed(username, password, rolesSet))
{
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity("You cannot access this resource").build(););
return;
}
}
}
}
and your authentication will work smoothly.

Tomcat 8.52 version CsrfPreventionFilter entryPoints param with regex pattern

I am using tomcat 8.52 to fix CSRF issue. In that
am using org.apache.catalina.filters.CsrfPreventionFilter.
How can I use entryPoints param with regex pattern matching.
How I can avoid CSRF checking in my login page.
My login page loads 20 js,40 imags,23 css. How all are can I mention in the entrypoint param?
My web.xml:
<filter>
<filter-name>CsrfFilter</filter-name>
<filter-class>org.apache.catalina.filters.CsrfPreventionFilter</filter-class>
<init-param>
<param-name>denyStatus</param-name>
<param-value>404</param-value>
</init-param>
<init-param>
<param-name>entryPoints</param-name>
<param-value>/mUser/login,/js/encrypt.js,/js/json-min.js,/m User/homepage,/dispatch/sendtemplate</param-value>
</init-param>
When I try to login with my pages, I am seeing only encrypt.js,json-min.js only loaded others are showing 404 error.
Also getting 404 page while logging to the page.
I define my own CsrfPreventionFilter class like this and put my JS and CSS and img in a folder named "static"
package filters.myCatalina;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
public class MyCsrfPreventionFilter extends MyCsrfPreventionFilterBase {
private Logger logger = Logger.getLogger(getClass().getName());
private final Set<String> entryPoints = new HashSet<>();
private int nonceCacheSize = 5;
public void setEntryPoints(String entryPoints) {
String values[] = entryPoints.split(",");
for (String value : values) {
this.entryPoints.add(value.trim());
}
}
public void setNonceCacheSize(int nonceCacheSize) {
this.nonceCacheSize = nonceCacheSize;
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
ServletResponse wResponse = null;
if (request instanceof HttpServletRequest &&
response instanceof HttpServletResponse) {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
boolean skipNonceCheck = false;
logger.info(getRequestedPath(req));
if ("/".equals(getRequestedPath(req)))
skipNonceCheck = true;
if ("/static/".equals(getRequestedPath(req).substring(0, 8)))
skipNonceCheck = true;
if (MyConstants.METHOD_GET.equals(req.getMethod())
&& entryPoints.contains(getRequestedPath(req))) {
skipNonceCheck = true;
}
HttpSession session = req.getSession(false);
#SuppressWarnings("unchecked")
LruCache<String> nonceCache = (session == null) ? null
: (LruCache<String>) session.getAttribute(
MyConstants.CSRF_NONCE_SESSION_ATTR_NAME);
if (!skipNonceCheck) {
String previousNonce =
req.getParameter(MyConstants.CSRF_NONCE_REQUEST_PARAM);
if (nonceCache == null || previousNonce == null ||
!nonceCache.contains(previousNonce)) {
res.sendError(getDenyStatus());
return;
}
}
if (nonceCache == null) {
nonceCache = new LruCache<>(nonceCacheSize);
if (session == null) {
session = req.getSession(true);
}
session.setAttribute(
MyConstants.CSRF_NONCE_SESSION_ATTR_NAME, nonceCache);
}
String newNonce = generateNonce();
nonceCache.add(newNonce);
wResponse = new CsrfResponseWrapper(res, newNonce);
} else {
wResponse = response;
}
chain.doFilter(request, wResponse);
}
protected static class CsrfResponseWrapper
extends HttpServletResponseWrapper {
private final String nonce;
public CsrfResponseWrapper(HttpServletResponse response, String nonce) {
super(response);
this.nonce = nonce;
}
#Override
#Deprecated
public String encodeRedirectUrl(String url) {
return encodeRedirectURL(url);
}
#Override
public String encodeRedirectURL(String url) {
return addNonce(super.encodeRedirectURL(url));
}
#Override
#Deprecated
public String encodeUrl(String url) {
return encodeURL(url);
}
#Override
public String encodeURL(String url) {
return addNonce(super.encodeURL(url));
}
/*
* Return the specified URL with the nonce added to the query string.
*/
private String addNonce(String url) {
if (url == null) {
return nonce;
}
String path = url;
String query = "";
String anchor = "";
int pound = path.indexOf('#');
if (pound >= 0) {
anchor = path.substring(pound);
path = path.substring(0, pound);
}
int question = path.indexOf('?');
if (question >= 0) {
query = path.substring(question);
path = path.substring(0, question);
}
StringBuilder sb = new StringBuilder(path);
if (query.length() > 0) {
sb.append(query);
sb.append('&');
} else {
sb.append('?');
}
sb.append(MyConstants.CSRF_NONCE_REQUEST_PARAM);
sb.append('=');
sb.append(nonce);
sb.append(anchor);
return sb.toString();
}
}
protected static class LruCache<T> implements Serializable {
private static final long serialVersionUID = 1L;
// Although the internal implementation uses a Map, this cache
// implementation is only concerned with the keys.
private final Map<T, T> cache;
public LruCache(final int cacheSize) {
cache = new LinkedHashMap<T, T>() {
private static final long serialVersionUID = 1L;
#Override
protected boolean removeEldestEntry(Map.Entry<T, T> eldest) {
if (size() > cacheSize) {
return true;
}
return false;
}
};
}
public void add(T key) {
synchronized (cache) {
cache.put(key, null);
}
}
public boolean contains(T key) {
synchronized (cache) {
return cache.containsKey(key);
}
}
}
}
my web.xml config
<filter>
<filter-name>CSRF</filter-name>
<filter-class>filters.myCatalina.MyCsrfPreventionFilter</filter-class>
<init-param>
<param-name>entryPoints</param-name>
<param-value>/index.jsp,/,index.jsp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CSRF</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
and in jsp entryPoint
<INPUT type="hidden" name="CSRF_NONCE" value="<%=response.encodeUrl(null)%>">
It's just a sample but it works and if you're using tomcat-catalina dependency you should use "org.apache.catalina.filters.CSRF_NONCE" in org.apache.catalina.filters.Constants class instead of "CSRF_NONCE"

Could Not autowire an object in Mule component

I am trying to autowire an object of a service class in mule flow. The code is:
public class SignatureValidator implements Callable
{
#Autowired
private TriggerHostServiceImpl triggerHostServiceImpl;
#Override
public Object onCall(MuleEventContext eventContext) throws Exception
{
MuleMessage message = eventContext.getMessage();
message = fetchPropertiesAndValidateMessageSignature(message);
return message.getPayload();
}
private MuleMessage fetchPropertiesAndValidateMessageSignature(MuleMessage message) throws GeneralSecurityException, IOException
{
String muleWSTriggerLabel = message.getInboundProperty("triggerLabel");
String muleWSSignature = message.getInboundProperty("signature");
String muleWSExpiresOn = message.getInboundProperty("expiresOn");
String xmlData = message.getInboundProperty("xmlData");
String appHostName = InitConfigurationLoader.getConfigSetting("applicationHostingName");
Trigger triggerJaxbObject = (Trigger) message.getPayload();
String applicationIdentifier = triggerJaxbObject.getApplicationIdentifier();
TriggerMapper triggerMapper = FetchConfigurationEntities.getTriggerMapper(applicationIdentifier, muleWSTriggerLabel);
String reportEmail = FetchConfigurationEntities.getReportEmail(triggerMapper);
ImportDetails importInstance = FetchConfigurationEntities.getImport(triggerMapper);
String importInstanceURL = importInstance.getWebserviceURL();
message.setInvocationProperty("triggerJaxbObject", triggerJaxbObject);
message.setInvocationProperty("importInstance", importInstance);
message.setInvocationProperty("reportEmail", reportEmail);
message.setInvocationProperty("appIdentifier", applicationIdentifier);
message.setInvocationProperty("importHost", importInstanceURL.substring(importInstanceURL.lastIndexOf('/')+1, importInstanceURL.length()));
setPayloadAfterValidation(message, muleWSTriggerLabel, xmlData, muleWSSignature, appHostName, muleWSExpiresOn);
return message;
}
My service class is:
package com.catalystone.csi.service;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.catalystone.csi.core.cache.UpdateCacheable;
import com.catalystone.csi.dao.TriggerHostDao;
import com.catalystone.csi.model.TriggerHost;
#Service
public class TriggerHostServiceImpl implements TriggerHostService
{
#Autowired
private TriggerHostDao triggerHostDao;
#Autowired
private UpdateCacheable updateCacheable;
/**
* Method to save mule configurations i.e. TriggerHosts
*/
#Override
#Transactional
public boolean saveTriggerHost(TriggerHost triggerHost)
{
if(triggerHostDao.saveTriggerHost(triggerHost))
{
Map<String, TriggerHost> allTriggerHosts = getAllTriggerHosts();
allTriggerHosts.put(triggerHost.getTriggerIdentifier(), triggerHost);
updateCacheable.updateAllTriggerHostCache(allTriggerHosts);
return true;
}
else
return false;
}
/**
* Method to fetch all the configurations
*/
#Override
#Transactional//this annotation is used to maintain transaction
public Map<String, TriggerHost> getAllTriggerHosts()
{
return triggerHostDao.getAllTriggerHosts();
}
/**
* Method to delete mule configuration for triggerHost
* #return - true if delete configuration is successfully done
*/
#Override
#Transactional//this annotation is used to maintain transaction
public Boolean deleteConfiguration(TriggerHost triggerHost, boolean isMultipleImportOccurrence)
{
Boolean isDeleteSuccessful = triggerHostDao.deleteConfiguration(triggerHost, isMultipleImportOccurrence);
//Getting all the configurations from cache
Map<String, TriggerHost> allTriggerHosts = getAllTriggerHosts();
//check if delete configuration successful then remove that configuration from cache
if(isDeleteSuccessful)
{
for(Entry<String, TriggerHost> triggerHostEntry : allTriggerHosts.entrySet())
{
if(triggerHostEntry.getValue().getTriggerIdentifier().equals(triggerHost.getTriggerIdentifier()))
{
allTriggerHosts.remove(triggerHostEntry.getKey());
break;
}
}
//update cache
updateCacheable.updateAllTriggerHostCache(allTriggerHosts);
return true;
}
return false;
}
#Override
#Transactional
public Boolean updateConfiguration(TriggerHost triggerHost)
{
if(triggerHostDao.updateConfiguration(triggerHost))
{
Map<String, TriggerHost> allTriggerHosts = getAllTriggerHosts();
allTriggerHosts.put(triggerHost.getTriggerIdentifier(), triggerHost);
updateCacheable.updateAllTriggerHostCache(allTriggerHosts);
return true;
}
return false;
}
#Override
#Transactional
public Boolean deleteConfiguration(String existingImportIdentifier)
{
return triggerHostDao.deleteConfiguration(existingImportIdentifier);
}
}
when I run this code then value of triggerHostServiceImpl is always null. How to autowire? I have also tried a link Dependency Injection is working at Mule application startup. Objects are getting null, when a request received and Failing by throwing NullEx
and
Spring3 Dependency Injection not working with mule
but then it is giving me so many exception that I couldn't get.
you have to Autowire the Interface not the Implementation
#Autowired
private TriggerHostService triggerHostService;
and add the setter and getter of triggerHostService

How to set up Selenium 2.x Test Suites in the same Webdriver in Eclipse (JUnit4)

I have been sifting through the answers on stack for a while now and have come across some examples of work that seem to accomplish this or at least come close.
Use same web driver throughout selenium suite
Before and After Suite execution hook in jUnit 4.x
JUnit Test Suite for Selenium 2
All I want to be able to do is export selenium test cases as JUnit4 files, bring them into eclipse and modify them as needed, then be able to add or remove it from a test suite. When the test suite runs, it should open one webdriver window and run through each test case, just the same way it runs in the selenium IDE on the base firefox window. The only catch seems to be the webdriver class. I have tried referencing this between test case classes, which seems to keep the window up without throwing an error, but the second test case never runs, like it's stuck in a loop, or stopped at #Before
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
#RunWith(Suite.class)
#SuiteClasses({TestCase1.class,TestCase2.class})
public class RunTestSuite {
}
^^^ Test Suite example ^^^
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class TestCase1 {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.google.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testOpen() throws Exception {
driver.get(baseUrl + "");
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
^^^ Test case 1 ^^^
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class TestCase2 {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
if (TestCase1.driver != null) {
driver = TestCase1.driver;
} else {
driver = new FirefoxDriver();
}
baseUrl = "http://www.google.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testOpen() throws Exception {
driver.get(baseUrl + "");
}
#After
public void tearDown() throws Exception {
//driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
^^^ Test Case 2 ^^^
Thanks for any help received!
You will have to change the access modifier of the driver instance from private to static public so that it can be accessed by the second class.
Also make sure both classes at the same package.
Here is how it should be at TestCase1 class
public static WebDriver driver;
I tried it and it works fine with me.