I got the following DTO Object
public class ToManyAssociationModel<T> implements Serializable {
private DualListModel<String> assigned;
...
public ToManyAssociationModel() {
...
source.add("FOO");
source.add("BAR");
...
assigned = new DualListModel<String>(source,target
);
}
}
My frontend looks like this:
<p:pickList id="pickList" value="#{benutzerkontoModel.availableBenutzergruppen}" var="cities" itemLabel="#{cities}" itemValue="#{cities}" />
and the BenutzerkontoModel looks like this:
public BenutzerkontoDTO(Benutzerkonto benutzerkonto, ToManyAssociationModel<Long> benutzergruppen) {
assert benutzerkonto != null : "benutzerkonto must not be null";
assert benutzergruppen != null : "benutzergruppen must not be null";
this.benutzerkonto = benutzerkonto;
this.benutzergruppen = benutzergruppen;
}
However I get the following error:
java.lang.ClassCastException: cannot assign instance of org.primefaces.model.DualListModel to field de.db.udg.diagnose.udgdiag.domain.base.ToManyAssociationModel.assigned of type org.primefaces.model.DualListModel in instance of de.db.udg.diagnose.udgdiag.domain.base.ToManyAssociationModel
Domain POM (where ToManyAssociationModel is nested): (only relevant parts)
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
WAR POM: (only relevant parts)
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>7.0</version>
<scope>compile</scope>
</dependency>
<!-- PrimeFaces File Upload utils -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
<scope>compile</scope>
</dependency>
Related
I would like to simulate a request submission using Postman. I am not sure what to put in Postman for my request if I have a HttpServletRequest in input to my method.
This is my Controller:
#RestController
public class MyController {
#PostMapping(path = "/test")
public ResponseEntity<String> test(HttpServletRequest request) {
final String host=request.getRemoteAddr();
final String key = request.getParameter("key");
final String application = request.getParameter("nomeApp");
...
}
My understanding is that when a HttpServletRequest object is in input to a method in Rest Controller class, I don't have to pass parameters because in someway the request is processed itself.
My Postman
This is my exception:
java.lang.IllegalStateException: No primary or single unique constructor found for interface javax.servlet.http.HttpServletRequest
at org.springframework.beans.BeanUtils.getResolvableConstructor(BeanUtils.java:266) ~[spring-beans-6.0.4.jar:6.0.4]
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:219) ~[spring-web-6.0.4.jar:6.0.4]
These are the dependencies used in my POM
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
<!-- Excluded commons-io because of CVE-2021-29425 -->
<exclusions>
<exclusion>
<artifactId>commons-io</artifactId>
<groupId>commons-io</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
Try using ServerHttpRequest instead of HttpServletRequest. ServerHttpRequest is the implementation class of HttpServletRequest.
#RestController
public class MyController {
#PostMapping(path = "/test")
public ResponseEntity<String> test(ServerHttpRequest request) {
final String host=request.getRemoteAddr();
final String key = request.getParameter("key");
final String application = request.getParameter("nomeApp");
...
}
I am developing an azure function app. function in azure function app is responsible to receive messages from azure event hub. this method should should update azure digital twin. I am creating Azure DigitalTwin instance like below
#FunctionName("eventGridMonitorString")
public void eventHubProcessor(
#EventHubTrigger(name = "msg", eventHubName = "", connection = "EventHubConnectionString") String message,
final ExecutionContext context) {
// context.getLogger().info(message);
String adtUrl = System.getenv("ADT_SERVICE_URL");
context.getLogger().info("ADTURl : " + adtUrl);
DigitalTwinsClient client = new DigitalTwinsClientBuilder().credential(new ClientSecretCredentialBuilder()
.tenantId("my_tenant_id").clientId("my_client_id")
.clientSecret("my_client_secret").build()).endpoint(adtUrl).buildClient();
Iterable<DigitalTwinsModelData> modelList = client.listModels();
Iterator<DigitalTwinsModelData> it = modelList.iterator();
while (it.hasNext()) {
DigitalTwinsModelData model = it.next();
context.getLogger().info("" + model.getDtdlModel());
}
for (DigitalTwinsModelData model : modelList) {
context.getLogger().info("Created model: " + model.getModelId());
}
}
This code works fine in my local java application but when I deploy this code to azure function app, it gives me below error
2021-05-27T07:42:35.173 [Error] Executed 'Functions.eventGridMonitorString' (Failed, Id=12a87102-78a3-4e2e-8715-b4401091d753, Duration=116ms)Result: FailureException: NoClassDefFoundError: Could not initialize class reactor.netty.http.client.HttpClientConfigStack: java.lang.reflect.InvocationTargetExceptionat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:498)at com.microsoft.azure.functions.worker.broker.JavaMethodInvokeInfo.invoke(JavaMethodInvokeInfo.java:22)at com.microsoft.azure.functions.worker.broker.JavaMethodExecutorImpl.execute(JavaMethodExecutorImpl.java:54)at com.microsoft.azure.functions.worker.broker.JavaFunctionBroker.invokeMethod(JavaFunctionBroker.java:57)at com.microsoft.azure.functions.worker.handler.InvocationRequestHandler.execute(InvocationRequestHandler.java:33)at com.microsoft.azure.functions.worker.handler.InvocationRequestHandler.execute(InvocationRequestHandler.java:10)at com.microsoft.azure.functions.worker.handler.MessageHandler.handle(MessageHandler.java:45)at com.microsoft.azure.functions.worker.JavaWorkerClient$StreamingMessagePeer.lambda$onNext$0(JavaWorkerClient.java:92)at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)at java.util.concurrent.FutureTask.run(FutureTask.java:266)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)at java.lang.Thread.run(Thread.java:748)Caused by: java.lang.NoClassDefFoundError: Could not initialize class reactor.netty.http.client.HttpClientConfigat reactor.netty.http.client.HttpClientConnect.<init>(HttpClientConnect.java:84)at reactor.netty.http.client.HttpClient.create(HttpClient.java:393)at com.azure.core.http.netty.NettyAsyncHttpClientBuilder.build(NettyAsyncHttpClientBuilder.java:91)at com.azure.core.http.netty.implementation.ReactorNettyClientProvider.createInstance(ReactorNettyClientProvider.java:14)at com.azure.core.implementation.http.HttpClientProviders.createInstance(HttpClientProviders.java:58)at com.azure.core.http.HttpClient.createDefault(HttpClient.java:50)at com.azure.core.http.HttpClient.createDefault(HttpClient.java:40)at com.azure.core.http.HttpPipelineBuilder.build(HttpPipelineBuilder.java:62)at com.azure.digitaltwins.core.DigitalTwinsClientBuilder.buildPipeline(DigitalTwinsClientBuilder.java:151)at com.azure.digitaltwins.core.DigitalTwinsClientBuilder.buildAsyncClient(DigitalTwinsClientBuilder.java:193)at com.azure.digitaltwins.core.DigitalTwinsClientBuilder.buildClient(DigitalTwinsClientBuilder.java:160)at com.ey.azurefunctions.PolarDelightFunctionApp.Function.eventHubProcessor(Function.java:32)... 16 more
am I missing something or is there any issue with above code?
Edit 1 I have below maven dependencies added to my project
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-digitaltwins-core</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core-http-netty</artifactId>
<version>1.7.1</version> <!-- {x-version-update;com.azure:azure-core-http-netty;dependency} -->
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.49.Final</version>
</dependency>
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty</artifactId>
<version>1.0.7</version>
</dependency>
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty-http</artifactId>
<version>1.0.7</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-bom</artifactId>
<version>Dysprosium-SR20</version>
<type>pom</type>
</dependency>
This question already has answers here:
Resolving dependency problems in Apache Spark
(7 answers)
Closed 4 years ago.
I have this small piece of java code to get apache spark recommendations:
public class Main {
public static class Rating implements Serializable {
private int userId;
private int movieId;
private float rating;
private long timestamp;
public Rating() {}
public Rating(int userId, int movieId, float rating, long timestamp) {
this.userId = userId;
this.movieId = movieId;
this.rating = rating;
this.timestamp = timestamp;
}
public int getUserId() {
return userId;
}
public int getMovieId() {
return movieId;
}
public float getRating() {
return rating;
}
public long getTimestamp() {
return timestamp;
}
public static Rating parseRating(String str) {
String[] fields = str.split(",");
if (fields.length != 4) {
throw new IllegalArgumentException("Each line must contain 4 fields");
}
int userId = Integer.parseInt(fields[0]);
int movieId = Integer.parseInt(fields[1]);
float rating = Float.parseFloat(fields[2]);
long timestamp = Long.parseLong(fields[3]);
return new Rating(userId, movieId, rating, timestamp);
}
}
static String parse(String str) {
Pattern pat = Pattern.compile("\\[[0-9.]*,[0-9.]*]");
Matcher matcher = pat.matcher(str);
int count = 0;
StringBuilder sb = new StringBuilder();
while (matcher.find()) {
count++;
String substring = str.substring(matcher.start(), matcher.end());
String itstr = substring.split(",")[0].substring(1);
sb.append(itstr + " ");
}
return sb.toString().trim();
}
static TreeMap<Long, String> res = new TreeMap<>();
public static void add(long k, String v) {
res.put(k, v);
}
public static void main(String[] args) throws IOException {
Logger.getLogger("org").setLevel(Level.OFF);
Logger.getLogger("akka").setLevel(Level.OFF);
SparkSession spark = SparkSession
.builder()
.appName("SomeAppName")
.config("spark.master", "local")
.getOrCreate();
JavaRDD<Rating> ratingsRDD = spark
.read().textFile(args[0]).javaRDD()
.map(Rating::parseRating);
Dataset<Row> ratings = spark.createDataFrame(ratingsRDD, Rating.class);
ALS als = new ALS()
.setMaxIter(1)
.setRegParam(0.01)
.setUserCol("userId")
.setItemCol("movieId")
.setRatingCol("rating");
ALSModel model = als.fit(ratings);
model.setColdStartStrategy("drop");
Dataset<Row> rowDataset = model.recommendForAllUsers(50);
rowDataset.foreach((ForeachFunction<Row>) row -> {
String str = row.toString();
long l = Long.parseLong(str.substring(1).split(",")[0]);
add(l, parse(str));
});
BufferedWriter bw = new BufferedWriter(new FileWriter(args[1]));
for (long l = 0; l < res.lastKey(); l++) {
if (!res.containsKey(l)) {
bw.write("\n");
continue;
}
String str = res.get(l);
bw.write(str);
}
bw.close();
}
}
I am trying different dependencies in my pom.xml to get it running, but all variants fail. This one:
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-core</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-mllib_2.12</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
fails with java.lang.ClassNotFoundException: text.DefaultSource, to fix it I add
org.apache.spark
spark-sql-kafka-0-10_2.10
2.0.2
now it crashes with ClassNotFoundException: org.apache.spark.internal.Logging$class, to fix it I add another ones:
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming_2.11</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.10</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.10</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming-kafka-0-8_2.11</artifactId>
<version>2.2.2</version>
</dependency>
now it fails with java.lang.NoClassDefFoundError: scala/collection/GenTraversableOnce to fix it I tried dozen of other combinations, all of them failed, the last one is
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming_2.11</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-mllib_2.11</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming-kafka-0-8_2.11</artifactId>
<version>2.2.2</version>
</dependency>
which again gives me ClassNotFoundException: text.DefaultSource, how can I fix it? Was there any logic behind implementing runtime linking in spark?
UPD: also tried
<dependencies>
<dependency> <!-- Spark dependency -->
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.0.1</version>
</dependency>
<dependency> <!-- Spark dependency -->
<groupId>org.apache.spark</groupId>
<artifactId>spark-mllib_2.11</artifactId>
<version>2.0.1</version>
</dependency>
<dependency> <!-- Spark dependency -->
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming_2.11</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.bahir</groupId>
<artifactId>spark-streaming-twitter_2.11</artifactId>
<version>2.0.1</version>
</dependency>
</dependencies>
(this still gives me java.lang.ClassNotFoundException: text.DefaultSource))
I also tried dependencies published in this question, but they also fail: Resolving dependency problems in Apache Spark
Source code is available here, so you can try various maven settings yourself: https://github.com/stiv-yakovenko/sparkrec
Finally I was able to make it work:
<dependencies>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-mllib_2.11</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.11.8</version>
</dependency>
</dependencies>
You have to use these exact versions otherwise it will crash in multiple various ways.
I am serializing a POJO into either JSON and XML depending on the Accept header.
#Path("/json/metallica")
public class JSONService{
#POST
#Path("/post")
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getTrackInJSON() {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
return Response.status(201).entity(track).build();
}
}
I want to have the name of the XML tag changed along with the JSON key name, i have used #XmlElement for this as it seemed to work with both XML and JSON.
Looking at the POJO class I want serialized into XML and JSON, the problem is that #XmlElement doesn't always work when serializing into JSON after redeploying the .war in Tomcat. Half the time it puts the name declared in #XmlElement(name = ""), and the other half it keeps the name of the field.
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Track {
private String title;
private String singer;
public String getTitle() {
return title;
}
#XmlElement(name = "title_element")
public void setTitle(String title) {
this.title = title;
}
public String getSinger() {
return singer;
}
#XmlElement(name = "singer_element")
public void setSinger(String singer) {
this.singer = singer;
}
#Override
public String toString() {
return "Track [title=" + title + ", singer=" + singer + "]";
}
}
The result for this in XML is always correct as <singer_element> and <title_element>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<track>
<singer_element>Metallica</singer_element>
<title_element>Enter Sandman</title_element>
</track>
but for JSON it is sometimes serialized incorrectly as title and singer instead of title_element and singer_element.
{
"title": "Enter Sandman",
"singer": "Metallica"
}
Redeploying the same .war file sometimes results in the wanted formatting.
{
"title_element": "Enter Sandman",
"singer_element": "Metallica"
}
pom.xml dependencies
<dependencies>
<!-- JAX-RS -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1</version>
</dependency>
<!-- Jersey -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.27</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.27</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.27</version>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.6</version>
</dependency>
</dependencies>
I am using apache-tomcat-9.0.11-windows-x64.
When I redeploy the same war file in Tomcat and make a post request on localhost:8080/jsonprop/json/metallica/post I get either "title" or "title_element" if I request to receive application/json and that's a problem cause I need to always get "title_element".
Link for war file
EDIT: Being more specific now i noticed a conflict i want to use BOTH dependencies below:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId>
<version>2.27</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.3.1</version>
</dependency>
Basically, I am trying to ignore a property (#JsonIgnore), but none of my Jackson annotations are working. Even the #JsonProperty. I tried to add the #JsonIgnore in getters and setters methods, but same behavior.
I also tried to follow official documentation, and tried different libraries
import org.codehaus.jackson.annotate.JsonIgnore; (Same Behavior)
import com.fasterxml.jackson.annotation.JsonIgnore; (Same Behavior)
I see similar posts like #12595351
My Response from the Controller, should not display the Revoked. Attribute, but i got this response:
Actual Response
{
"accessToken": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJqb2huLmRvZUBleGFtcGxlLmNvbSIsImlzcyI6ImpvaG4uZG9lQGV4YW1wbGUuY29tIiwiaWF0IjoxNTI1MzI1Nzk1LCJleHAiOjE1MjUzMzI5OTV9.uri3pRwXQHHG09F-wM40qfuRMRVu_WBK3HlfquGvwYc",
"expiresAt": "2018-05-03T07:36:35.087Z[UTC]",
"expiresIn": 7199,
"issuedAt": "2018-05-03T05:36:35.087Z[UTC]",
"refreshToken": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJqb2huLmRvZUBleGFtcGxlLmNvbSIsImlzcyI6ImpvaG4uZG9lQGV4YW1wbGUuY29tIiwiaWF0IjoxNTI1MzI1Nzk1LCJleHAiOjE1MjU5MzA1OTV9.xj2oytAVwiAIR8U2upJkPH_BdORuJUNbiicvuvGFz0w",
"revoked": false,
"type": "Bearer"
}
Expected Response
{
"accessToken": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJqb2huLmRvZUBleGFtcGxlLmNvbSIsImlzcyI6ImpvaG4uZG9lQGV4YW1wbGUuY29tIiwiaWF0IjoxNTI1MzI1Nzk1LCJleHAiOjE1MjUzMzI5OTV9.uri3pRwXQHHG09F-wM40qfuRMRVu_WBK3HlfquGvwYc",
"expiresAt": "2018-05-03T07:36:35.087Z[UTC]",
"expiresIn": 7199,
"issuedAt": "2018-05-03T05:36:35.087Z[UTC]",
"refreshToken": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJqb2huLmRvZUBleGFtcGxlLmNvbSIsImlzcyI6ImpvaG4uZG9lQGV4YW1wbGUuY29tIiwiaWF0IjoxNTI1MzI1Nzk1LCJleHAiOjE1MjU5MzA1OTV9.xj2oytAVwiAIR8U2upJkPH_BdORuJUNbiicvuvGFz0w",
"type": "Bearer"
}
pom.xml (Using Maven)
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wedhany.fimper</groupId>
<artifactId>fimper</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>fimper</name>
<build>
<finalName>fimper</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<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>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>de.mkammerer</groupId>
<artifactId>argon2-jvm</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>9.0.1</version>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>5.0.7</version>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId>
<version>2.27</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring4</artifactId>
<version>2.27</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-jdk-http</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.17.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.9.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>Development</id>
<dependencies>
<dependency>
<groupId>com.github.blocoio</groupId>
<artifactId>faker</artifactId>
<version>1.2.7</version>
</dependency>
</dependencies>
</profile>
</profiles>
<properties>
<jersey.version>2.27</jersey.version>
<springframework.version>4.3.16.RELEASE</springframework.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
Token.java (My Model)
package com.wedhany.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.wedhany.models.enums.token.GrantType;
import com.wedhany.models.enums.token.Type;
import java.util.Date;
public class Token {
/**
* Attributes
*/
private String accessToken;
private String refreshToken;
#JsonIgnore
private boolean revoked;
#JsonProperty("expires_at")
private Date expiresAt;
private Date issuedAt;
private GrantType grantType;
private Type type;
private User user;
/**
* #return Token TTL in seconds.
*/
public long getExpiresIn() {
return this.expiresAt.getTime() < new Date().getTime()
? 0
: (this.expiresAt.getTime() - new Date().getTime()) / 1000;
}
/**
* #return Token that will grant authentication and authorization.
*/
public String getAccessToken() {
return accessToken;
}
/**
* #param accessToken Token string.
*/
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
/**
* #return Token used to request a new token.
*/
public String getRefreshToken() {
return refreshToken;
}
/**
* #return Invalid token if true.
*/
public boolean isRevoked() {
return revoked;
}
/**
* #param revoked True for invalid.
*/
public void setRevoked(boolean revoked) {
this.revoked = revoked;
}
/**
* #param refreshToken Refresh token.
*/
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
/**
* #return Token's expiration date.
*/
public Date getExpiresAt() {
return expiresAt;
}
/**
* #param expiresAt Token's expiration date.
*/
public void setExpiresAt(Date expiresAt) {
this.expiresAt = expiresAt;
}
/**
* #return Date where the token was requested.
*/
public Date getIssuedAt() {
return issuedAt;
}
/**
* #param issuedAt Date where the token was requested.
*/
public void setIssuedAt(Date issuedAt) {
this.issuedAt = issuedAt;
}
/**
* #return Type of the token.
*/
public Type getType() {
return type;
}
/**
* #param type Type of the token.
*/
public void setType(Type type) {
this.type = type;
}
/**
* #return How the token was claimed.
*/
public GrantType getGrantType() {
return grantType;
}
/**
* #param grantType Set token type of grant.
*/
public void setGrantType(GrantType grantType) {
this.grantType = grantType;
}
/**
* #return Owner of the token
*/
public User getUser() {
return user;
}
/**
* #param user Token's owner.
*/
public void setUser(User user) {
this.user = user;
}
}
AuthenticationController
package com.wedhany.controllers;
import com.wedhany.exceptions.AuthorizationException;
import com.wedhany.models.Token;
import com.wedhany.models.User;
import com.wedhany.services.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import javax.security.sasl.AuthenticationException;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("auth")
public class AuthenticationController {
#Autowired
private AuthenticationService authenticationService;
#POST
#Path("login")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response login(User user, #HeaderParam("user-agent") String userAgent) throws Exception {
try {
// Authenticate the user using the credentials provided
this.authenticationService.authenticate(user.getEmail(), user.getPassword());
// Issue a token for the user
Token token = this.authenticationService.issueToken(user.getEmail(), userAgent);
// Return the token on the response
return Response.ok(token).build();
} catch (AuthorizationException e) {
return Response.status(Response.Status.UNAUTHORIZED).build();
} catch (AuthenticationException e) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
#POST
#Path("refresh")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response refresh(Token token, #HeaderParam("user-agent") String userAgent) throws AuthenticationException {
return Response.status(Response.Status.CREATED)
.entity(this.authenticationService.refresh(token.getRefreshToken(), userAgent))
.build();
}
#POST
#Path("register")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response register(User user) {
user = authenticationService.save(user);
return Response.status(Response.Status.CREATED)
.entity(user)
.build();
}
}
Choose either one of the following but not both:
<!-- JSON-B (JSR-347) support -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId>
<version>2.27</version>
</dependency>
<!-- Jackson 2.x support -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.27</version>
</dependency>
Both Jackson and JSON-B provide JSON from/to Java binding:
Jackson is a quite mature library for JSON processing. It's flexible and has a fair number of extensions modules.
JSON-B is also referenced as JSR-347. It's an specification for JSON binding. The actual implementation will be provided by Eclipse Yasson, which is the reference implementation of the JSR-347.
If you want go for jersey-media-json-jackson, you are supposed to use Jackson annotations. To ignore a property, for instance, use #JsonIgnore.
If you want to go for jersey-media-json-binding, you are supposed to use JSON-B annotations. To ignore a property, for instance, use #JsonbTransient.
You are using jersey-bom, a dependency management artifact that consolidate and centralize the management of dependency versions (without actually adding the dependencies to the project).
So you don't need to specify the version of the org.glassfish.jersey artifacts. Use one of the following (without version):
<!-- JSON-B (JSR-347) support -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId>
</dependency>
<!-- Jackson 2.x support -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
See more details here and here.
The following code works for me with jackson version 2.8.10
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonIgnoreExample {
private static class BeanWithIgnore {
#JsonIgnore
public int id;
public String name;
public BeanWithIgnore(int id, String name) {
this.id = id;
this.name = name;
}
}
public static void main(String[] args) throws JsonProcessingException {
BeanWithIgnore bean = new BeanWithIgnore(1, "My bean");
String result = new ObjectMapper().writeValueAsString(bean);
System.out.println(result); // {"name":"My bean"}
}
}
Basically the jersey-media-json-binding and jersey-media-json-jackson have similar behavior. You can't use both at the same time. The reason the jersey-media-json-jackson was not working it is because the provider which have more priority is the jersey-media-json-binding.
I don't know the whole configuration of your project so one think you can do that is, create manually JSON and then send to response like:
ObjectMapper maper = new ObjectMapper();
return Response.ok(maper.writer().withDefaultPrettyPrinter().writeValueAsString(tokenObject));
It will work like manual conversion without using auto serialization by Jersey.
Note: This thing is not recommendable but it should work.
You need this dependency for conversion:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
This works for me, I have these libs in my pom.xml:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${org.glassfish.jersey.core.version}</version>
<scope>provided</scope>
</dependency>
<!-- ************** Jackson XML and JSON API ************************* -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>${org.glassfish.jersey.core.version}</version>
<scope>provided</scope>
</dependency>
Just remove that property from your class and add this annotation:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown=true)
public class Token {
// ... keep only the properties you want to map
this will tell Jackson to only bind the properties which you actually have in your class ignoring all the rest that might be present in the JSON output.