Jersey Rest Service not working using Json annotaion - java

I have the following classes:
ServerStartup.java
import java.io.IOException;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.net.httpserver.HttpServer;
public class ServerStartUp {
static final String BASE_URI = "http://localhost:9999/";
public static void main(String[] args) {
try {
final ResourceConfig rc = new PackagesResourceConfig("com.twins.engine");
rc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
HttpServer server = HttpServerFactory.create(BASE_URI,rc);
server.setExecutor(null);
server.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and the following class SysInfo.Java
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.twins.engine.model.SysInfo;
#Path("/Sys")
public class General {
#GET
#Path("/info")
#Produces(MediaType.APPLICATION_JSON)
public SysInfo getInfo(){
SysInfo info = new SysInfo("Monetoring 365");
return info;
}
}
and the following model class SysInfo.java
public class SysInfo {
private String name;
public SysInfo(String name) {
this.setName(name);
}
public String getName() {return name;}
public void setName(String name) {this.name = name; }
}
When i run the serverStartup class and Navigate to the following url:
http://127.0.0.1:9999/sys/info
i got the following exception:
Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class com.twins.engine.model.SysInfo, and Java type class com.twins.engine.model.SysInfo, and MIME media type text/html was not found
... 15 more
enter image description hereas well i have the following Jars attached as image, is there any missing configuration i have to do

Try following
final ResourceConfig rc = new PackagesResourceConfig("com.twins.engine");
final Map<String, Object> config = new HashMap<String, Object>();
config.put("com.sun.jersey.api.json.POJOMappingFeature", true);
rc.setPropertiesAndFeatures(config);
HttpServer server = HttpServerFactory.create(BASE_URI,rc);
server.setExecutor(null);
server.start();
and probably you have to add jackson-mapper
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.12</version>
</dependency>

Related

Can't get Active Objects to work in Jira

I am currently doing an internship that involves creating Jira plugins to solve some problems the users at the company experience with Jira. For the first extension I need to create a new section on the view issue page where users can put input and edit the input. In order to do this I've created a web-panel which contains a input. But no matter what I try (And I've been trying different things for the last 3 weeks) I can't get active objects to work.
Currently the moment the plugin tries to load in jira it shows the error: "Error rendering 'tig.jira.extension.tigPasswordExtension:issue-page-input'. Please contact your JIRA administrators." and when I try to test the REST API call in the restbrowser it shows the error:
""message": "AOP configuration seems to be invalid: tried calling method [public abstract net.java.ao.RawEntity[] com.atlassian.activeobjects.external.ActiveObjects.find(java.lang.Class,net.java.ao.Query)] on target [com.atlassian.activeobjects.osgi.TenantAwareActiveObjects#12bfb51b]; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class",
_ "status-code": 500,"_
Is there anyone here that can replicate my problem and pinpoint what I am screwing up?
My current files are as follows:
Atlassian-plugin.xml
<atlassian-plugin key="${atlassian.plugin.key}" name="${project.name}" plugins-version="2">
<plugin-info>
<description>${project.description}</description>
<version>${project.version}</version>
<vendor name="${project.organization.name}" url="${project.organization.url}"/>
<param name="plugin-icon">images/pluginIcon.png</param>
<param name="plugin-logo">images/pluginLogo.png</param>
</plugin-info>
<!-- add our i18n resource -->
<resource type="i18n" name="i18n" location="tigPasswordExtension"/>
<!-- add our web resources -->
<web-resource key="tigPasswordExtension-resources" name="tigPasswordExtension Web Resources">
<dependency>com.atlassian.auiplugin:ajs</dependency>
<resource type="download" name="tigPasswordExtension.css" location="/css/tigPasswordExtension.css"/>
<resource type="download" name="tigPasswordExtension.js" location="/js/tigPasswordExtension.js"/>
<resource type="download" name="images/" location="/images"/>
<context>tigPasswordExtension.resource</context>
</web-resource>
<web-panel name="IssuePageInput" i18n-name-key="issue-page-input.name" key="issue-page-input" location="atl.jira.view.issue.right.context" weight="1">
<description key="issue-page-input.description">Passwords en SSH</description>
<context-provider class="tig.jira.extension.tigPasswordExtension.PasswordContextProvider"/>
<component-import key="appProps" interface="com.atlassian.sal.api.ApplicationProperties"/>
<resource name="view" type="velocity" location="/vm/password-input.vm"/>
<label key="issue-page-input.title"/>
</web-panel>
<!-- Active Objects module -->
<ao key="password-ao">
<description>The configuration of the Active Objects service</description>
<entity>tig.jira.extension.tigPasswordExtension.ao.PasswordModel</entity>
</ao>
<rest name="Password Resource" i18n-name-key="password-resource.name" key="password-resource" path="/passwordresource" version="1.0">
<description key="password-resource.description">The Password Resource Plugin</description>
</rest>
</atlassian-plugin>
tigPasswordExtension.js
AJS.toInit(function($) {
AJS.$('#searchButton2').click(function (){
var test = "lol";
AJS.$.ajax({
url:"jira/rest/passwordresource/1.0/password",
type: "post",
dataType: 'json',
async: false,
data: ({issueKey : document.getElementById("issueKeyInput").value, content: document.getElementById("passwordInput").value}),
success: function(data)
{
test = data;
console.log(test);
}
})
});
});
PasswordDto
package tig.jira.extension.tigPasswordExtension.dto;
public class PasswordDto {
private String issueKey;
private String content;
public PasswordDto(){}
public String getIssueKey(){return this.issueKey;}
public void setIssueKey(String issueKey){this.issueKey = issueKey;}
public String getContent(){return this.content;}
public void setContent(String content){this.content = content;}
}
PasswordModel
package tig.jira.extension.tigPasswordExtension.ao;
import net.java.ao.Entity;
import net.java.ao.Preload;
#Preload
public interface PasswordModel extends Entity {
String getIssue();
void setIssue(String issue);
String getContent();
void setContent(String content);
}
PasswordDao
package tig.jira.extension.tigPasswordExtension.ao;
import com.atlassian.activeobjects.external.ActiveObjects;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import com.google.common.collect.ImmutableMap.Builder;
import net.java.ao.Query;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.Map;
#Named
public class PasswordDao {
private final ActiveObjects activeObjects;
#Inject
public PasswordDao(#ComponentImport ActiveObjects activeObjects){this.activeObjects = activeObjects;}
public PasswordModel getByIssueKey(String issueKey){
Query query = this.buildIssueQuery(issueKey);
PasswordModel[] passwordModels = this.activeObjects.find(PasswordModel.class, query);
return passwordModels.length > 0 ? passwordModels[0] : null;
}
public void update(String issueKey, String content){
PasswordModel passwordModel = this.getByIssueKey(issueKey);
if (passwordModel == null){
Map<String, Object> params = (new Builder()).put("ISSUE_KEY", issueKey).put("CONTENT", content).build();
this.activeObjects.create(PasswordModel.class, params);
} else {
passwordModel.setContent(content);
passwordModel.save();
}
}
private Query buildIssueQuery(String issueKey){
return Query.select().where("ISSUE_KEY = ?", issueKey);
}
}
PasswordResource
package tig.jira.extension.tigPasswordExtension.rest;
import tig.jira.extension.tigPasswordExtension.service.PasswordService;
import javax.ws.rs.*;
#Path("/password")
public class PasswordResource{
private final PasswordService passwordService;
public PasswordResource(PasswordService passwordService){this.passwordService = passwordService;}
#POST
public void update(#QueryParam("issue") String issueKey, #QueryParam("content") String content) {
this.passwordService.update(issueKey, content);
}
}
PasswordService
package tig.jira.extension.tigPasswordExtension.service;
import tig.jira.extension.tigPasswordExtension.ao.PasswordDao;
import tig.jira.extension.tigPasswordExtension.ao.PasswordModel;
import tig.jira.extension.tigPasswordExtension.dto.PasswordDto;
import javax.inject.Inject;
import javax.inject.Named;
#Named
public class PasswordService {
private final PasswordDao passwordDao;
#Inject
public PasswordService(PasswordDao passwordDao){
this.passwordDao = passwordDao;
}
public void update(String issueKey, String content){
this.passwordDao.update(issueKey, content);
}
public PasswordDto getByIssueKey(String issueKey){
PasswordModel passwordModel = this.passwordDao.getByIssueKey(issueKey);
if (passwordModel == null){
return null;
} else {
PasswordDto dto = new PasswordDto();
dto.setIssueKey(issueKey);
dto.setContent(passwordModel.getContent());
return dto;
}
}
}
PasswordContextProvider
package tig.jira.extension.tigPasswordExtension;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.plugin.webfragment.contextproviders.AbstractJiraContextProvider;
import com.atlassian.jira.plugin.webfragment.model.JiraHelper;
import com.atlassian.jira.user.ApplicationUser;
import tig.jira.extension.tigPasswordExtension.dto.PasswordDto;
import tig.jira.extension.tigPasswordExtension.service.PasswordService;
import java.util.HashMap;
import java.util.Map;
public class PasswordContextProvider extends AbstractJiraContextProvider {
Map contextMap = new HashMap();
private String issueKey;
private final PasswordService passwordService;
public PasswordContextProvider(PasswordService passwordRepository){
this.passwordService = passwordRepository;
}
public Map getContextMap(ApplicationUser user, JiraHelper jiraHelper) {
Issue currentIssue = (Issue) jiraHelper.getContextParams().get("issue");
issueKey = currentIssue.getKey();
//passwordService.update(issueKey, "klote");
PasswordDto passwordDto = this.passwordService.getByIssueKey(issueKey);
if (passwordDto != null){
contextMap.put("AO", "1");
contextMap.put("content", "Staat nog niks in gek");
if (passwordDto.getContent() != null) {
contextMap.put("content", passwordDto.getContent());
}
}
contextMap.put("issueKey", issueKey);
return contextMap;
}
}
The only problem I could find after a quick look is in the class PasswordDao. If I replace the variable query by it's value then it will look like below.
activeObjects.find(PasswordModel.class, Query.select().where("ISSUE_KEY = ?", issueKey));
Whereas your entity class PasswordModel.java does not have any such method String xxxIssueKey(). Refer Offical document for column name of table created using ActiveObjects.
Best practice documentation can be a good start for you when working with Active Objects.
Update the method as given below (change ISSUE_KEY to ISSUE).
private Query buildIssueQuery(String issueKey){
return Query.select().where(" ISSUE = ? ", issueKey);
}
I hope this helps you.

NoSuchMethodError using dropwizard websocket jee7 bundle server

I'm using Dropwizard for a REST server and dropwizard-websocket-jee7-bundle to enable websockets.
For the websocket server I used this example.
Testing the websocket server standalone works fine, but in combination with Dropwizard, when a client tries to connect (to ws://localhost:port/actions) it gets a 500 Internal Server Error (Error log below).
I'm guessing there is some bad or missing configuration, but I can't figure our where.
ServerExample:
package com.example;
import static org.eclipse.jetty.servlets.CrossOriginFilter.ALLOWED_HEADERS_PARAM;
import static org.eclipse.jetty.servlets.CrossOriginFilter.ALLOWED_METHODS_PARAM;
import static org.eclipse.jetty.servlets.CrossOriginFilter.ALLOWED_ORIGINS_PARAM;
import static org.eclipse.jetty.servlets.CrossOriginFilter.ALLOW_CREDENTIALS_PARAM;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import com.example.health.SearchHealthCheck;
import com.example.resources.TestFind;
import be.tomcools.dropwizard.websocket.WebsocketBundle;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import com.example.websocket.DeviceWebSocketServer;
public class ServerExample extends Application<ServerExampleConfiguration> {
private WebsocketBundle websocket = new WebsocketBundle();
public static void main(String[] args) throws Exception {
new ServerExample().run(args);
}
#Override
public String getName() {
return "com.example";
}
#Override
public void initialize(Bootstrap<ServerExampleConfiguration> bootstrap) {
super.initialize(bootstrap);
bootstrap.addBundle(websocket);
}
#Override
public void run(ServerExampleConfiguration configuration, Environment environment) throws Exception {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORSFilter", CrossOriginFilter.class);
filter.setInitParameter(ALLOWED_METHODS_PARAM, "OPTIONS,POST,GET");
filter.setInitParameter(ALLOWED_ORIGINS_PARAM, "*");
filter.setInitParameter(ALLOWED_HEADERS_PARAM, "Origin,Content-Type,Accept,X-Requested-With");
filter.setInitParameter(ALLOW_CREDENTIALS_PARAM, "true");
filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
environment.jersey().register(new TestFind());
environment.healthChecks().register("search", new SearchHealthCheck());
//Annotated endpoint
websocket.addEndpoint(DeviceWebSocketServer.class);
}
}
DeviceWebSocketServer:
package com.example.websocket;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.io.StringReader;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import com.example.model.Device;
import java.util.logging.Level;
import java.util.logging.Logger;
#ApplicationScoped
#ServerEndpoint("/actions")
public class DeviceWebSocketServer {
#Inject
private DeviceSessionHandler sessionHandler;
#OnOpen
public void open(Session session) {
sessionHandler.addSession(session);
}
#OnClose
public void close(Session session) {
sessionHandler.removeSession(session);
}
#OnError
public void onError(Throwable error) {
Logger.getLogger(DeviceWebSocketServer.class.getName()).log(Level.SEVERE, null, error);
}
#OnMessage
public void handleMessage(String message, Session session) {
try (JsonReader reader = Json.createReader(new StringReader(message))) {
JsonObject jsonMessage = reader.readObject();
if ("add".equals(jsonMessage.getString("action"))) {
Device device = new Device();
device.setName(jsonMessage.getString("name"));
device.setDescription(jsonMessage.getString("description"));
device.setType(jsonMessage.getString("type"));
device.setStatus("Off");
sessionHandler.addDevice(device);
}
if ("remove".equals(jsonMessage.getString("action"))) {
int id = (int) jsonMessage.getInt("id");
sessionHandler.removeDevice(id);
}
if ("toggle".equals(jsonMessage.getString("action"))) {
int id = (int) jsonMessage.getInt("id");
sessionHandler.toggleDevice(id);
}
}
}
}
DeviceSessionHandler:
package com.example.websocket;
import javax.enterprise.context.ApplicationScoped;
import javax.json.JsonObject;
import javax.json.spi.JsonProvider;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.Session;
import com.example.model.Device;
#ApplicationScoped
public class DeviceSessionHandler {
private int deviceId = 0;
private final Set<Session> sessions = new HashSet<>();
private final Set<Device> devices = new HashSet<>();
public void addSession(Session session) {
sessions.add(session);
for (Device device : devices) {
JsonObject addMessage = createAddMessage(device);
sendToSession(session, addMessage);
}
}
public void removeSession(Session session) {
sessions.remove(session);
}
public List<Device> getDevices() {
return new ArrayList<>(devices);
}
public void addDevice(Device device) {
device.setId(deviceId);
devices.add(device);
deviceId++;
JsonObject addMessage = createAddMessage(device);
sendToAllConnectedSessions(addMessage);
}
public void removeDevice(int id) {
Device device = getDeviceById(id);
if (device != null) {
devices.remove(device);
JsonProvider provider = JsonProvider.provider();
JsonObject removeMessage = provider.createObjectBuilder()
.add("action", "remove")
.add("id", id)
.build();
sendToAllConnectedSessions(removeMessage);
}
}
public void toggleDevice(int id) {
JsonProvider provider = JsonProvider.provider();
Device device = getDeviceById(id);
if (device != null) {
if ("On".equals(device.getStatus())) {
device.setStatus("Off");
} else {
device.setStatus("On");
}
JsonObject updateDevMessage = provider.createObjectBuilder()
.add("action", "toggle")
.add("id", device.getId())
.add("status", device.getStatus())
.build();
sendToAllConnectedSessions(updateDevMessage);
}
}
private Device getDeviceById(int id) {
for (Device device : devices) {
if (device.getId() == id) {
return device;
}
}
return null;
}
private JsonObject createAddMessage(Device device) {
JsonProvider provider = JsonProvider.provider();
JsonObject addMessage = provider.createObjectBuilder()
.add("action", "add")
.add("id", device.getId())
.add("name", device.getName())
.add("type", device.getType())
.add("status", device.getStatus())
.add("description", device.getDescription())
.build();
return addMessage;
}
private void sendToAllConnectedSessions(JsonObject message) {
for (Session session : sessions) {
sendToSession(session, message);
}
}
private void sendToSession(Session session, JsonObject message) {
try {
session.getBasicRemote().sendText(message.toString());
} catch (IOException ex) {
sessions.remove(session);
Logger.getLogger(DeviceSessionHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Dependencies:
<dependencies>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.7</version>
</dependency>
<dependency>
<groupId>org.apache.jena</groupId>
<artifactId>jena-arq</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-core</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.8</version>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1</version>
</dependency><dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>be.tomcools</groupId>
<artifactId>dropwizard-websocket-jee7-bundle</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
Error Log:
WARN [2017-08-31 16:55:46,863] org.eclipse.jetty.servlet.ServletHandler: Error for /actions
! java.lang.NoSuchMethodError: org.eclipse.jetty.io.AbstractConnection.<init>(Lorg/eclipse/jetty/io/EndPoint;Ljava/util/concurrent/Executor;Z)V
! at org.eclipse.jetty.websocket.common.io.AbstractWebSocketConnection.<init>(AbstractWebSocketConnection.java:225)
! at org.eclipse.jetty.websocket.server.WebSocketServerConnection.<init>(WebSocketServerConnection.java:41)
! at org.eclipse.jetty.websocket.server.WebSocketServerFactory.upgrade(WebSocketServerFactory.java:520)
! at org.eclipse.jetty.websocket.server.WebSocketServerFactory.acceptWebSocket(WebSocketServerFactory.java:186)
! at org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter.doFilter(WebSocketUpgradeFilter.java:206)
! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
! at io.dropwizard.servlets.ThreadNameFilter.doFilter(ThreadNameFilter.java:34)
! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
! at io.dropwizard.jersey.filter.AllowedMethodsFilter.handle(AllowedMethodsFilter.java:50)
! at io.dropwizard.jersey.filter.AllowedMethodsFilter.doFilter(AllowedMethodsFilter.java:44)
! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
! at org.eclipse.jetty.servlets.CrossOriginFilter.handle(CrossOriginFilter.java:308)
! at org.eclipse.jetty.servlets.CrossOriginFilter.doFilter(CrossOriginFilter.java:262)
! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
! at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581)
! at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1174)
! at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
! at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1106)
! at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
! at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
! at com.codahale.metrics.jetty9.InstrumentedHandler.handle(InstrumentedHandler.java:240)
! at io.dropwizard.jetty.RoutingHandler.handle(RoutingHandler.java:51)
! at org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:459)
! at io.dropwizard.jetty.BiDiGzipHandler.handle(BiDiGzipHandler.java:68)
! at org.eclipse.jetty.server.handler.RequestLogHandler.handle(RequestLogHandler.java:56)
! at org.eclipse.jetty.server.handler.StatisticsHandler.handle(StatisticsHandler.java:169)
! at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
! at org.eclipse.jetty.server.Server.handle(Server.java:524)
! at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:319)
! at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:253)
! at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
! at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
! at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
! at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
! at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
! at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
! at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
! at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
! at java.lang.Thread.run(Thread.java:745)
0:0:0:0:0:0:0:1 - - [31/ago/2017:16:55:46 +0000] "GET /actions HTTP/1.1" 500 245 "-" "-" 47
Edited: Added dependencies list.
Downgraded the dropwizard version I was using to the last reported version in the bundle (0.9.1) and this error is gone (although i have a null pointer exception now. will open a new question about that error).

Capturing LOGIN COOKIE via Rest Template

I have below code for making a POST call to RestAPI for Tableau system, which is working and seeing response output.
However, I would like to capture cookie from this output and need to be used for further consumption! Can somebody help me on this problem?
Code:
package com.abc.it.automation.service;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Properties;
import org.springframework.http.HttpHeaders;
import org.springframework.http.RequestEntity.HeadersBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
import com.abc.it.automation.utils.SSLUtil;
public class BIaaSTableauService {
private static Properties tableau_properties = new Properties();
static {
// Loads the values from configuration file into the Properties instance
try {
tableau_properties.load(new FileInputStream("res/config.properties"));
} catch (IOException e) {
System.out.println(e);
}
}
private static final String loginURL = tableau_properties.getProperty("server.host");
private static final String siteSearchURL = tableau_properties.getProperty("site.search.url");
public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException {
RestTemplate restTableau = new RestTemplate();
String requestLogin = "<tsRequest>"+
"<credentials name=\"svc_tableau\" password=\"xxxxxxxxx\" >"+
"<site contentUrl=\"\"/>"+
"</credentials>"+
"</tsRequest>";
SSLUtil.turnOffSslChecking();
ResponseEntity<String> responseLogin = restTableau.postForEntity(loginURL, requestLogin, String.class);
System.out.println(responseLogin.getBody());
You need to build your RestTemplate as follows.
RestTemplate restTableau = new RestTemplate(new MyClientHttpRequestFactory());
Extend ClientHttpRequestFactory as follows.
public class MyClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
private Cookie cookie;
//setters and getters.
#Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
this.setCookie(connection.getRequestProperty("Cookie"));
}
}

How to configure embedded jetty to access Jersey resources?

I'm trying to configure embedded jetty to talk to my Jersey resources but I can't figure out how to do it. I've tried a couple of different things but nothing seems to work. The jetty tutorials don't really handle how to do it with Jersey. Any code suggestions or links are greatly appreciated
EDIT:
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;
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);
}
Trying to connect to this class:
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);
}
}
You're mixing 2 versions of Jersey in your code together - ServletContainer from Jersey 2.x (package org.glassfish.jersey.*) and properties from Jersey 1.x (package/prefix com.sun.jersey.*).
To deploy your app using Jersey 2.x change these two lines
h.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
h.setInitParameter("com.sun.jersey.config.property.packages", "resources");
from your main method to
h.setInitParameter(ServerProperties.PROVIDER_PACKAGES, "resources");
and check the other ServerProperties you may find useful.

