Json cannot add dependencies - json

Spring Boot version is using version 4.5.2. How can I add Json dependencies to this version?
This error occurs when accessing the current site.
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Feb 28 03:31:40 KST 2020
There was an unexpected error (type=Internal Server Error, status=500).
No converter found for return value of type: class com.example.demo.Dto.TestVo
org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class com.example.demo.Dto.TestVo
at
Source code of TestVo class:
package com.example.demo.Dto;
public class TestVo {
private int seq;
private String title;
private String contents;
private String author;
private String password;
private int reads = 0;
private String deleted = "N";
#Override
public String toString() {
return "TestVo [seq=" + seq + ", title=" + title + ", contents=" + contents + ", author=" + author + ", password=" + password + ", reads=" + reads + ", deleted=" + deleted + "]";
}
}

Your question isn't quite clear, we need to see your dto code, but try and see if adding the following dependency to your pom.xml, solves your problem.
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.10.2</version>
</dependency>

You have not added any getter, and setter methods for member variables for TestVo class.
Add getter and setter methods.

Related

#JsonCreator annotation want an enum value for attribute mode, but is allready given

When creating a shared library for automated deployment with jenkins I use a rest service that provides me with Json objects. Now when I run the pipeline the following error occurs:
Expected enum Value for attribute mode in #com.fasterxml.jackson.annotation.JsonCreator
The interesting thing is that this error does not occur on another Jenkins instance.
The code:
import com.cloudbees.groovy.cps.NonCPS
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
#JsonIgnoreProperties(ignoreUnknown = true)
class Asset {
final String downloadUrl
final String path
final String repository
final String format
#JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
Asset(
#JsonProperty('downloadUrl') String downloadUrl,
#JsonProperty('path') String path,
#JsonProperty('repository') String repository,
#JsonProperty('format') String format
){
this.downloadUrl = downloadUrl
this.path = path
this.repository = repository
this.format = format
}
#Override #NonCPS
String toString() {
return "Asset{" +
"downloadUrl='" + downloadUrl + '\'' +
", path='" + path + '\'' +
", repository='" + repository + '\'' +
", format='" + format + '\'' +
'}';
}
}

Glassfish XML (or JSON) Response for JAX-RS Object Marshalling Results in HTTP 500 Internal Server Error

