this is how expose
#POST
#Path("/postPerson/{id}")
#Consumes({"application/com.myapp-v1.0+xml", "application/com.myapp-v1.0+json"})
#Produces(MediaType.APPLICATION_JSON)
public Person postPerson(Person person, #PathParam("id") int id) {
log4j.info("adding person to map id : " + id + " person : " + person.toString());
personsMap.put(id, person);
log4j.info("After size v1.0 : " + personsMap.size() + " id : " + id);
return person;
}
#POST
#Path("/postPerson/{id}")
#Consumes({"application/com.myapp-v2.0+xml", "application/com.myapp-v2.0+json"})
#Produces(MediaType.APPLICATION_XML)
public String postPersonv1(Person person, #PathParam("id") int id) {
log4j.info("Before size v2.0 : " + personsMap.size() + " id : " + id);
personsMap.put(id, person);
log4j.info("After size v2.0 : " + personsMap.size() + " id : " + id);
return "ok";
}
XML works fine !!
But When I post Json face this exception :
No message body reader has been found for class server.obj.Person, ContentType: application/com.myapp-v2.0+json
[WARNING] /malamPayroll/cxfDemo/postPerson/1000
java.lang.AbstractMethodError: javax.ws.rs.core.Response$ResponseBuilder.status(ILjava/lang/String;)Ljavax/ws/rs/core/Response$ResponseBuilder;
at javax.ws.rs.core.Response$ResponseBuilder.status(Response.java:921)
enter image description here
I had the same problem, after some experiments I just downgraded version of javax.ws.rs-api from 2.1 to 2.0.1 and exception is gone. still not sure what was causing the exception as in 2.1 sources I couldn't even see status method with string as input parameter.
Related
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.
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 + '\'' +
'}';
}
}
So basically I want this test to pass should a valid name , like Paul, be entered. However, the junit always fails and I just cant figure out why. Any help is greatly appreciated. The code actually works when I run it also.
public int searchCustomer(String fName) throws SQLException
{
displayAllCustomers();
if(fName.isEmpty())
{
System.out.println("Please enter a name to search: ");
Scanner scanner = new Scanner(System.in);
fName = scanner.nextLine();
}
String fnameQ="Select * from customers where first_name='"+fName+"';";
try
{
rs = stmt.executeQuery(fnameQ);
while (rs.next())
{
int cus_id = rs.getInt("cus_id");
int reg_id=rs.getInt("reg_id");
String first_name = rs.getString("first_name");
String last_name = rs.getString("last_name");
int dob=rs.getInt("dob");
String address_line1=rs.getString("address_line1");
String address_line2=rs.getString("address_line2");
String eircode=rs.getString("eircode");
System.out.println("" + cus_id + " ¦ " + reg_id + " ¦ " + first_name + " ¦ " + last_name + " ¦ " + dob+ " ¦ " + address_line1 + " ¦ " + address_line2 + " ¦ " + eircode);
}
}
catch (SQLException sqle)
{
System.out.println("Error: failed to display all products.");
System.out.println(sqle.getMessage());
System.out.println(fnameQ);
return 0;
}
return 1;
}
Here is the junit test.
public void testsearchCustomer0001() throws SQLException {
newsagentDatabase testObject = new newsagentDatabase();
try{
assertEquals(1,testObject.searchCustomer("Paul"));
}
catch(Exception e)
{
fail("This should be true");
}
}
I am using junit3 if that is needed info. The actual aim of the code is to output info from a database. If you have any questions ask them!!! I will be actively checking here.
I have a Spring REST service (written in Groovy; although that shouldn't matter) that exposes a secured endpoint like so:
class AppData {
String id
String payload
String fizzbuzz
}
#RequestMapping(method=RequestMethod.POST)
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody AppResponse onAppData(#RequestBody AppData appData) {
// Does some processing on appData and then saves
// its 'payload' field to a MongoDB
}
And this works perfectly fine when it receives JSON of the following form:
{
"id" : "12345",
"payload" : "Please save me to a MongoDB",
"fizzbuzz" : "wakka wakka"
}
I'm using Jackson to handle JSON serialization here.
The problem is that I now want the payload property to be true JSON, not a String. So I want to be able to send the endpoint something like this:
{
"id" : "12345",
"payload" : {
"foo" : 24,
"bar" : false,
"whistlefeather" : "Yes of course"
},
"fizzbuzz" : "wakka wakka"
}
And have the payload properly saved off to MongoDB. But here's the catch:
Lots of different teams (potentially hundreds) are going to be sending this endpoint AppData, and all of their payloads are going to look completely different (each team has different payloads they want to send me and have saved in MongoDB). And I don't want to have to write a new endpoint and AppData subclass for each new team I onboard (and thus expose this endpoint to).
Is there any way I can:
Keep my endpoint exactly the way it is; but
Allow the AppData#payload property to accept JSON in any form?
Keeping my code exactly the way it is, if I send a JSON message where the payload is also JSON (and isn't a string), Spring just returns a 400 with an empty response body. This is happening because Spring expects payload to be a String, but sees that its a JSON object.
Any ideas on what I can do inside the AppData class to handle this, or any notions of what the best practice is here?
Use a JsonNode as the type for the payload:
public class AppData {
String id;
JsonNode payload;
String fizzbuzz;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public JsonNode getPayload() {
return payload;
}
public void setPayload(JsonNode payload) {
this.payload = payload;
}
public String getFizzbuzz() {
return fizzbuzz;
}
public void setFizzbuzz(String fizzbuzz) {
this.fizzbuzz = fizzbuzz;
}
public static void main(String[] args) throws IOException {
String json = "{\n" +
" \"id\" : \"12345\",\n" +
" \"payload\" : {\n" +
" \"foo\" : 24,\n" +
" \"bar\" : false,\n" +
" \"whistlefeather\" : \"Yes of course\"\n" +
" },\n" +
" \"fizzbuzz\" : \"wakka wakka\"\n" +
"}";
ObjectMapper om = new ObjectMapper();
AppData appData = om.readValue(json, AppData.class);
System.out.println("appData ID = " + appData.getId());
System.out.println("appData fizzbuzz = " + appData.getFizzbuzz());
System.out.println("appData payload = " + appData.getPayload());
String json2 = "{\n" +
" \"id\" : \"12345\",\n" +
" \"payload\" : \"Please save me to a MongoDB\",\n" +
" \"fizzbuzz\" : \"wakka wakka\"\n" +
"}";
appData = om.readValue(json2, AppData.class);
System.out.println("appData ID = " + appData.getId());
System.out.println("appData fizzbuzz = " + appData.getFizzbuzz());
System.out.println("appData payload = " + appData.getPayload());
}
}
Output:
appData ID = 12345
appData fizzbuzz = wakka wakka
appData payload = {"foo":24,"bar":false,"whistlefeather":"Yes of course"}
appData ID = 12345
appData fizzbuzz = wakka wakka
appData payload = "Please save me to a MongoDB"
Note that to get back a JSON string for the payload, you shouldn't use toString() as in the above example. You should use objectMapper.writeValueAsString(payload).
You can try using a Map, i don't know what it is in Groovy, but this would be the structure in Java.
public class AppData {
String id;
Map<String, Object> payload;
String fizzbuzz;
}
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?