500 Error in Embedded Jetty Application - java

I keep getting a 500 error when I run this code and I cannot, for the life of me, figure out why. If anyone can also help me figure out how to get a stacktrace to print out that'd be awesome as well. Here's the code I have (it's a Maven project):
EDIT: Nothing prints to the server log but I believe this is because Jetty is embedded
package pojo;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.servlet.ServletContainer;
public class Main {
public static void main(String[] args) throws Exception {
Server server = new Server(8112);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
ServletHolder h = new ServletHolder(new ServletContainer());
h.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
h.setInitParameter("com.sun.jersey.config.property.packages", "resources");
h.setInitOrder(1);
context.addServlet(h, "/*");
try
{
server.start();
server.join();
}
catch (Throwable t)
{
t.printStackTrace(System.err);
}
}
}
I'm trying to access this resource:
package resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import java.util.ArrayList;
import java.util.List;
import pojo.Party;
#Path("/parties")
public class AllPartiesResource {
#Context
UriInfo url;
#Context
Request request;
String name;
public static final Timer allTime = DBConnection.registry.timer(MetricRegistry.name("Timer","all-parties"));
#GET
#Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public List<Party> getAllParties() throws Exception
{
final Timer.Context context=allTime.time(); //start the timer
List<Party> list = new ArrayList<Party>();
DBConnection.readAllData();
list.addAll(DBConnection.getPartyCollection().values());
context.stop(); //stops timer
return list;
// ---> code for Jackson
// String string;
// DBConnection.readAllData();
// ObjectMapper jsonMapper = new ObjectMapper();
// string=jsonMapper.writeValueAsString(DBConnection.getPartyCollection());
// return string;
}
#GET
#Path("count")
#Produces(MediaType.TEXT_PLAIN)
public String getPartyCount() throws Exception
{
DBConnection.readAllData();
return String.valueOf(DBConnection.getPartyCollection().size());
}
#Path("{party}") //points to OnePartyResource.class
public OnePartyResource getParty(#PathParam("party")String party)
{
name = party;
return new OnePartyResource(url,request,party);
}
}
Here's my 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>PartyAPI</groupId>
<artifactId>PartyAPIMaven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>com.codahale.metrics</groupId>
<artifactId>metrics-core</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.0.4.v20130625</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.0.4.v20130625</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>9.0.4.v20130625</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jax-rs-ri</artifactId>
<version>2.0-m13</version>
</dependency>
<dependency>
<groupId>com.google.code.simple-spring-memcached</groupId>
<artifactId>spymemcached</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>oss.sonatype.org</id>
<name>OSS Sonatype Staging</name>
<url>https://oss.sonatype.org/content/groups/staging</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.6</version>
<configuration>
<createDependencyReducedPom>true</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<Main-Class>com.resteasy.Star.Main</Main-Class>
</manifestEntries>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
</project>
When I enter in localhost:8112/parties I get the following:
HTTP ERROR: 500
Problem accessing /parties. Reason:
Request failed.
Powered by Jetty://

Figured this error out too. Essentially in my setInitParam() method I'm trying to call a package that doesn't exist. The com.sun.jersey... package didn't exist in my pom. After adding it (and deleting glassfish) it worked perfectly.

Related

Spigot/Bungeecord Hibernate - Invalid logger interface org.hibernate.internal.CoreMessageLogger

I tried using Hibernate ORM to handle my BungeeCord database mappings. I've used it before and had no problems doing so.
Now I revisited Minecraft programming and could not get Hibernate running.
My pom.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.jakobi</groupId>
<artifactId>sessionutil</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>17</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>oss.sonatype.org</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository>
<repository>
<id>maven.enginehub.org</id>
<url>https://maven.enginehub.org/repo/</url>
</repository>
<repository>
<id>repo.spongepowered.org</id>
<url>https://repo.spongepowered.org/maven/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>net.md-5</groupId>
<artifactId>bungeecord-api</artifactId>
<version>1.19-R0.1-SNAPSHOT</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.md-5</groupId>
<artifactId>bungeecord-api</artifactId>
<version>1.19-R0.1-SNAPSHOT</version>
<type>javadoc</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.2.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>23.0.0</version>
</dependency>
</dependencies>
<build>
<defaultGoal>clean install</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<minimizeJar>true</minimizeJar>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>1.0.1</version>
</dependency>
</dependencies>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
And my main is:
package io.jakobi.sessionutil;
import io.jakobi.sessionutil.database.entity.Action;
import io.jakobi.sessionutil.database.entity.Session;
import io.jakobi.sessionutil.database.repository.ActionRepository;
import io.jakobi.sessionutil.database.repository.SessionRepository;
import io.jakobi.sessionutil.listener.PlayerChatListener;
import io.jakobi.sessionutil.listener.PlayerJoinListener;
import io.jakobi.sessionutil.listener.PlayerQuitListener;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.internal.CoreMessageLogger;
import java.io.File;
public class SessionUtil extends Plugin {
private static final String HIBERNATE_CONFIG_FILE_NAME = "hibernate.cfg.xml";
private SessionFactory sessionFactory;
#Override
public void onEnable() {
sessionFactory = new Configuration()
.configure(new File(this.getDataFolder().getAbsolutePath() + "/" + HIBERNATE_CONFIG_FILE_NAME))
.addAnnotatedClass(Session.class)
.addAnnotatedClass(Action.class)
.buildSessionFactory();
ActionRepository actionRepository = new ActionRepository(sessionFactory);
SessionRepository sessionRepository = new SessionRepository(sessionFactory);
registerListener(this, actionRepository, sessionRepository);
}
#Override
public void onDisable() {
if (this.sessionFactory != null) {
this.sessionFactory.close();
}
}
private void registerListener(SessionUtil instance, ActionRepository actionRepository, SessionRepository sessionRepository) {
this.getProxy().getPluginManager().registerListener(instance, new PlayerJoinListener(sessionRepository));
this.getProxy().getPluginManager().registerListener(instance, new PlayerQuitListener(sessionRepository));
this.getProxy().getPluginManager().registerListener(instance, new PlayerChatListener(sessionRepository, actionRepository));
}
}
The issue that I am facing is that on startup, the following exception is thrown:
WARNING] Exception encountered when loading plugin: SessionUtil
java.lang.ExceptionInInitializerError
at io.jakobi.sessionutil.SessionUtil.onEnable(SessionUtil.java:27)
at net.md_5.bungee.api.plugin.PluginManager.enablePlugins(PluginManager.java:265)
at net.md_5.bungee.BungeeCord.start(BungeeCord.java:285)
at net.md_5.bungee.BungeeCordLauncher.main(BungeeCordLauncher.java:67)
at net.md_5.bungee.Bootstrap.main(Bootstrap.java:15)
Caused by: java.lang.IllegalArgumentException: Invalid logger interface org.hibernate.internal.CoreMessageLogger (implementation not found in PluginClassloader(desc=PluginDescription(name=SessionUtil, main=io.jakobi.sessionutil.SessionUtil, version=1.0-SNAPSHOT, author=Lukas Jakobi <lukas#jakobi.io>, depends=[], softDepends=[], file=plugins/sessionutil-1.0-SNAPSHOT.jar, description=A utility plugin to manage user sessions, libraries=[])))
at org.jboss.logging.Logger$1.run(Logger.java:2556)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:318)
at org.jboss.logging.Logger.getMessageLogger(Logger.java:2529)
at org.jboss.logging.Logger.getMessageLogger(Logger.java:2516)
at org.hibernate.internal.CoreLogging.messageLogger(CoreLogging.java:29)
at org.hibernate.internal.CoreLogging.messageLogger(CoreLogging.java:25)
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:106)
... 5 more
A quick google search didn't really help. I found a comment saying I have to initialize the logger with Hibernate.initalize(object). I could not get that to work either.
Thanks in advance for any help! :)
I don't know how class loading works in this "environment", but the hibernate-core.jar should contain a class called org.hibernate.internal.CoreMessageLogger_$logger, which is the logger implementation that apparently can't be found. Maybe the class loader is broken?
Your maven shade plugin contains the following:
<configuration>
<minimizeJar>true</minimizeJar>
</configuration>
This causes all the logging dependencies to be dropped while shading. Removing this line will fix the issue.

415 Unaccepted Media Type Maven Not Working

I converted my ReST web project into a maven project using eclipse and I keep getting this error (415 Unsupported Media Type) when I run it on Tomcat. Any idea on what I could be doing wrong? I am thinking I have an incorrect path in my post/action method in my index.jsp file, but I am not entirely sure because the path was the same for the ReST project and it worked perfectly fine.
This is the beginning of my class:
import com.triprates.*;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.POST;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.ws.rs.FormParam;
#Path("error")
public class RestWeb {
#GET
#Produces(MediaType.TEXT_HTML)
public String getText() {
return "<body> Error. Invalid data. </body>";
}
#POST
#Produces(MediaType.TEXT_HTML)
#Path("/inputvalues")
public String getParamText(#FormParam("travel") String travel,
#FormParam("start") String start,
#FormParam("duration") String end,
#FormParam("party") String people) {
String returnString = processInput(travel, start, end, people);
return "<body> " + returnString + " </body>";
}
my pom file:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>mavenProject</groupId>
<artifactId>mavenProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers </groupId>
<artifactId>jersey-container-servlet </artifactId>
<version>2.25.1</version>
</dependency>
<dependency>
<groupId>javax.ws.rs </groupId>
<artifactId>javax.ws.rs-api </artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject </groupId>
<artifactId>jersey-hk2 </artifactId>
<version>2.28</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
</dependencies>
I have an index.jsp file as well that has my post/action method and a web.xml. Am I missing a dependency that is causing this error?

Pact File Not Generated Inspite of test being Passed

I am trying to generate Pact file.The test is passing when is "Run As-Junit Test" in Eclipse. However, unable to really understand why the Pact Contract File is not generated. Can you please help? Below is my test code:
package pact;
import au.com.dius.pact.consumer.*;
import au.com.dius.pact.consumer.dsl.DslPart;
import au.com.dius.pact.consumer.dsl.PactDslJsonBody;
import au.com.dius.pact.model.PactFragment;
import org.junit.Assert;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.consumer.dsl.PactDslWithState;
import org.junit.Rule;
import org.junit.Test;
import utils.Configuration;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class GetHelloWorldTest
{
#Rule
public PactProviderRule rule = new PactProviderRule("PP Provider", "localhost", 9000, this);
private String helloWorldResults;
#Pact(provider = Configuration.DUMMY_PROVIDER,consumer = Configuration.DUMMY_CONSUMER)
public PactFragment createFragment(PactDslWithProvider builder)//TODO
{
return builder
.uponReceiving("get hello world response")
.path("/hello-world")
.method("GET")
.willRespondWith()
.status(200)
.body("{\"id\":2,\"content\":\"Hello, Stranger!\"}")
.toFragment();
}
#Test
#PactVerification(value = "PP provider")
public void shouldGetHelloWorld() throws IOException
{
DummyConsumer restClient = new DummyConsumer(Configuration.SERVICE_URL);
Assert.assertEquals("{\"id\":32,\"content\":\"Hello, Stranger!\"}",restClient.getHelloWorld());
}
}
My POM File is as below :
<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>consumer</groupId>
<artifactId>consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>3.3.9</version>
</dependency>
<dependency>
<groupId>org.apache.maven.reporting</groupId>
<artifactId>maven-reporting-impl</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-utils</artifactId>
<version>3.0.24</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8</version>
</dependency>
<dependency>
<groupId>au.com.dius</groupId>
<artifactId>pact-jvm-consumer-junit_2.10</artifactId>
<version>2.4.18</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.13</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18</version>
<configuration>
<systemPropertyVariables>
<pact.rootDir>PPPPP/pact</pact.rootDir>
<buildDirectory>${project.build.directory}</buildDirectory>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
I had the same problem that my Pact file has not been generated in the folder that I specified in the maven-surfire-plugin.
However I realized that the file has been generated, but in the folder "target > pacts". To generate the file I just needed to execute the maven goal "mvn test".
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<pact.rootDir>src/test/resources/pacts</pact.rootDir>
<buildDirectory>${project.build.directory}</buildDirectory>
</systemPropertyVariables>
I have set the pact.rootDir like this but it always generates the pact contract in the target/pact folder so now I am taking it from there.
It would seem that you're missing your state specification in the createFragment function.
To fix it in your example, change your function to this:
#Pact(state = "PP provider", provider = Configuration.DUMMY_PROVIDER,consumer = Configuration.DUMMY_CONSUMER)
public PactFragment createFragment(PactDslWithProvider builder)
From here, the verification process will know to check for that state because of the name, verify it, then write the Pact file out under the pacts directory, which is the default.
Here's an example that works for me:
package pact;
import au.com.dius.pact.consumer.*;
import au.com.dius.pact.model.PactFragment;
import org.junit.Rule;
import org.junit.Test;
import utils.Configuration;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class GetHelloWorldTest
{
#Rule
public PactRule rule = new PactRule(Configuration.MOCK_HOST, Configuration.MOCK_HOST_PORT, this);
private DslPart helloWorldResults;
#Pact(state = "HELLO WORLD", provider = Configuration.DUMMY_PROVIDER, consumer = Configuration.DUMMY_CONSUMER)
public PactFragment createFragment(ConsumerPactBuilder.PactDslWithProvider.PactDslWithState builder)
{
helloWorldResults = new PactDslJsonBody()
.id()
.stringType("content")
.asBody();
return builder
.uponReceiving("get hello world response")
.path("/hello-world")
.method("GET")
.willRespondWith()
.status(200)
.headers(Configuration.getHeaders())
.body(helloWorldResults)
.toFragment();
}
#Test
#PactVerification("HELLO WORLD")
public void shouldGetHelloWorld() throws IOException
{
DummyConsumer restClient = new DummyConsumer(Configuration.SERVICE_URL);
assertEquals(helloWorldResults.toString(), restClient.getHelloWorld());
}
}
Pact JVM appears to ignore the buildDirectory property
Try the following configuration:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18</version>
<configuration>
<systemPropertyVariables>
<pact.rootDir>${project.build.directory}/pacts</pact.rootDir>
<buildDirectory>${project.build.directory}</buildDirectory>
</systemPropertyVariables>
</configuration>
</plugin>

Get client ip in Jersey 2.22.2

I am trying to access the clients IP that are calling my rest server but I only get null as a response. The web-server is running and I can access it from the web browser.
I have tried with
#Context HttpServletRequest
And also with
#Context ContainerRequest request
request.getRequestHeader("HTTP_FORWARDED")
//HTTP_X_FORWARDED
//HTTP_CLIENT_IP
But neither succeeds, the response is null or blank.
Setup
Jersey v: 2.22.2
Grizzly v: 2.3.22
Java v: 8
Rest.java
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.container.ContainerRequestContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
#Path("/rest")
public class Rest {
#GET
#Path("/test/")
#Produces(MediaType.APPLICATION_JSON)
public TestAddress test(#Context HttpServletRequest re){
System.out.println(re.getRemoteAddr());
TestAddress adr = new TestAddress();
adr.setAge(32);
adr.setName("Fidde");
adr.setSurename("Lass");
//System.out.println(uriInfo.getBaseUri());
return adr;
}
main.java
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import java.io.IOException;
import java.net.URI;
public class Main {
// Base URI the Grizzly HTTP server will listen on
public static final String BASE_URI = "http://localhost:8080/myapp/";
/**
* Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
* #return Grizzly HTTP server.
*/
public static HttpServer startServer() {
// create a resource config that scans for JAX-RS resources and providers
// in com.example package
final ResourceConfig rc = new ResourceConfig().packages("com.example");
// create and start a new instance of grizzly http server
// exposing the Jersey application at BASE_URI
return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
}
/**
* Main method.
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
final HttpServer server = startServer();
System.out.println(String.format("Jersey app started with WADL available at "
+ "%sapplication.wadl\nHit enter to stop it...", BASE_URI));
System.in.read();
server.stop();
}
}
Pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
Test
Bootstrap
jar
0.0.1-SNAPSHOT
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>backend.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.22.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-grizzly2-http</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<jersey.version>2.22.2</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
HttpServletRequest provides a getRemoteAddr() method that should returns the remote IP address.
Note that proxying or NATing may modify the IP address.
EDIT :
The solution is to inject a grizzly request :
#GET
#Path("/test/")
#Produces(MediaType.APPLICATION_JSON)
public TestAddress test(#Context org.glassfish.grizzly.http.server.Request re) {
System.out.println(re.getRemoteAddr());
...
}
This is working for me, but it is totally grizzly dependant.

How to embed Jetty and Jersey into my Java application

So I'm trying to embed jetty into my web application so that if I package it as a jar someone can just run the jar file without having to worry about configuring a server. However, I'm having some problems setting up my main class so that jetty can access my resource classes. I've looked at tutorials but they haven't given me exactly what I'm looking for. This is what I have so far.
package pojo;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class Main {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
context.setContextPath("/");
ServletHolder h = new ServletHolder(new DefaultServlet());
h.setInitParameter("javax.ws.rs.Application","resources.DBCollection");
context.addServlet(h, "/*");
server.setHandler(context);
server.start();
server.join();
}
}
And I'm trying to map it to this class:
package resources;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import pojo.Party;
#Path("/parties")
public class DBCollection {
#Context
UriInfo url;
#Context
Request request;
String name;
#GET
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Party> getAllParties() throws Exception
{
List<Party> list = new ArrayList<Party>();
list.addAll(DBConnection.getPartyCollection().values());
return list;
}
#GET
#Path("count")
#Produces(MediaType.TEXT_PLAIN)
public String getPartyCount() throws Exception
{
return String.valueOf(DBConnection.getPartyCollection().size());
}
#Path("{party}")
public DBResource getParty(#PathParam("party")String party)
{
return new DBResource(url,request,party);
}
}
Here's my POM file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>PartyAPI</groupId>
<artifactId>PartyAPIMaven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>com.codahale.metrics</groupId>
<artifactId>metrics-core</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.0.0.RC0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.0.0.RC0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>9.0.0.RC0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.0-SNAPSHOT</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>oss.sonatype.org</id>
<name>OSS Sonatype Staging</name>
<url>https://oss.sonatype.org/content/groups/staging</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.6</version>
<configuration>
<createDependencyReducedPom>true</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<Main-Class>com.resteasy.Star.Main</Main-Class>
</manifestEntries>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
A few things.
Jetty 9.0.0.RC0 is an old, not-yet stable, release candidate, consider upgrading to a stable, final release, such as 9.0.4.v20130625
You need something that will connect that Jax RS class into the servlet api. Usually done via a Servlet or some sort of initialization with your library of choice. (In you case Jersey)
In your example, you have only setup a DefaultServlet to serve static files, nothing has been configured to use your DBCollection object.
For Jersey, you'll need to configure the org.glassfish.jersey.servlet.ServletContainer and setup its servlet-mappings on a context of your choice.
Example:
package com.example;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class Main
{
public static void main(String[] args)
{
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
context.setContextPath("/");
server.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/webapi/*");
jerseyServlet.setInitOrder(1);
jerseyServlet.setInitParameter("jersey.config.server.provider.packages","com.example");
ServletHolder staticServlet = context.addServlet(DefaultServlet.class,"/*");
staticServlet.setInitParameter("resourceBase","src/main/webapp");
staticServlet.setInitParameter("pathInfoOnly","true");
try
{
server.start();
server.join();
}
catch (Throwable t)
{
t.printStackTrace(System.err);
}
}
}
This example adds the ServletContainer that jersey provides to the ServletContextHandler that Jetty uses to look up what to do based on the incoming request. Then it adds the DefaultServlet to handle any requests for content that Jersey does not handle (such as static content)
In case you want to completely manage the lifecycle of your DBCollection resource programmatically (eg you instantiate it yourself, do some setup/initialization etc), instead of having Jersey create the instance for you, you can use a ResourceConfig like such:
ServletContextHandler sch = new ServletContextHandler();
sch.setContextPath("/xxx");
TheResource resource = new TheResource();
ResourceConfig rc = new ResourceConfig();
rc.register(resource);
ServletContainer sc = new ServletContainer(rc);
ServletHolder holder = new ServletHolder(sc);
sch.addServlet(holder, "/*");
Server server = new Server(port);
server.setHandler(sch);
server.start();
server.join();
Note the line TheResource resource = new TheResource();. Here we create our own instance of TheResource, and we can manipulate it at will now.

Categories