I am trying to get a JAX RS resource to return a response with a JSON object. When I display the response properties via println() calls in the resource class I see that the MediaType is correctly set to "application/json", that there is an entity associated with the response with the expected type (SalesOrder), status (Status.FOUND) and that the response object is an instance of OutboundJaxrsResponse. But somehow when the browser (or a Jersey client) receives the response, these response attributes seem to be "replaced" and a HTTP 500 Internal Server error is the result. My SalesOrder class is annotated with #XmlRootElement.
My resource looks like this:
#GET
#Path("{orderUid}")
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getSalesOrder(#PathParam("orderUid") Integer orderUid) {
Response response = null;
System.out.println("Entering SalesOrderResource getSalesOrder()...");
SalesOrder retrievedSalesOrder = salesOrderService.retrieveSalesOrder(orderUid);
System.out.println("Service called and found salesOrder Uid: " + retrievedSalesOrder.getSalesOrderUid());
if (retrievedSalesOrder != null) {
System.out.println("SalesOrder found with UID: " + retrievedSalesOrder.getSalesOrderUid());
response = Response.status(Status.FOUND).entity(retrievedSalesOrder).type(MediaType.APPLICATION_JSON).build();
// The following readEntity call results in a Javax.ejb.EJBException ???
// SalesOrder fetched = response.readEntity(SalesOrder.class);
} else {
response = Response.status(Status.NOT_FOUND).header("x-reason", "Order cannot be found").build();
}
System.out.println("Response status: " + response.getStatus());
System.out.println("Response status info: " + response.getStatusInfo());
System.out.println("Response class: " + response.getClass());
System.out.println("Response length: " + response.getLength());
System.out.println("Response media type: " + response.getMediaType());
System.out.println("Response entity: " + response.getEntity());
return response;
}
...which results in the following at runtime:
2015-04-12T18:08:21.803-0600|Info: Response status: 302
2015-04-12T18:08:21.803-0600|Info: Response status info: Found
2015-04-12T18:08:21.803-0600|Info: Response class: class org.glassfish.jersey.message.internal.OutboundJaxrsResponse
2015-04-12T18:08:21.803-0600|Info: Response length: -1
2015-04-12T18:08:21.803-0600|Info: Response media type: application/xml
2015-04-12T18:08:21.803-0600|Info: Response entity: business.salesOrderMgmt.entity.SalesOrder#5e49cadd
The SalesOrder entity is defined as:
#Entity
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#JsonIgnoreProperties({"subTotal", "userAccount"})
#Table(name="sales_order")
#NamedQuery(name="SalesOrder.findAll", query="SELECT s FROM SalesOrder s")
public class SalesOrder implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="SALES_ORDER_UID")
private int salesOrderUid;
#Column(name="ORDER_NUMBER")
private String orderNumber;
#Column(name="BILL_TO_CITY")
private String billToCity;
#Column(name="BILL_TO_FIRST_NAME")
private String billToFirstName;
#Column(name="BILL_TO_LAST_NAME")
private String billToLastName;
#Column(name="BILL_TO_STATE")
private String billToState;
#Column(name="BILL_TO_STREET_NAME")
private String billToStreetName;
#Column(name="BILL_TO_STREET_NUMBER")
private String billToStreetNumber;
#Column(name="BILL_TO_UNIT_NUMBER")
private String billToUnitNumber;
#Column(name="BILL_TO_ZIP_CODE")
private int billToZipCode;
#Column(name="CREDIT_CARD_CSV")
private int creditCardCsv;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="CREDIT_CARD_EXPIRATION_DATE")
private Date creditCardExpirationDate;
#Column(name="CREDIT_CARD_NUMBER")
private String creditCardNumber;
#Column(name="CREDIT_CARD_TYPE")
private String creditCardType;
#Column(name="EMAIL_ADDRESS")
private String emailAddress;
#Column(name="NAME_ON_CREDIT_CARD")
private String nameOnCreditCard;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="SALES_ORDER_DATE")
private Date salesOrderDate;
#Column(name="SALES_ORDER_STATUS")
private String salesOrderStatus;
#Column(name="SHIP_TO_CITY")
private String shipToCity;
#Column(name="SHIP_TO_STATE")
private String shipToState;
#Column(name="SHIP_TO_STREET_NAME")
private String shipToStreetName;
#Column(name="SHIP_TO_STREET_NUMBER")
private String shipToStreetNumber;
#Column(name="SHIP_TO_UNIT_NUMBER")
private String shipToUnitNumber;
#Column(name="SHIP_TO_ZIP_CODE")
private int shipToZipCode;
#Column(name="PROMO_CODE")
private String promoCode;
//Calculated and persisted for data retrieval performance
#Column(name="SUB_TOTAL")
private BigDecimal subTotal;
#Column(name="DISCOUNT")
private BigDecimal discount;
#Column(name="SALES_TAX")
private BigDecimal salesTax;
#Column(name="SHIPPING")
private BigDecimal shipping;
#Column(name="TOTAL")
private BigDecimal total;
#Version
#Column(name="LAST_UPDATED_TIME")
private Timestamp lastUpdatedTime;
//bi-directional many-to-one association to UserAccount
#ManyToOne
#JoinColumn(name="USER_ACCOUNT_UID")
private UserAccount userAccount;
#OneToMany(targetEntity=SalesOrderLine.class, mappedBy = "salesOrder", cascade = CascadeType.ALL)
private List<SalesOrderLine> lineItems;
public SalesOrder() {
}
...getters and setters
Dependencies in my POM include:
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.5.2</version>
</dependency>
Not only does a request (http://localhost:8080/[myapp]/resources/salesOrders/13) result in an HTTP 500 Internal Server error but when I have attempted calling response.readEntity(SalesOrder.class) within the resource the Glassfish server log show a javax.ejb.EJBException warning caused by java.lang.IllegalStateException: Method not supported on an outbound message at org.glassfish.jersey.message.internal.OutboundJaxrsResponse.readEntity(OutboundJaxrsResponse.java:145).
I think there is a problem with the JAXB marshalling of the SalesOrder object but I cannot pin down the root cause. If I simply attempt the following I still get an HTTP 500 Internal Server error as well, indicating that neither XML nor JSON marshalling is taking place but I thought this was built into the latest versions (Glassfish 4, JAX-RS 2)?
Any ideas?
I figured out the problem and will post it here for the benefit of others.
1) I added the following to the resource method:
#Consumes(MediaType.TEXT_PLAIN)
2) Step #1 resulted in the following error at runtime:
A cycle is detected in the object graph. This will cause infinitely deep XML
3) The error led me to add #XmlTransient to all entity fields related to other entities in OneToMany, ManyToMany and ManyToOne.
Now I am able to return a response in XML and JSON.
I have had similar problem. To be sure, check if your log shows something like:
SEVERE: MessageBodyWriter not found for media type=application/json,
type=class SalesOrder, genericType=class SalesOrder.
If so, problem is that you did not register Jackson (or another JSON writer provider). See this section of Jersey documentation for instructions:
https://jersey.java.net/documentation/latest/media.html#d0e7857
In my case, I chose Jackson. I added following to my pom.xml.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.17</version>
</dependency>
Then I had to register the provider:
public class Application extends ResourceConfig {
public Application() {
packages(<your ws package>);
register(JacksonFeature.class);
}
}

