Error in getting the input in queryparam - java

I have a problem in my web service. It is because, on my first url path, it will check the plate number. Now, I want to get the input of the user from the first url path and use it on the second path. Is it possible? Here's the first url where I will scan the input of the user:
package com.taxisafe.server;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.taxisafe.connection.DatabaseConnection;
import com.taxisafe.json.JsonConstruction;
//PATH FOR CHECKING PLATE NUMBER
#Path("platecheck") //for the url
public class PlateNumberCheck {
#GET
//To get the full url : http://Ipaddress:portnumber/#path/#getPath
#Path("/check")
#Produces(MediaType.APPLICATION_JSON)
//Produces is for the response of JSON.
public String check(#QueryParam("platenumber") String platenumber){
String sagot = "";
if(checkInput(platenumber)){
sagot = JsonConstruction.JSONResponse("checked", true);
} else{
sagot = JsonConstruction.JSONResponse("checked", false, "Not in the database");
}
return sagot;
}
private boolean checkInput (String platenumber){
System.out.println("Check Input");
boolean output = false;
if(JsonConstruction.isNotNull(platenumber)){
try{
output = DatabaseConnection.checkPlate(platenumber);
} catch (Exception e){
output = false;
}
} else{
output = false;
}
return output;
}
}
Here is where I want to access the platenumber without using another String like taxi_plate_no
package com.taxisafe.server;
import java.util.ArrayList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.google.gson.Gson;
import com.taxisafe.array.ArrayConnection;
import com.taxisafe.connection.DatabaseConnection;
import com.taxisafe.json.JsonConstruction;
import com.taxisafe.objects.Objects;
#Path("/displays")
public class DisplayTaxiDetails {
#GET
#Path("taxidetails")
#Produces(MediaType.APPLICATION_JSON)
public String taxidetails(#QueryParam("taxi_plate_no") String taxi_plate_no{
String sagot = "";
String taxidetails = null;
if(checkInput(taxi_plate_no)){
sagot = JsonConstruction.JSONResponse("checked", true);
ArrayList<Objects> taxiDetailsList = new ArrayList<Objects>();
try{
taxiDetailsList = new ArrayConnection().getTaxiDetails(taxi_plate_no);
Gson gson = new Gson();
taxidetails = gson.toJson(taxiDetailsList);
} catch (Exception e){
e.printStackTrace();
}
return taxidetails;
} else{
sagot = JsonConstruction.JSONResponse("checked", false, "Not in the database");
}
return sagot;
}
private boolean checkInput (String taxi_plate_no){
System.out.println("Check Input");
boolean output = false;
if(JsonConstruction.isNotNull(taxi_plate_no)){
try{
output = DatabaseConnection.checkPlate(taxi_plate_no);
} catch (Exception e){
output = false;
}
} else{
output = false;
}
return output;
}
}

Related

How to change custom validation message in the validator class in spring boot?

