Jersey 1.9 webapp on Tomcat 8 (Eclipse) upgrade to 1.19.1 cause 404 error - eclipse

if I change the jersey version to a higher one than 1.9 then a 404 error returns when I try to run the servlet.
Here are some details of my setting:
- Tomcat 8
- Eclipse Luna
- Maven for integrating the lib
I guess there are maybe changes in the syntax of the RestFul service provide since 1.9, but I'm not sure. So here is the servlet code:
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
#Path("/helloWorldREST")
public class HelloWorldREST {
#GET
#Path("/{parameter}")
public Response responseMsg( #PathParam("parameter") String parameter,
#DefaultValue("Nothing to say") #QueryParam("value") String value) {
String output = "Hello from: " + parameter + " : " + value;
return Response.status(200).entity(output).build();
}
}

Related

Junit class failing after ACS Commons version upgrade to 5.3.4

I upgraded ACS Commons version from 5.0.6 to 5.3.4 in my project and now can see most of the test classes failing with below error
org.junit.jupiter.api.extension.ParameterResolutionException: Failed to resolve parameter [io.wcm.testing.mock.aem.junit5.AemContext arg0] in method [void com.test.test.core.filters.LoggingFilterTest.doFilter(io.wcm.testing.mock.aem.junit5.AemContext) throws java.io.IOException,javax.servlet.ServletException]: Could not create io.wcm.testing.mock.aem.junit5.ResourceResolverMockAemContext instance.
at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameter(ExecutableInvoker.java:232)
at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameters(ExecutableInvoker.java:176)
at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameters(ExecutableInvoker.java:137)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:118)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:184)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:180)
a
Caused by: org.reflections.ReflectionsException: Scanner TypeAnnotationsScanner was not configured
at org.reflections.Store.get(Store.java:39)
at org.reflections.Store.get(Store.java:61)
at org.reflections.Store.get(Store.java:46)
Please find below my test class. I am using JUnit version as below
<dependency>
<groupId>io.wcm</groupId>
<artifactId>io.wcm.testing.aem-mock.junit5</artifactId>
<version>4.0.4</version>
<scope>test</scope>
</dependency>
Attaching the class below:
import java.io.IOException;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import org.apache.sling.testing.mock.sling.servlet.MockRequestPathInfo;
import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest;
import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;
import uk.org.lidalia.slf4jext.Level;
import uk.org.lidalia.slf4jtest.LoggingEvent;
import uk.org.lidalia.slf4jtest.TestLogger;
import uk.org.lidalia.slf4jtest.TestLoggerFactory;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
#ExtendWith(AemContextExtension.class)
class LoggingFilterTest {
private LoggingFilter fixture = new LoggingFilter();
private TestLogger logger = TestLoggerFactory.getTestLogger(fixture.getClass());
#BeforeEach
void setup() {
TestLoggerFactory.clear();
}
#Test
void doFilter(AemContext context) throws IOException, ServletException {
MockSlingHttpServletRequest request = context.request();
MockSlingHttpServletResponse response = context.response();
MockRequestPathInfo requestPathInfo = (MockRequestPathInfo) request.getRequestPathInfo();
requestPathInfo.setResourcePath("/content/test");
requestPathInfo.setSelectorString("selectors");
fixture.init(mock(FilterConfig.class));
fixture.doFilter(request, response, mock(FilterChain.class));
fixture.destroy();
List<LoggingEvent> events = logger.getLoggingEvents();
assertEquals(0, events.size());
}
}
Does anyone know why it is failing with the ACS Commons version change?
This is like breaking lot many junit test classes

JAX-RS not responding at all (404)

I'm using Eclipse 2020-03, Gradle and Tomcat. all I did follows.
Installing gradle through eclipse marketplace.
making gradle project.
adding those on build.gradle dependencies
dependencies {
// This dependency is exported to consumers, that is to say found on their compile classpath.
api 'org.apache.commons:commons-math3:3.6.1'
// This dependency is used internally, and not exposed to consumers on their own compile classpath.
implementation 'com.google.guava:guava:28.2-jre'
// Use JUnit test framework
testImplementation 'junit:junit:4.12'
compile 'org.glassfish.jersey.containers:jersey-container-servlet:2.27'
compile group: 'org.glassfish.jersey.inject', name: 'jersey-hk2', version: '2.27'
compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.4.0-b180830.0359'
compile group: 'org.glassfish.jersey.media', name: 'jersey-media-json-jackson', version: '2.27'
}
adding "rest" package on src/main/java
adding ApplicationConfig.java and RestApiService.java on rest package.
ApplicationConfig.java
package rest;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("/api")
public class ApplicationConfig extends Application {
#Override
public Map<String, Object> getProperties(){
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("jersey.config.server.provider.packages", "A_UnivG.rest");
return properties;
}
}
RestApiService.java
package rest;
import java.util.logging.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import Data.*;
#Path("/Data")
public class RestApiService {
Logger logger = Logger.getLogger("RestApiService");
IntegrationDAO dao = new IntegrationDAO();
#GET
#Path("hello")
#Produces(MediaType.TEXT_PLAIN)
public String getHello() {return "Hello";}
}
and when I try to request http://localhost:portnumber/A_UnivG/api/Data/hello it spits out only 404 error.
cannot figure out why.
My project works with plain jsp files. I have a JSP page which uses DAO Read but it works just fine. well, that shouldn't be a problem I just tried hello world and it doesn't work at all.

