JAX-RS: How to navigate to Response method to get all resources? - java

I want to implement method to get All Orders when I send request on: localhost:8080/ProjectName/MyApplication/orders
Now when I access that location in my web browser I got:
HTTP Status 404 - Not Found
#Path("orders")
public class MehanicarServis {
#GET
#Produces(MediaType.TEXT_XML)
public Response getOrders() {
try {
Connection c = DriverManager.getConnection(DB.LOCATION, DB.USER, DB.PASS);
Statement s = c.createStatement();
String query = "SELECT * FROM orders";
ResultSet r = s.executeQuery(query);
List<Order> orders = new ArrayList<>();
while (r.next()) {
orders.add(new Order(r.getInt("id"), r.getString("name")));
}
GenericEntity<List<Order>> gOrders = new GenericEntity<List<Order>>(orders) {};
return Response.status(200).entity(gOrders).build();
} catch (SQLException ex) {
Logger.getLogger(MehanicarServis.class.getName()).log(Level.SEVERE, null, ex);
return Response.status(404).build();
}
}
Method is right, there's no problems, but I have problem to invoke this Response method over URL in browser? What should i change in URL example to invoke it?
P.S. I've implemented MyApplication class which extends Application, so in my opinion mistake is somewhere between annotations of getOrders()?

Related

How to convert select-input content to string on sql query?

My html form has 2 select-input field which are sent via HTTP POST as json to my java webserver API and then to my postgresql. Im having a internal error and i believe that is because the select-input json output is like this "field":["value"]
How can i tell java to read the content inside the [ ]?
this is my query
String sqlQuery = "INSERT INTO neuromotora(nervonome,latencia,amplitudedistal,amplitudeprox,velocidade,ondaf,pacienteid,ladonervo)"
+ " VALUES(?,?,?,?,?,?,?,?) RETURNING neuromotoraid";
This is the http post method on my angular frontend
postData(params){
let headers = new Headers();
headers.append('Content-type','application/json');
return this.http.post(this.api,params,{
headers: headers
}).map(
(res:Response) => {return res.json();}
);
And this is the java web server post method
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Path("/neuromotora/")
public Response createNeuromotora(Neuromotora n) throws SQLException, ClassNotFoundException{
neuromotoraDAO dao = new neuromotoraDAO();
dao.insert(n);
return Response
}
And this is the neuromotora java
public class Neuromotora {
private int neuromotoraid;
private String latencia;
private String amplitudeDistal;
private String amplitutdeProx;
private String nervoNome;
private String ladoNervo;
private String ondaF;
private int pacienteid;
...getters and setters..
}
Insert method
public Long insert(Neuromotora oferta) throws SQLException, ClassNotFoundException{
Long id = null;
String sqlQuery = "INSERT INTO neuromotora(nervonome,latencia,amplitudedistal,amplitudeprox,velocidade,ondaf,pacienteid,ladonervo)"
+ " VALUES(?,?,?,?,?,?,?,?) RETURNING neuromotoraid";
try{
PreparedStatement stmt = this.con.getConnection().prepareStatement(sqlQuery);
stmt.setString(1,oferta.getNervoNome());
stmt.setString(2,oferta.getLatencia());
stmt.setString(3,oferta.getAmplitudeDistal());
stmt.setString(4,oferta.getAmplitutdeProx());
stmt.setString(5, oferta.getVelocidade());
stmt.setString(8, oferta.getOndaF());
stmt.setInt(6,oferta.getPacienteid());
stmt.setString(7,oferta.getLadoNervo());
ResultSet rs = stmt.executeQuery();
if(rs.next()){
id = rs.getLong("neuromotoraid");
}
this.con.commit();
}
catch(SQLException e){
this.con.rollback();
throw e;
}
return id;
}
Removing the the multiple="true" on the ion-select and adding size="1" worked for me, the input is no longer a json array.

DynamoDB - how to get Primary Key (which is random id) from database to make endpoind class?

I've made method that I use to edit Item from database.
This is how my method looks:
public Product editProduct(PrimaryKey primaryKey, Product content) {
UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey(primaryKey).withValueMap(createValueMap(content));
UpdateItemOutcome itemOutcome = databaseController.getTable(PRODUCT_TABLE).updateItem(updateItemSpec);
return convertToProduct(itemOutcome);
}
private Map<String, Object> createValueMap(Product content) {
Map<String, Object> result = new HashMap<>();
result.put("name", content.getName());
result.put("calories", content.getCalories());
result.put("fat", content.getFat());
result.put("carbo", content.getCarbo());
result.put("protein", content.getProtein());
result.put("productKinds", content.getProductKinds());
result.put("author", content.getAuthor());
result.put("media", content.getMedia());
result.put("approved", content.getApproved());
return result;
}
private Product convertToProduct(UpdateItemOutcome itemOutcome) {
Product product = new Product();
product.setName(itemOutcome.getItem().get("name").toString());
product.setCalories(itemOutcome.getItem().getInt("calories"));
product.setFat(itemOutcome.getItem().getDouble("fat"));
product.setCarbo(itemOutcome.getItem().getDouble("carbo"));
product.setProtein(itemOutcome.getItem().getDouble("protein"));
product.setProductKinds(itemOutcome.getItem().getList("productKinds"));
ObjectMapper objectMapper = new ObjectMapper();
try {
Author productAuthor = objectMapper.readValue(itemOutcome.getItem().getString("author"), Author.class);
product.setAuthor(productAuthor);
} catch (IOException e) {
e.printStackTrace();
}
try {
Media productMedia = objectMapper.readValue(itemOutcome.getItem().getString("media"), Media.class);
product.setMedia(productMedia);
} catch (IOException e) {
e.printStackTrace();
}
return product;
}
Now I want to create endpoint class for this method but I have problem, I need to get primarykey as parameter (it's looks like this for example: 2567763a-d21e-4146-8d61-9d52c2561fc0) and I don't know how to do this.
At the moment my class looks like that:
public class EditProductLambda implements RequestHandler<Map<String, Object>, ApiGatewayResponse> {
private LambdaLogger logger;
#Override
public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) {
logger = context.getLogger();
logger.log(input.toString());
try{
Product product = RequestUtil.parseRequest(input, Product.class);
//PrimaryKey primaryKey = XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
KitchenService kitchenService = new KitchenService(new DatabaseController(context, Regions.EU_CENTRAL_1), logger);
Product editedProduct = kitchenService.editProduct(primaryKey, product);
return ResponseUtil.generateResponse(HttpStatus.SC_CREATED, editedProduct);
} catch (IllegalArgumentException e){
return ResponseUtil.generateResponse(HttpStatus.SC_BAD_REQUEST, e.getMessage());
}
}
Can someone give me some advice how to do that? Or maybe my method is done wrong?
So first you have to create a trigger to Lambda function and ideal prefer here would be an API gateway. You can pass your data as query string or as a request body to API gateway.
You can use body mapping template in the integration request section of API gateway and get request body/query string. Construct a new json at body mapping template, which will have data from request body/query string. As we are adding body mapping template your business logic will get the json we have constructed at body mapping template.
Inside body mapping template to get query string please do ,
$input.params('querystringkey')
For example inside body mapping template (If using query string),
#set($inputRoot = $input.path('$'))
{
"primaryKey" : "$input.params('$.primaryKey')"
}
if passing data as body then,
#set($inputRoot = $input.path('$'))
{
"primaryKey" : "$input.path('$.primaryKey')"
}
Please read https://aws.amazon.com/blogs/compute/tag/mapping-templates/ for more details on body mapping template

How to resolve javax.xml.bind.UnmarshallException?

I am new RESTful web Services and after going through some documentation I am in a state to invoke a web service. It looks like I am receiving a 200 status back from the service producer when I look at the response object but I am also getting javax.xml.bind.UnmarshallException. I get this exception when the code reaches to read the entity. I am a little lost as I am not sure what to do or what to look at in order to resolve this error.
XML Representation of Object
#XmlRootElement( name = "Somethig", namespace = "http://respone.something.com" )
#ReleaseInfo( version = "v4", description = "Response for Validate Email
Service" )
public class ThirdPartyValidateEMailAddressResponse extends BaseResponse {
private String emailAddressProvided;
private String emailAddressReturned;
private String mailboxName;
private String domainName;
private String topLevelDomain;
private String topLevelDomainDesc;
private boolean syntaxCorrected;
private boolean caseStandardized;
private boolean domainNameUpdated;
Client Code:
public ValidateEMailAddressServiceResponse validateEMailAddress( ValidateEMailAddressServiceRequest request ) throws Exception {
WebTarget service = config.createWebResource(request.getServiceURL());
ValidateEMailAddressServiceResponse resp = new ValidateEMailAddressServiceResponse();
service = service.path(SOMETHING).path(SOMETHING).path(SOMETHING).register(ThirdPartyValidateEmailResponseXMLReader.class);
ValidateEMailAddressServiceRequestParameter parameter = null;
parameter = request.getParameter(ValidateEMailAddressServiceRequestParameter.PARAMETERS.emailAddress.name());
if (parameter != null) {
service = service.queryParam(ValidateEMailAddressServiceRequestParameter.PARAMETERS.emailA
Invocation.Builder b = applyHeaders(service, request.getHeaders(), request.getHttpHeaders());
if(request.getAccepts() != null){
b = b.accept(request.getAccepts().value());
}
Response response = b.get(Response.class);
try {
resp = (ValidateEMailAddressServiceResponse) handleBaseResponse(resp, response);
// Managing business or error response
ThirdPartyValidateEMailAddressResponse thirdPartyResponse = null;
if (shouldProcessEntity(SOMETHING+ SOMETHING + SOMETHING, resp)) {
if (ContentType.XML.equals(request.getAccepts()) || ContentType.JSON.equals(request.getAccepts())) {
thirdPartyResponse = response.readEntity(ThirdPartyValidateEMailAddressResponse.class);
}
else {
throw new Exception("Invalid Content Type found while processing response");
}
}
else {
thirdPartyResponse = new ThirdPartyValidateEMailAddressResponse();
thirdPartyResponse.setMessages(createMessagesFromHTTPStatus(resp));
response.close();
}
}
catch (IOException e) {
throw new EISClientException("Exception in processing ValidateEMailAddress", e);
}
return resp;
}
Looks like it fails right here
thirdPartyResponse =
response.readEntity(ThirdPartyValidateEMailAddressResponse.class);
stack trace:
mig.eis.client.EISClientException: javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; Premature end of file.]
Please let me know if anything else is needed from my side to debug this issue.
Thanks

Removing/deleting from google datastore using endpoints, illegal arguement exception, delete with non-zero content length not supported

I'm trying to delete objects from the datastore (using cloud endpoints)
I know the connection is valid because I'm pulling/inserting objects with no problem
However when I try to delete using various approaches I get the same exception
java.lang.illegalArgumentException:DELETE with non-zero content length is not supported
approach 1(using the raw datastore service and the key I stored when inserting the item):
#ApiMethod(name = "removeRPurchase")
public RPurchase removeRPurchase(RPurchase purchase) {
NamespaceManager.set(purchase.getAccount());
DatastoreService d=DatastoreServiceFactory.getDatastoreService();
Key k=KeyFactory.stringToKey(purchase.getKeyrep());
try {
d.delete(k);
} catch (Exception e) {
e.printStackTrace();
purchase=null;
}
return purchase;
}
Approach 2
#ApiMethod(name = "removeRPurchase")
public RPurchase removeRPurchase(RPurchase purchase) {
NamespaceManager.set(purchase.getAccount());
Key k=KeyFactory.stringToKey(purchase.getKeyrep());
EntityManager mgr = getEntityManager();
RPurchase removed=null;
try {
RPurchase rpurchase = mgr.find(RPurchase.class, k);
mgr.remove(rpurchase);
removed=rpurchase;
} finally {
mgr.close();
}
return removed;
}
Ive also tried various variations with the entity manager and the Id, but all with the same exception
The object that i've passed in does contain the namespace in the account, and it does contain the 'KeytoString' of the key associated with the object
the endpoint is called as it should in an AsyncTask endpoint.removeRPurchase(p).execute();
Any help suggestions are appreciated
Make your API method a POST method like this:
#ApiMethod(name = "removeRPurchase" path = "remove_r_purchase", httpMethod = ApiMethod.HttpMethod.POST)
public RPurchase removeRPurchase(RPurchase purchase) {
NamespaceManager.set(purchase.getAccount());
DatastoreService d=DatastoreServiceFactory.getDatastoreService();
Key k=KeyFactory.stringToKey(purchase.getKeyrep());
try {
d.delete(k);
} catch (Exception e) {
e.printStackTrace();
purchase=null;
}
return purchase;
}
I had the same problem because I was using httpMethod = ApiMethod.HttpMethod.DELETE. The error it gives is correct. Simply change it to a POST and do whatever you want inside that API method like delete entities, return entities, etc.
How about trying out the following :
#ApiMethod(
name = "removeRPurchase",
httpMethod = HttpMethod.DELETE
)
public void removeRPurchase(#Named("id") String id) {
//Now take the id and plugin in your datastore code to retrieve / delete
}

Jersey delivers an empty JSON

I'm working on a project for the university which makes me mad. I need to develop a webservice with jersey, but every request sends me just this empty JSON:
[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]
The database query is test and delivers content. I just don't know what it could be.
Java:
#Path("/getFachbereiche")
public class GetFachbereiche {
#GET
#Produces("application/json")
public Fachbereich[] getFachbereiche() {
List<Fachbereich>fList = new ArrayList<Fachbereich>();
Connection conn = MySQLConnection.getInstance();
if (conn != null) {
try {
// Anfrage-Statement erzeugen.
Statement query;
query = conn.createStatement();
// Ergebnistabelle erzeugen und abholen.
String sql = "SELECT * FROM Fachbereich";
ResultSet result = query.executeQuery(sql);
//Ergebniss zurückliefern
while (result.next()) {
fList.add(new Fachbereich(result.getInt(1), result.getString(2)));
}
} catch(SQLException e) {
e.printStackTrace();
}
}
return fList.toArray(new Fachbereich[fList.size()]);
}
}
Your attributes from Fachbereich are private, by default, private attributes are not serialized.
You have two solutions :
Put XmlElement annotation on each attribute so it will be serialized
Or define a public getter for each attribute.

Categories