CDI - Java EE Servlet saving variables to a managed bean

I have a Java EE class that currently reads info from a form and prints it out.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Response extends HttpServlet
{
String date = "0";
public void init() throws ServletException
{
//Get Election Date from xml
String initial = getInitParameter("electionDate");
date = initial;
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
//Get values from form
PrintWriter out = response.getWriter();
String firstName=request.getParameter("firstname");
String lastName=request.getParameter("lastname");
String address=request.getParameter("address");
String city=request.getParameter("city");
String state=request.getParameter("state");
String zip=request.getParameter("zip");
String phone = request.getParameter("phone");
String affil=request.getParameter("affil");
//Print Summary of Voter Registration
out.println("<html>");
out.println("<head><title>Registration Summary</title></head>");
out.println("<body>");
out.println("<p>Registration Summmary</p>");
out.println("<p>First Name: " + firstName + "</p>");
out.println("<p>Last Name: " + lastName + "</p>");
out.println("<p>Address : " + address + "</p>");
out.println("<p>City : " + city + "</p>");
out.println("<p>State : " + state + "</p>");
out.println("<p>Zip: " + zip + "</p>");
out.println("<p>Phone Number: " + phone + "</p>");
out.println("<p>Affiliation: " + affil + "</p>");
out.println("<p>Next Election Date: " + date + "</p></p>");
out.println("<p>Is the above information correct?</p>");
out.println("<button>Yes</button>");
out.println("<button>No</button>");
out.println("</body></html>");
out.close();
}
}
I want to get the values (firstName, lastName, etc.) from this Java servlet and inject to a bean.
Then when this file calls another servlet I want the values from the bean to be available in that servlet.
I just want to know how to store the variables I created above into a managed bean and then have the other servlet reference and retrieve the variables in that bean.
I have beans.xml, web.xml, pom.xml (I'm using Maven) files set up already.
You cannot simply inject Strings, so you will have to use a qualifier (the simplest one is #Named, see if that is sufficient).
In your servlet, say
#Produces
#Named("foo")
String lastName;
...
void doPost() {
lastName = getParameter(...);
}
and in the target bean, use
#Inject
#Named("foo")
String lastName;
Since you are in a Request-Scope, keep in mind that injecting request-scoped values into longer living instances (EJBs for example) might lead to unpredictable behavior. I seriously doubt that your approach will make you happy. Perhaps you could tell us more about what you are trying to do?

JPA difference Windows / Unix System?

For development purposes i'm using a windows environment (Eclipse / Jboss)
There i have a userDAO, that offers the method to rerieve a UserEntity by first- and lastname. This Query runs well on the dev environment. However on the Unix-Environment, i get a javax.persistence.NoResultException: No entity found for query Exception.
Situation in Detail:
A REST-Service is beeing called, containing many Data, along with a firstname and lastname. this parameters needs to be used to obtain the actuall userEntity. (It fails for ANY user on Unix.)
So, the rest service is doing this:
#Consumes("application/json")
#Produces("application/json")
public String create(String plaindata) {
JSONObject data = new JSONObject(plaindata);
String ownerFirstname = data.getString("userFirstname"); //Yes userX, not ownerX
String ownerLastname = data.getString("userLastname");
UserEntity owner = null;
try {
owner = userDataService.getUserDetailsByName(ownerFirstname, ownerLastname);
} catch (Exception e) {
throw new Exception("Found zero possible users for the given name '" + ownerFirstname + " " + ownerLastname
+ "'. Cannot invoke process.", e);
}
...
}
The userDataService looks (stripped) like this:
private static String GET_USER_BY_FIRSTNAME_LASTNAME_QUERY = "SELECT * FROM " + DBConstants.USER_TABLE_NAME
+ " user WHERE user.FIRST_NAME = :firstnameValue AND user.LAST_NAME = :lastnameValue";
public UserEntity getUserDetailsByName(String firstname, String lastname) {
Query query = em.createNativeQuery(GET_USER_BY_FIRSTNAME_LASTNAME_QUERY, UserEntity.class);
query.setParameter("firstnameValue", firstname);
query.setParameter("lastnameValue", lastname);
UserEntity u = (UserEntity) query.getSingleResult();
return u;
}
DBConstants contains the table name like:
public static final String DATATABLE_PREFIX = "pre_";
public static final String USER_TABLE_NAME = DATATABLE_PREFIX+"user_entity";
Column Names in mySQL are Capitalized, so everything seems right.
this works on a Windows Environment, but NOT in the Unix Environment :(
String ownerFirstname = data.getString("userFirstname").trim();
String ownerLastname = data.getString("userLastname").trim();
And it works... Strange thing - what could be the difference between windows and unix towards this issue? (The Exception logged absolutely NO Whitespace)

Datanucleus JDO setting fields to null

In an attempt to find another issue, my tests came up with the following bit of code.
public class TestPersistance {
private static final PersistenceManagerFactory PMF = JDOHelper.getPersistenceManagerFactory("datanucleus.properties");
public static final PersistenceManager pm = PMF.getPersistenceManager();
static final TestUserDataDB ud = new TestUserDataDB();
public static void main(String args[])
{
TestPersistance tp = new TestPersistance();
tp.createData();
}
#Test public void createData()
{
assertTrue("Null machined id at start", ud.machineId != null);
pm.currentTransaction().begin();
try
{
pm.makePersistent(ud);
}
finally
{
pm.currentTransaction().commit();
}
assertTrue("Null machined id at end", ud.machineId != null);
}
}
where the second assert fails. ie. my object that I am asking to be persisted is being changed by the makePersistent call. The data is being stored in the database.
Any ideas? Can any one confirm this.
using
jdo-api-3.0.jar
datanucleus-core-2.2.0-release.jar
datanucleus-enhancer-2.1.3.jar
datanucleus-rdbms-2.2.0-release.jar
mysql-connector-java-5.1.13.jar
in eclipse with MySql database.
#PersistenceCapable
public class TestUserDataDB {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
public Long id;
#Persistent
public String userid = "test1";
#Persistent
public String machineId = "test2";
// local userid
#Persistent
public long uid = 1L;
#Persistent
public long systemTime = 123L;
public long chk = 1234L;
public long createTime = System.currentTimeMillis();
public TestUserDataDB()
{
}
#Override
public String toString() {
return "TestUserDataDB [chk=" + chk + ", createTime=" + createTime
+ ", id=" + id + ", machineId=" + machineId + ", systemTime="
+ systemTime + ", uid=" + uid + ", userid=" + userid + "]";
}
}
Properties file is
javax.jdo.PersistenceManagerFactoryClass=org.datanucleus.jdo.JDOPersistenceManagerFactory
datanucleus.metadata.validate=false
javax.jdo.option.ConnectionDriverName=com.mysql.jdbc.Driver
javax.jdo.option.ConnectionURL=jdbc:mysql://localhost/test
javax.jdo.option.ConnectionUserName=root
javax.jdo.option.ConnectionPassword=yeahRight
datanucleus.autoCreateSchema=true
datanucleus.validateTables=false
datanucleus.validateConstraints=false
Why are you accessing fields directly ? Is the accessing class declared as PersistenceAware ? Well it isn't so you can't do that - use the getters.
What is "ud" object state before persist ? (transient?) what is it after persist ? (hollow?) What does the log say ? Chances are that it is in hollow state and then you access a field directly and it has no value (by definition, as per the spec) ... but since you didn't bother calling the getter it hasn't a chance to retrieve the value. And you likely also don't have "RetainValues" persistent property set
Suggest you familiarise yourself with the JDO spec and object lifecycle states
In some cases, it is necessary to access deserialized objects' attributes directly (i.e. if using GSON library for JSON serialization). In that case you can use:
MyClass copy = myPersistencyManager.detachCopy(myRetrievedInstance);