Below is my code
package com.jockeyclub.races.validation;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.springframework.beans.BeanWrapperImpl;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class RaceReqConstraintValidator implements ConstraintValidator<RaceReq, Object> {
private String raceNum;
private String raceDate;
private String message;
#Override
public void initialize(RaceReq constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
raceDate = constraintAnnotation.raceDate();
raceNum = constraintAnnotation.raceNum();
}
#Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
String rn = (String) new BeanWrapperImpl(value).getPropertyValue(raceNum);
String rd = (String) new BeanWrapperImpl(value).getPropertyValue(raceDate);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String d = formatter.format(LocalDate.parse(new String((String) rd), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
String u = String.format("https://racing.hkjc.com/racing/information/English/Racing/LocalResults.aspx?RaceDate=%s", d);
try {
URL url = new URL(u);
WebRequest request = new WebRequest(url, HttpMethod.POST);
WebClient webClient = new WebClient();
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setCssEnabled(false);
webClient.getCookieManager().setCookiesEnabled(true);
HtmlPage page = webClient.getPage(request);
if (page.getElementById("errorContainer") != null) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addPropertyNode(raceDate).addConstraintViolation(); //message: "No race on this date"
return false;
}
if (!raceNum.equals("1") && page.getByXPath(String.format("/html/body/div/div[2]/table/tbody/tr/td[%s]/a", raceNum)).isEmpty()) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addPropertyNode(raceNum).addConstraintViolation(); //message: "Invalid race number"
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
this is my validator class wherein I return false under 2 conditions. First if condition will return false if there is no race on that date. Second, if condition will return false if the race number is invalid
Here I want to send different messages if my first if condition returns false and if my second if condition returns false. Is there any way to do this? I have mentioned the messages as comments

Java org.json JDBC only last table row from database

I have a RESTful application that connects to MySQL database (raw paste here: https://pastebin.com/raw/3fBp3j0B) and prints out table data in JSON format.
If I System.out.println() some data from ResultSet, everything shows up correctly, but with the JSON API only the last row in the table is printed out, twice.
import java.sql.*;
import javax.json.*;
public class Tietokanta {
protected Connection yhteys = null;
protected Statement kysely = null;
protected ResultSet tulosjoukko = null;
public boolean avaaYhteys() {
boolean ok = true;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
yhteys = DriverManager.getConnection("jdbc:mysql://localhost/savukelaskuri?serverTimezone=UTC", "root", "");
} catch (Exception e) {
e.printStackTrace();
ok = false;
}
return ok;
}
public boolean suljeYhteys() {
boolean ok = true;
try {
this.yhteys.close();
} catch (Exception e) {
ok = false;
}
return ok;
}
}
...
import java.math.BigDecimal;
import javax.json.Json;
import javax.json.JsonArray;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import static javax.ws.rs.client.Entity.json;
import javax.ws.rs.core.MediaType;
import org.json.JSONArray;
import org.json.JSONObject;
#Path("savukkeet")
public class ApiResource extends Tietokanta {
JSONObject jsonolio = new JSONObject();
JSONArray jsontaulu = new JSONArray();
#Context
private UriInfo context;
public ApiResource() {
this.avaaYhteys();
}
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getJson() {
try {
kysely = yhteys.createStatement();
String sql = "SELECT * FROM kulutus";
tulosjoukko = kysely.executeQuery(sql);
while (tulosjoukko.next()) {
System.out.println(tulosjoukko.getString("pvm"));
jsonolio.put("id", tulosjoukko.getInt("id"));
jsonolio.put("pvm", tulosjoukko.getString("pvm"));
jsonolio.put("kulutus", tulosjoukko.getInt("kulutus"));
jsontaulu.put(jsonolio);
}
} catch (Exception e) {
e.printStackTrace();
}
return jsontaulu.toString(4);
}
}
I expect the result to be
[
{
"kulutus": 9,
"pvm": "2019-01-14 16:46:00",
"id": 1
},
{
"kulutus": 8,
"pvm": "2019-01-15 21:18:00",
"id": 2
}
]
but instead I get this
[
{
"kulutus": 8,
"pvm": "2019-01-15 21:18:00",
"id": 2
},
{
"kulutus": 8,
"pvm": "2019-01-15 21:18:00",
"id": 2
}
]
It should work if you create a new JSONObject for each iteration in the while loop:
while (tulosjoukko.next()) {
System.out.println(tulosjoukko.getString("pvm"));
jsonolio = new JSONObject();
jsonolio.put("id", tulosjoukko.getInt("id"));
jsonolio.put("pvm", tulosjoukko.getString("pvm"));
jsonolio.put("kulutus", tulosjoukko.getInt("kulutus"));
jsontaulu.put(jsonolio);
}
Java is pass-by-reference, so when you put a property to jsonolio it overrides the previous value even inside the JSONArray because it is still the same object
putting an object in another container does not make a copy for you. you have 1 json Object and you fill it twice. and you put 2 copies of it in the list. at the end the 1 object just has the second set of values in it. so that is what gets output.
put this line JSONObject jsonolio = new JSONObject(); just after while (tulosjoukko.next()) {

PlayFramework how to access list from super controller

I am completing my university project, but I encountered weird problem. Since I am a student, apologize in the adavance if it is prosaic.
I have my BasicCommonController which has List backendErrors = new ArrayList<>()
, and I have another Controller which extends BasicCommonController, and I'm able to access backendErrors list from BasicCommonController, but I am not able
to put new Element to the list, wchich is always empty. I have tried to access via super.backendErrors, but it also does not work.
How to add some error to the super.backendErrors and access it in another Controllers
this is abstract controller:
package controllers;
import org.apache.commons.lang3.StringUtils;
import play.Logger;
import play.Play;
import play.mvc.Controller;
import java.util.ArrayList;
import java.util.List;
/**
* Created by vv on 22.04.2017.
*/
public class BasicAbstractController extends Controller {
public static final String GO_HOME = "/";
public List<String> backendErrors = new ArrayList<>();
public static String getPlaceToObserve(){
String place = Play.application().configuration().getString("storage.place");
if(StringUtils.isNotBlank(place)){
return place;
}
return StringUtils.EMPTY;
}
public static String getServerInstance(){
String instance = Play.application().configuration().getString("storage.place");
if(StringUtils.isNotBlank(instance)){
return instance;
}
return StringUtils.EMPTY;
}
}
this is example controller
package controllers;
import com.google.common.io.Files;
import com.sun.org.apache.regexp.internal.RE;
import constans.AppCommunicates;
import play.Logger;
import play.mvc.Http;
import play.mvc.Result;
import util.FileUtil;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* Created by vv on 22.04.2017.
*/
public class FileUploadController extends BasicAbstractController {
public Result upload() {
Http.MultipartFormData<File> body = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart<File> picture = body.getFile("picture");
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
File fileToSave = new File(getPlaceToObserve() + "/" + picture.getFilename());
try{
Files.copy(file,fileToSave);
}
catch (IOException ioe){
Logger.error("Unable to write file");
}
Logger.error("File Handled Cuccessfully");
return redirect(GO_HOME);
} else {
flash("error", "Missing file");
return badRequest();
}
}
public Result delete(String fileName){
List<File> files = FileUtil.getCurrentFileNames();
File fileToDelete = null;
for (File file : files) {
if(file.getName().equals(fileName)){
fileToDelete = file;
break;
}
}
boolean deletionResult = FileUtil.deleteGivenFile(fileToDelete);
if(!deletionResult){
// i am not able to add smthg here
backendErrors.add(AppCommunicates.UNABLE_TO_DELETE_FILE);
}
return redirect(GO_HOME);
}
}
I am not able to add nor access list from other controllers

Full RESTFUL WebService with GSON and Java

I have created a RESTFUL webservice, witch returns a json, but at this time i only consult and show a simple select * , i need to create a complete CRUD solution, if anyone have some samples to share, i'll appreciate.
Best Regards to all
My code until now are:
DAO - Access.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import dto.Usuarios;
public class Access
{
public ArrayList<Usuarios> getUsuarios(Connection con) throws SQLException
{
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM usuarios");
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Usuarios usuariosObj = new Usuarios();
usuariosObj.setUsr_id(rs.getInt("usr_id"));
usuariosObj.setUsr_login(rs.getString("usr_login"));
usuariosObj.setUsr_pwd(rs.getString("usr_pwd"));
usuariosList.add(usuariosObj);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return usuariosList;
}
}
DTO - Usuarios.java
package dto;
public class Usuarios
{
private int usr_id;
private String usr_login;
private String usr_pwd;
public Usuarios()
{
}
public Usuarios(int usr_id, String usr_login, String usr_pwd)
{
super();
this.usr_id = usr_id;
this.usr_login = usr_login;
this.usr_pwd = usr_pwd;
}
public int getUsr_id()
{
return usr_id;
}
public void setUsr_id(int usr_id)
{
this.usr_id = usr_id;
}
public String getUsr_login()
{
return usr_login;
}
public void setUsr_login(String usr_login)
{
this.usr_login = usr_login;
}
public String getUsr_pwd()
{
return usr_pwd;
}
public void setUsr_pwd(String usr_pwd)
{
this.usr_pwd = usr_pwd;
}
#Override
public String toString()
{
return "[ {usr_id=" + usr_id + ", usr_login=" + usr_login + ", usr_pwd=" + usr_pwd + "} ]";
}
}
Model - AccessManager.java
package model;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import dao.Access;
import dao.Database;
import dto.Usuarios;
public class AccessManager
{
public ArrayList<Usuarios> getUsuarios() throws Exception
{
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
Database db = new Database();
Connection con = db.getConnection();
Access access = new Access();
usuariosList = access.getUsuarios(con);
return usuariosList;
}
}
WebService - UsuariosService.java
package webService;
import java.util.ArrayList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import com.google.gson.Gson;
import model.AccessManager;
import dto.Usuarios;
#Path("/UsuariosService")
public class UsuariosService
{
#GET
#Path("/usuarios")
#Produces("application/json")
public String usuarios()
{
String usuarios = null;
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
try
{
usuariosList = new AccessManager().getUsuarios();
Gson gson = new Gson();
//usuarios = gson.toJson(usuariosList);
usuarios = "{\"usuarios\" :" + gson.toJson(usuariosList) + "}";
} catch (Exception e)
{
e.printStackTrace();
}
return usuarios;
}
}
Usually you should ask a specific trouble you have instead of ask for samples. It looks like you have a structured code and all you need is implement all operations exposing as a service.
In case you need a sample, there quite a lot of resources on the web. Something like this: https://code.google.com/p/javaee6-crud-example/
I'll try give you some quick tips below:
WebService - UsuariosService.java
#POST
#Path("/usuarios")
public Response save(Usuario user) {
try {
manager= new AccessManager();
manager.save(user);
return Response.ok("User has been created.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
#DELETE
#Path("/usuarios/{id}")
public Response delete(#PathParam("id") String id) {
try {
manager= new AccessManager();
manager.delete(id);
return Response.ok("User has been deleted.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
#PUT
#Path("/usuarios/{id}")
public Response delete(#PathParam("id") String id, Usuario user) {
try {
manager= new AccessManager();
manager.update(id, user);
return Response.ok("User has been updated.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
If you donĀ“t understand the usage of PUT, DELETE, POST and so on, I recommend you to read HTTP Method Tutorial. There is several discussion regarding this but you might skip it for a while.
I think you might get an idea from here. Your DAO needs to implement methods to perform CRUD interface as well. The link I've added has a very simple sample that might help as well. You might also check this JPA link.
Not sure whether info above helped but I think it is a start since you have to code it in order to understand more about it :)

Java #PathParam always null

I'm trying to use the #PathParam using Jersey, but it always sees it as null.
Here's the method:
The url is http://localhost:8080/GiftRegistryAPI/api/v2/inventory/david with /v2/inventory being at the class level
package com.omar.rest.inventory;
import javax.websocket.server.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import org.codehaus.jettison.json.JSONArray;
import com.omar.rest.util.*;
#Path("/v2/inventory")
public class V2_Inventory {
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response returnHostRegistries(#QueryParam("hostId") int hostId) throws Exception {
String returnString = null;
JSONArray jsonArray = new JSONArray();
try {
// A host ID of 0 indicates a null parameter, there will never be a host with an ID of 0
if (hostId == 0) {
return Response.status(400).entity("Error: please provide a valid host ID for this search").build();
}
Schema dao = new Schema();
jsonArray = dao.qryReturnHostRegistries(hostId);
returnString = jsonArray.toString();
}
catch (Exception e) {
e.printStackTrace();
return Response.status(500).entity("Server was not able to process your request").build();
}
System.out.println(returnString);
return Response.ok(returnString).build();
}
#Path("/{firstName}")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response returnSearchedRegistries(#PathParam("firstName") String name) throws Exception{
String returnString = null;
JSONArray jsonArray = new JSONArray();
System.out.println("Name: " +name);
try {
Schema dao = new Schema();
jsonArray = dao.qryReturnHostRegistries(name);
returnString = jsonArray.toString();
}
catch (Exception e) {
e.printStackTrace();
return Response.status(500).entity("Server was not able to process your request").build();
}
System.out.println(returnString);
return Response.ok(returnString).build();
}
}
The name parameter when debugged is always null, and I can't find any way at all of getting it to recognise I've entered anything in.
Any ideas what might be going wrong?
It was my import statement
import javax.websocket.server.PathParam;
should have been
import javax.ws.rs.PathParam;
In this error, most of the time the issue is wrong import. Just make sure you have import javax.ws.rs.PathParam;

Categories

Resources