Error while adding servlet mapping for path - java

I am trying to deploy my application on a local Websphere Application Server (Version "8.5.5.5").
If I click "Run on Server", I always get:
Error while adding servlet mapping for path-->/xcc-admin/test/query,
wrapper-->ServletWrapper[XCCAdminServlet.XCCAdminMain:[/XCCAdminMain,
/xcc-admin/rest/query, /xcc-admin/test/query]],
application-->xcc-admin.
Code:
package XCCAdminServlet;
import java.io.IOException;
import javax.annotation.Resource;
import javax.annotation.Resource.AuthenticationType;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
/**
* Servlet implementation class XCCAdminMain
*/
#WebServlet({"/XCCAdminMain", "/xcc-admin/rest/query", "/xcc-admin/test/query"})
#Resource(name = "jdbc/MyDataSource", type = javax.sql.DataSource.class, shareable = true, authenticationType = AuthenticationType.CONTAINER)
public class XCCAdminMain extends HttpServlet {
private static final long serialVersionUID = 1L;
#PersistenceUnit(unitName = "XCCAdminUnit")
private EntityManagerFactory emf;
/**
* #see HttpServlet#HttpServlet()
*/
public XCCAdminMain() {
super();
// TODO Auto-generated constructor stub
}
#GET
#Path("/{param}")
public Response getQuery(#PathParam("param") String msg) throws ServletException {
return Response.status( 200 ).entity( "Get Request received, queryparam: " + msg ).build();
}
}
How to fix this?

Related

assert output response sling servlet filter