Grizzly and ServletContainerContext

I'm trying to get hold of some injected context (for example Session or HttpServletRequest) in a Servlet I've written, running on Grizzly, but nothing I do seems to work. The whole process seems to stall rather prematurely with the following error:
SEVERE: Missing dependency for field: javax.servlet.http.HttpServletRequest com.test.server.LolCat.hsr
The server is dead simple, it consists of two files, the static entry point (Main.java):
package com.test.server;
import java.io.IOException;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.grizzly.http.server.HttpServer;
import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.ClassNamesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
public class Main {
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost/").port(8080).build();
}
public static final URI BASE_URI = getBaseURI();
public static void main(String[] args) throws IOException {
ResourceConfig rc = new ClassNamesResourceConfig(LolCat.class);
HttpServer httpServer = GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
System.in.read();
httpServer.stop();
}
}
and the serlvet (LolCat.java):
package com.test.server;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
#Path(value = "/lol")
public class LolCat {
#Context HttpServletRequest hsr;
#GET
#Path(value="/cat")
public String list() {
return "meow";
}
}
Specifically, it's the #Context-line in the above source file that is the source and solution to all my problems. I need it, and according to everything I've read about Jersey and Servlets it should work, but alas it does not. I've also tried using GrizzlyWebContainerFactory instead of the GrizzlyServerFactory, but to no avail.
For reference, the project is compiled with the following dependencies:
org.glassfish.grizzly:grizzly-framework:jar:2.2.21
org.glassfish.grizzly:grizzly-http:jar:2.2.21
org.glassfish.grizzly:grizzly-http-servlet:jar:2.2.21
org.glassfish.grizzly:grizzly-http-server:jar:2.2.21
com.sun.jersey:jersey-server:jar:1.17
com.sun.jersey:jersey-servlet:jar:1.17
com.sun.jersey:jersey-core:jar:1.17
javax.servlet:javax.servlet-api:jar:2.5.0
com.sun.jersey:jersey-grizzly2:jar:1.17
com.sun.jersey:jersey-grizzly2-servlet:jar:1.17
asm:asm:jar:3.3.1
This Main class works fine for me:
package com.test.server;
import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import java.io.IOException;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.core.ClassNamesResourceConfig;
import com.sun.jersey.spi.container.servlet.ServletContainer;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;
import org.glassfish.grizzly.servlet.ServletRegistration;
import org.glassfish.grizzly.servlet.WebappContext;
public class Main {
private static final String JERSEY_SERVLET_CONTEXT_PATH = "";
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost").port(8080).path("/").build();
}
public static final URI BASE_URI = getBaseURI();
public static void main(String[] args) throws IOException {
// Create HttpServer and register dummy "not found" HttpHandler
HttpServer httpServer = GrizzlyServerFactory.createHttpServer(BASE_URI, new HttpHandler() {
#Override
public void service(Request rqst, Response rspns) throws Exception {
rspns.setStatus(404, "Not found");
rspns.getWriter().write("404: not found");
}
});
// Initialize and register Jersey Servlet
WebappContext context = new WebappContext("WebappContext", JERSEY_SERVLET_CONTEXT_PATH);
ServletRegistration registration = context.addServlet("ServletContainer", ServletContainer.class);
registration.setInitParameter(ServletContainer.RESOURCE_CONFIG_CLASS,
ClassNamesResourceConfig.class.getName());
registration.setInitParameter(ClassNamesResourceConfig.PROPERTY_CLASSNAMES, LolCat.class.getName());
registration.addMapping("/*");
context.deploy(httpServer);
System.in.read();
httpServer.stop();
}
}
Try http://localhost:8080/lol/cat in your browser.
You can change JERSEY_SERVLET_CONTEXT_PATH to update Servlet's context-path.
As per developers explanations - Grizzly is not fully compliant to JAX-RS 2.0 so there will be no official contexts injections/wrapping. See Jersey Bug-1960
Applicable for Jersey + Grizzly version 2.7+
Luckily there is a way to inject Grizzly request/response objects. Kind of tricky but works
Code sample provided in one of Jersey's unit tests. See Jersey container test
So code fragment will be:
import javax.inject.Inject;
import javax.inject.Provider;
public someclass {
#Inject
private Provider<Request> grizzlyRequestProvider;
public void method() {
if (grizzlyRequestProvider != null) {
Request httpRequest = grizzlyRequestProvider.get();
// Extract what you need
}
}
}
Works fine both for filters and service methods
You can also manually register a ResourceContext
HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(getBaseURI());
WebappContext context = new WebappContext("WebappContext", "/api");
ServletRegistration registration = context.addServlet("ServletContainer",
new ServletContainer(config));
registration.addMapping("/*");
context.deploy(httpServer);
Where config is your resource context.
Try something like this :-
public class Main {
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost/").port(8080).build();
}
public static void main(String[] args) throws IOException {
ResourceConfig rc = new ResourceConfig().packages("com.example");//path to you class files
HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc);
System.in.read();
httpServer.stop();
}
}

Categories

Resources