Java #PathParam always null - java

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;

Related

How to save excel data to json file?

When I try to save excel data in JSON file under resource folder. I am getting Null pointer exception when I hit send in postman. Not sure if the code is okay or anyone can refer any code for saving excel file in json format.
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.simple.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.google.gson.Gson;
#RestController
public class ExcelController {
#PostMapping("excel")
public String getExcel(#RequestParam("file") MultipartFile file) {
excel2Json(file);
return "Success";
}
public void excel2Json(MultipartFile file) {
try {
XSSFWorkbook workBook = new XSSFWorkbook(file.getInputStream());
XSSFSheet workSheet = workBook.getSheetAt(0);
List<JSONObject> dataList = new ArrayList<>();
XSSFRow header = workSheet.getRow(0);
for(int i=1;i<workSheet.getPhysicalNumberOfRows();i++) {
XSSFRow row = workSheet.getRow(i);
JSONObject rowJsonObject = new JSONObject();
for(int j=0; j<row.getPhysicalNumberOfCells();j++) {
String columnName = header.getCell(j).toString();
String columnValue = row.getCell(j).toString();
rowJsonObject.put(columnName, columnValue);
}
dataList.add(rowJsonObject);
}
System.out.println(dataList);
writeData2JsonFile(dataList);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeData2JsonFile(List<JSONObject> dataList) {
Gson gson = new Gson();
try {
FileWriter file = new FileWriter("D:\\work\\blog-api\\src\\main\\resources\\data.json");
file.write(gson.toJson(dataList));
file.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please let me know why I am getting null pointer exception when I hit the excel file in postman.

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

Error in getting the input in queryparam

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;
}
}

Not a Valid Service SOAP Call

I am creating my first SOAP Service and I am getting the error Not a valid Service. Could someone please help me out? I am creating a project for a imaginary belt store. SO my service is supposed to get all the products that are not shipped yet. For now i am just sending it in an array. Once the service starts working i will modify it in a better way.
Below is my error
Exception in thread "main" javax.xml.ws.WebServiceException: {http://service.itmd.iit/}OrdersImplService is not a valid service. Valid services are: {http://util.itmd.iit/}OrdersImplService
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:200)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:145)
at com.sun.xml.internal.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:93)
at javax.xml.ws.Service.<init>(Service.java:56)
at javax.xml.ws.Service.create(Service.java:680)
at iit.itmd.client.Client.main(Client.java:19)
Below is my Interface
package iit.itmd.service;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.xml.bind.annotation.XmlRootElement;
#WebService
#SOAPBinding(style=Style.RPC)
#XmlRootElement
public interface Orders {
#WebMethod String[] getNotFulfilled();
}
My Order Implementation class which implements the above interface is given below
package iit.itmd.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import iit.itmd.service.Orders;
#XmlType
#WebService(endpointInterface="iit.itmd.service.Orders")
public class OrdersImpl implements Orders{
#Override
#XmlElement
public String[] getNotFulfilled() {
// TODO Auto-generated method stub
Connection conn=null;
Statement statement=null;
int i=0;
String selecttableSql="select id,customer_id from orders where status<>'SHIPPED'";
String[] result=null;
try{
DBConn con=new DBConn();
conn=con.getConnection();
statement = conn.createStatement();
ResultSet rs = statement.executeQuery(selecttableSql);
System.out.println(rs.getFetchSize());
while (rs.next()) {
String orderId = rs.getString("ID");
String customerId = rs.getString("CUSTOMER_ID");
result[i]=orderId;
result[i]= customerId;
System.out.println("userid : " + orderId);
System.out.println("username : " + orderId);
}}
catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
}
I created a client to call the SOAP Service. The code for the client is below
package iit.itmd.client;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import iit.itmd.domain.*;
import iit.itmd.service.Orders;
public class Client {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://localhost:9999/BeltStore/getnotshipped");
//1st argument service URI, refer to wsdl document above
//2nd argument is service name, refer to wsdl document above
QName qname = new QName("http://service.itmd.iit/", "OrdersImplService");
Service service = Service.create(url, qname);
Orders order = service.getPort(Orders.class);
System.out.println(order.getNotFulfilled());
}
}
Could someone please let me know what i am doing wrong? Thanks.
In your client code you specify a namespace for the service, which is good practice, but I don't see that namespace back in your service code. Your service has to define a namespace and this should correspond with the namespace your client uses for specifying the webservice method. E.g.
#WebService(targetNamespace = "http://service.itmd.iit/")

Categories

Resources