Running appium with .bat file

I need some to help me with the below. I am having error each time i run this project. It launches the cmd but fail to run the test.
package Automation;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.remote.MobilePlatform;
public class FirstAppiumTest {
#Test
public void startappium () throws IOException, InterruptedException
{
Runtime.getRuntime().exec ("cmd /c start C:\\startappium.bat");
Thread.sleep(7000L);
File appDir=new File("src");
File app = new File(appDir,"app.apk");
DesiredCapabilities cap=new DesiredCapabilities();
cap.setCapability(MobileCapabilityType.PLATFORM_NAME,MobilePlatform.ANDROID);
cap.setCapability(MobileCapabilityType.DEVICE_NAME,"Android Emulator");
cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 100);
cap.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
AndroidDriver driver = new AndroidDriver (new URL ("http://127.0.0.1:4723/wd/hub"),cap);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
}
}
Here are the errors below.
FAILED: startappium
java.lang.NoSuchMethodError: com.google.common.collect.ImmutableSet.toImmutableSet()Ljava/util/stream/Collector;
at org.openqa.selenium.remote.ProtocolHandshake.streamW3CProtocolParameters(ProtocolHandshake.java:238)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
I appreciate your prompt reply. Thank you

POST Request not working with CORS (Java EE7, Glassfish 4.1, JAX-RS 2.0)

I used NetBeans IDE 8.0.1 "RESTful Web Services from database" wizard to map my table objects with JPA and JAX-RS 2.0.
After the classes were created, with the project options "Test RESTful Web Services", NetBeans itself creates an interface (HTML, css).
This works fine in my localhost. I can connect to my database from the Web Services created, sending GET and POST (JSON) Requests.
Now, I need to access from another domain different from my localhost, so I tried with CORS.
Searching diferent post I used this code:
package CORS;
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.ext.Provider;
#Provider
#PreMatching
public class CORSResponseFilter implements ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException {
response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}
And with this ApplicationConfig class created, the resource (CORSRequestFilter) was added:
package entities.service;
import java.util.Set;
import javax.ws.rs.core.Application;
#javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(CORS.CORSResponseFilter.class);
resources.add(entities.service.AppSettingsFacadeREST.class);
resources.add(entities.service.CategoryFacadeREST.class);
resources.add(entities.service.CityFacadeREST.class);
resources.add(entities.service.EmailInitialSubscriptionFacadeREST.class);
resources.add(entities.service.IdentityProviderFacadeREST.class);
resources.add(entities.service.ItemFacadeREST.class);
resources.add(entities.service.ItemHistoryFacadeREST.class);
resources.add(entities.service.ItemStatusFacadeREST.class);
resources.add(entities.service.PhotoFacadeREST.class);
resources.add(entities.service.UserFacadeREST.class);
resources.add(entities.service.WantedItemsFacadeREST.class);
}
}
And it works perfectly for a while!
I was able to connect to my database to my Glassfish server from another domain using the RESTful web services just fine. I even develop an AngularJS app and could use the RSWebServices too.
Then I started to receive this error:
XMLHttpRequest cannot load http://xx.x.xxx.xx:8080/freeproject/webresources/entities.emailinitialsubscription. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxxxxxxxxxx.com' is therefore not allowed access. The response had HTTP status code 400.
The preflight request is returned with a status 200 OK. But the POST request is failed.
Searching on internet I found that Oracle itself https://blogs.oracle.com/theaquarium/entry/supporting_cors_in_jax_rs tells me to follow this post:
http://www.developerscrappad.com/1781/java/java-ee/rest-jax-rs/java-ee-7-jax-rs-2-0-cors-on-rest-how-to-make-rest-apis-accessible-from-a-different-domain/
So, I tried that and I added a new class: resources.add(CORS.CORSRequestFilter.class):
package CORS;
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
#Provider
#PreMatching
public class CORSRequestFilter implements ContainerRequestFilter {
#Override
public void filter( ContainerRequestContext requestCtx ) throws IOException {
String path = requestCtx.getUriInfo().getPath();
// IMPORTANT!!! First, Acknowledge any pre-flight test from browsers for this case before validating the headers (CORS stuff)
if ( requestCtx.getRequest().getMethod().equals( "OPTIONS" ) ) {
requestCtx.abortWith( Response.status( Response.Status.OK ).build() );
}
}
}
But it doesn't work. The abortWith function stop the chain of requests and the POST request is never sent.
What can I do here? Any help will be highly appreciated.

What library are HtmlUnitDriver & WebDriver part of?

Using below code (taken from http://www.scalatest.org/user_guide/using_selenium)
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.selenium.WebBrowser
import org.scalatest.FlatSpec
class BlogSpec extends FlatSpec with ShouldMatchers with WebBrowser {
implicit val webDriver: WebDriver = new HtmlUnitDriver
"The blog app home page" should "have the correct title" in {
go to (host + "index.html")
title should be ("Awesome Blog")
}
}
I receive the errors
Multiple markers at this line
- not found: type HtmlUnitDriver
- not found: type WebDriver
Are the HtmlUnitDriver & WebDriver libraries not part of the scalatest installation, where can I import them from ?
I just needed the Selenium dependency (http://seleniumhq.org/download/maven.html) :
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.24.1</version>
</dependency>