I am trying to assert output of the below transformed response from sling servlet filter. I am not able to get hold of output response and not able to assert.
import com.day.cq.wcm.api.Page;
import com.safeway.app.rxwa.pharmacy.utils.HttpServletResponseCopier;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.engine.EngineConstants;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* This filter rewrites link for the Content Fragment list model exporter
*/
#Component(service = Filter.class,
immediate = true,
configurationPolicy = ConfigurationPolicy.REQUIRE,
property = {
EngineConstants.SLING_FILTER_SCOPE + "=" + EngineConstants.FILTER_SCOPE_REQUEST,
EngineConstants.SLING_FILTER_METHODS + "=GET",
EngineConstants.SLING_FILTER_PATTERN + "=/content/experience-fragments/rxwa/.*",
EngineConstants.SLING_FILTER_SELECTORS + "=model",
EngineConstants.SLING_FILTER_EXTENSIONS + "=json"})
#Designate(ocd = ContentJsonLinkRewriterFilter.Config.class)
public class ContentJsonLinkRewriterFilter implements Filter {
private static final Logger logger =
LoggerFactory.getLogger(ContentJsonLinkRewriterFilter.class);
private Config config;
private List<String> resourceTypes;
#Reference
private ResourceResolverFactory resolverFactory;
#Activate
public void activate(Config config) {
this.config = config;
this.resourceTypes = Arrays.asList(config.resourceTypes());
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
// no-op
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String resultString = "{}";
// add author check
if (!(response instanceof SlingHttpServletResponse) || !(request instanceof SlingHttpServletRequest)) {
throw new IllegalStateException("Filter not properly registered as Sling Servlet Filter");
}
if (!config.enabled()) {
logger.debug("Filter disabled");
filterChain.doFilter(request, response);
return;
}
SlingHttpServletRequest slingHttpServletRequest = (SlingHttpServletRequest) request;
Resource currentResource = slingHttpServletRequest.getResource();
String currentResourceType = currentResource.getResourceType();
if(currentResource.isResourceType("cq:Page")) {
Page page = slingHttpServletRequest.getResource().adaptTo(Page.class);
currentResourceType = page.getContentResource().getResourceType();
}
String finalProcessResourceType = currentResourceType;
if (resourceTypes.stream().noneMatch(resourceType -> StringUtils.startsWith(finalProcessResourceType, resourceType))) {
logger.debug("Current resource path {} is not configured to be evaluated", currentResourceType);
filterChain.doFilter(request, response);
return;
}
// Wrap Response Class before servlet gets called
HttpServletResponseCopier responseCopier = new HttpServletResponseCopier((SlingHttpServletResponse) response);
filterChain.doFilter(request, responseCopier);
// externalize links after the servlet finishes
responseCopier.flushBuffer();
//read original response
byte[] responseBytes = responseCopier.getCopy();
String responseString = new String(responseBytes, responseCopier.getCharacterEncoding());
if (StringUtils.isNotEmpty(responseString)) {
//replace all links
resultString = responseString.replaceAll(StringUtils.substring(slingHttpServletRequest.getRequestURI(),0, slingHttpServletRequest.getRequestURI().lastIndexOf("/")), "");
}
responseCopier.resetBuffer();
responseCopier.getOutputStream().write(resultString.getBytes());
responseCopier.setContentType("application/json");
responseCopier.setCharacterEncoding("utf-8");
}
#Override
public void destroy() {
// no-op
}
#ObjectClassDefinition(name = "Content Fragment List Link Rewriter Filter",
description = "Configuration for filter to extend Content Fragment List functionality to rewrite links")
public #interface Config {
#AttributeDefinition(name = "Enabled",
description = "If this filter should not be active, rather try to delete this config. " + "Only in cases " +
"where this cannot be easily accomplished uncheck this option to disable the filter.") boolean enabled() default false;
#AttributeDefinition(name = "Resource Types",
description = "Resource Types to be evaluated by the filter.") String[] resourceTypes();
}
}
Unit test I tried
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import com.safeway.app.rxwa.pharmacy.utils.HttpServletResponseCopier;
import io.wcm.testing.mock.aem.junit.AemContext;
import org.apache.commons.io.IOUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.testing.mock.osgi.MapUtil;
import org.apache.sling.testing.mock.sling.loader.ContentLoader;
import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import com.day.cq.commons.jcr.JcrConstants;
import com.day.cq.wcm.api.components.ComponentContext;
import com.day.cq.wcm.api.designer.Design;
import com.day.cq.wcm.api.designer.Designer;
import com.google.common.collect.Sets;
import org.mockito.junit.MockitoJUnitRunner;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
#RunWith(MockitoJUnitRunner.class)
public class ContentJsonLinkRewriterFilterTest {
protected static final String CONTENT_ROOT = "/content/experience-fragments/rxwa";
public Map<String, Object> props = new HashMap<>();
#Rule
public AemContext context = new AemContext();
#Mock
FilterChain chain;
public ContentJsonLinkRewriterFilter filter;
#Before
public void setUp() {
context.load().json("/test-page-content.json", "/content/experience-
fragments/rxwa");
props.clear();
props.put("enabled", "true");
props.put("resourceTypes", new String[] {"rxwa-
pharmacy/components/structure/xfpage"});
ContentJsonLinkRewriterFilter aei = context.registerInjectActivateService(new
ContentJsonLinkRewriterFilter(), props);
filter = Mockito.spy(aei);
}
#Test
public void doFilterCall() throws ServletException, IOException {
context.requestPathInfo().setResourcePath("/content/experience-fragments/rxwa/templated-
page");
context.requestPathInfo().setSelectorString("model");
context.requestPathInfo().setExtension("json");
context.request().setMethod("GET");
context.response().setCharacterEncoding("UTF-8");
context.currentPage("/content/experience-fragments/rxwa/templated-page");
Mockito.doAnswer(invocation -> {
HttpServletResponseWrapper httpServletResponseWrapper =
(HttpServletResponseWrapper) invocation.getArguments()[1];
String testHtmlContent = IOUtils.toString(
ContentLoader.class.getResourceAsStream("/test-page-content.json"),
StandardCharsets.UTF_8
);
httpServletResponseWrapper.getWriter()
.write(testHtmlContent);
httpServletResponseWrapper.getWriter().flush();
return null;
}).when(chain).doFilter(Mockito.any(), Mockito.any());
filter.doFilter(context.request(), context.response(), chain);
Mockito.verify(chain).doFilter(Mockito.any(), Mockito.any());
String testHtmlContent2 = IOUtils.toString(
ContentLoader.class.getResourceAsStream("/test-page-content.json"),
StandardCharsets.UTF_8
);
}
}

RestEasy Mock unit test with CDI

I've a simple RestEasy WebServie which will take a dependency.
When I test by publishing into Wildfly server everything is working fine. But I tried to mock it using JUnit. But, it's throwing null pointer exception as the dependency isn't injected.
Following is the code which I've done. What is wrong I'm doing.
WebService;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/")
public class IlService {
#Inject
private il.helper.RequestData rData;
#GET
public Response postIds() {
return Response.status( 200 ).type( MediaType.TEXT_HTML ).entity( rData.getRequestData().get( "logicalOperator" ).asText() ).build();
}
}
JUnit Test class:
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.jboss.resteasy.spi.InjectorFactory;
import org.jboss.resteasy.spi.PropertyInjector;
import org.jboss.resteasy.spi.Registry;
import org.jboss.resteasy.spi.ResourceFactory;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.junit.Before;
import org.junit.Test;
import il.helper.RequestData;
import il.services.IlService;
import junit.framework.Assert;
public class IlServiceTest {
private Dispatcher dispatcher;
ResteasyProviderFactory resteasyProviderFactory;
ResourceFactory factory;
InjectorFactory injectorFactory;
PropertyInjector propertyInjector;
#Before
public void setUpResource() {
dispatcher = MockDispatcherFactory.createDispatcher();
resteasyProviderFactory = dispatcher.getProviderFactory();
injectorFactory = resteasyProviderFactory.getInjectorFactory();
propertyInjector = injectorFactory.createPropertyInjector( IlService.class, resteasyProviderFactory );
propertyInjector.inject( new RequestData() );
resteasyProviderFactory.setInjectorFactory( injectorFactory );
Registry registry = dispatcher.getRegistry();
registry.addSingletonResource( new IlService() );
}
#Test
public void IlServicePost() {
try {
MockHttpRequest request = MockHttpRequest.create( "get", "" );
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke( request, response );
Assert.assertEquals( 200, response.getStatus() );
} catch ( Exception e ) {
e.printStackTrace();
}
}
}

Java tomcat sound

i got the folloing warning
28-Jun-2016 16:09:36.482 WARNING [localhost-startStop-2]
org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads
The web application [PickByVoice] appears to have started a thread
named [Java Sound Event Dispatcher] but has failed to stop it. This is
very likely to create a memory leak. Stack trace of thread:
java.lang.Object.wait(Native Method)
java.lang.Object.wait(Object.java:502)
com.sun.media.sound.EventDispatcher.dispatchEvents(EventDispatcher.java:182)
com.sun.media.sound.EventDispatcher.run(EventDispatcher.java:222)
java.lang.Thread.run(Thread.java:745)
I got a webservice and when a request is called the webservice will playback a sound file. It doesnt work.
It works in eclipse useing the tomcat server. dont know why
hope someone can help me
thx
here is some code:
class Webservice
import java.io.IOException;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
//Import all the needed classfiles
import org.PickByVoice.bluetooth.btautoconnect;
import org.PickByVoice.model.Languages;
import org.PickByVoice.model.WavFile;
import org.PickByVoice.service.AudioService;
import org.PickByVoice.service.UploadService;
import org.PickByVoice.exception.Statues;
#Path("restwebservice") //rootpath of the Servlet
#Singleton //Singleton is used to creat only one instance for all requests. So the Wav-Filelist needs to initiate only once.
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.TEXT_HTML)
public class RaspberryPiResources {
//creating instance, setting variables
long startTime=System.currentTimeMillis();
Languages listLanguages=new Languages();
AudioService audioService = new AudioService();
btautoconnect bluetoothAutoConnection=new btautoconnect();
public static WavFile wavFileList;
final String
String currentId="",currentShelfId="",currentstate="nothing scanned",language,location,currentthread;
int i=0;
public RaspberryPiResources(){
language="eng";
audioService.seterrorList("eng"); // Language specific error files are loaded
}
#GET
#Path("init")
public Response initialization(#DefaultValue("eng") #QueryParam ("language") String language,#QueryParam("warehouse") String country) throws InterruptedException, IOException{
audioService.playinit(1L,language);
return Response.status(Statues.INITSUCESS).type(MediaType.TEXT_PLAIN).entity("ok").build(); //Status code 600
}
#GET
#Path("/sounds/messages/{messageId}")
public Response outputErrorSounds(#PathParam("messageId") final long soundId) throws InterruptedException, IOException{
currentthread=Thread.currentThread().getName();
audioService.setcurrentThread(currentthread);
audioService.errorSound(soundId,language,currentstate,currentId,currentthread); //Playing the error message and repeating the scann-Id
return Response.status(Statues.OK).entity(Statues.OK.getReasonPhrase()).build(); //Status code 603
}
class AudioService
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class AudioService{
public AudioInputStream audioInStream = null;
public FilterIds filterId=new FilterIds();
public File file;
public SourceDataLine sourceDataLine;
char firstcharacter;
String compare="",currentThread="",Threadcompare="",vrrr="";
WavFile wav;
public AudioService() {
// TODO Auto-generated constructor stub
}
//Stops and closes the SourceDataLine
public void closeAudioLine(){
sourceDataLine.stop();
sourceDataLine.flush();
sourceDataLine.close();
}
public void playinit(Long idOfSound, String language) throws InterruptedException, IOException{
wav=new WavFile(language);
String soundpath=wav.getErrorSoundFileList().get(idOfSound);
currentThread="init";
playAudio(soundpath);
}
public synchronized String errorSound(Long soundId, String language,String currentState,String currentId, String Threadname) throws InterruptedException, IOException{
currentThread="playerrorSound";
if(!currentThread.equals("playerrorSound")){
ack();
}
if(Threadname.equals(Thread.currentThread().getName()))
{
Threadcompare=Thread.currentThread().getName();
String soundpath=wav.getErrorSoundFileList().get(soundId);
playAudio(soundpath);
try{
audioInStream.close();
}catch(IOException ioe)
{ioe.printStackTrace();}
}
return "end";
}

How to set response header for digital asset in AEM CQ6.1?

I have a request that if a user directly accesses a .pdf asset(for example, http://localhost:4505/content/dam/company/us/en/962059.pdf) from AEM CQ 6.1, I need to send a custom http respone header. This is what I wrote. This is only works if I open a .html page. But it doesn't work if I open a .pdf in browser. So what did I do wrong?
Thanks
package com.mycompany.wcm.filter;
import org.apache.felix.scr.annotations.*;
import org.apache.felix.scr.annotations.sling.SlingFilter;
import org.apache.felix.scr.annotations.sling.SlingFilterScope;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.*;
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.apache.sling.runmode.RunMode;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.Session;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
#SlingFilter(
label = "Sample Filter",
description = "Sample Description",
metatype = true,
generateComponent = true, // True if you want to leverage activate/deactivate
generateService = true,
order = -501, // The smaller the number, the earlier in the Filter chain (can go negative);
scope = SlingFilterScope.REQUEST)
#Properties({
#Property(
label = "Vendor",
name = "service.vendor",
value = "SampleVendor",
propertyPrivate = true
)
})
public class AssetFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
final SlingHttpServletResponse slingResponse = (SlingHttpServletResponse) response;
slingResponse.setHeader("myheader1","no-cache");
slingResponse.setHeader("myheader2","no-store");
chain.doFilter(request, response);
}
#Override
public void destroy() {
}
}
Just a update, initialy I thought the problem only happens to .pdf file, but this also happens to image file. So I created a regular JSP web application, and this code is working for regular web app. Is there something funny on AEM side?

java.lang.NoClassDefFoundError how to resolved this error

when i submit the registration form Registration servlet run but when i created an object of session factory of hibernate it give me an Exception ."javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)".Please help me to find from this exception.
package login;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
#WebServlet("/Registration")
public class Registration extends HttpServlet {
private static final long serialVersionUID = 1L;
public Registration() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String username = request.getParameter("username");
String password = request.getParameter("password");
String name = request.getParameter("name");
User u = new User();
u.setUsername(username);
u.setPassword(password);
u.setName(name);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
}
Add latest hibernate.jar in your class path

Categories