An Error Occurred: Syntax Error: Unexpected token y - mysql

I don't know why I am getting this. Here is some of the code where I try to retrieve some information from database and send it as response to a Jersey resource mapped to a certain URL. I don't know what that y is theerror referring to:
public String myInformation(String theName){
String infoQuery = "Select * from bookinfo where name= \'theName\'";
ResultSet result = null;
conn = newConnection.dbConnection();
try
{
preparedStatement = conn.prepareStatement(infoQuery);
result = preparedStatement.executeQuery(infoQuery);
}
catch (SQLException e)
{
e.printStackTrace();
}
StringBuilder information = new StringBuilder();
try
{
if(result != null){
while(result.next()){
// Build the string which is returned from this
// method and sent as json response for a URL of a resource
I read columns from database and use StringBuilder to store it. At the end I convert it to String and pass it to Jersey resource.
}
else{
System.out.println("No result");
}
}
catch (SQLException e)
{
e.printStackTrace();
}
String someInformation = information.toString();
return someInformation;
}
In my resource:
#GET
#Path("/allSome/{theName}")
#Produces(MediaType.APPLICATION_JSON)
public Response getSomeInfo(#PathParam("theName") String theName){
System.out.println("Name is: "+ theName);
BookInformation bookInfo = new BookInformation();
String bookInformation =bookInfo.bookInformation(bookName);
ResponseBuilder responseBuilder = Response.status(Status.OK);
responseBuilder.entity(bookInformation);
Response response = responseBuilder.build();
return response;
}
Edit
My method is returning a String. On Postman client and I am receiving data back from database but it is coming back as a string with no spaces between them. I think I need to convert that string to JSON so that my resource can send it back to client for displaying on page.
Any help is appreciated. Thanks.

The 'y' must be in the theName parameter, along with some quotes. You should be using PreparedStatement properly, with a placeholder parameter:
String infoQuery = "Select * from bookinfo where name = ?";
// ...
preparedStatement = conn.prepareStatement(infoQuery);
preparedStatement.setString(1, theName);
// ...
Your code is poorly structured. Code that depends on the success of a try block should be inside the try block.

Related

Downloading file from mySQL DB via servlet hosted on AWS

I am currently creating a webpage that displays a table with data from an Mysql DB. One of the columns is a file (stored as a BLOB in the DB). The name of the file is an anchor tag that links to my download.java servlet. My download servlet works when deploying locally, however now that I have deployed to an AWS ElasticBeanstalk instance the servlet does not work.
In the log it says the following:
org.apache.coyote.http11.AbstractHttp11Processor.process Error parsing HTTP request header
Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
and
/usr/share/tomcat8/Downloads/sdc.png (No such file or directory)
The servlet code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "dbURL?serverTimezone=" + TimeZone.getDefault().getID();
Connection conn = DriverManager.getConnection(url , "username" , "password");
String fn = request.getParameter("Id");
String selectSQL = "SELECT file FROM Requests WHERE fileID=?";
PreparedStatement pstmt = conn.prepareStatement(selectSQL);
pstmt.setString(1, fn);
ResultSet rs = pstmt.executeQuery();
// write binary stream into file
String home = System.getProperty("user.home");
File file = new File(home+"/Downloads/" + fn);
FileOutputStream output = new FileOutputStream(file);
System.out.println("Writing to file " + file.getAbsolutePath());
while (rs.next()) {
InputStream input = rs.getBinaryStream("file");
byte[] buffer = new byte[1024];
while (input.read(buffer) > 0) {
output.write(buffer);
}
}
RequestDispatcher rd = request.getRequestDispatcher("/requests.jsp");
rd.forward(request, response);
rs.close();
pstmt.close();
} catch (SQLException | IOException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The servlet should download the file from the Mysql DB to the users download folder. However, this only works locally, on the AWS server it fails. I assume this is because:
String home = System.getProperty("user.home");
returns the home path of the AWS server instance, rather than the path of the users/visitors home path.
Please help me adjust my servlet so that it works on the AWS server
UPDATE: After some research I think that getting the path to the client's download folder is not possible. Now I think I need to make us of a 'save as' dialog box. Any tips on how to do this and resources that could help me do this is appreciated
I was able to get my servlet working using code posted in a question here
My working code now looks like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = null;
try {
// Get Database Connection.
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "dbURL?serverTimezone=" + TimeZone.getDefault().getID();
conn = DriverManager.getConnection(url , "username" , "password");
String fileName = request.getParameter("Id");
System.out.println("File Name: " + fileName);
// queries the database
String sql = "SELECT file FROM requests WHERE fileID= ?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, file);
ResultSet result = statement.executeQuery();
if (result.next()) {
// gets file name and file blob data
Blob blob = result.getBlob("file");
InputStream inputStream = blob.getBinaryStream();
int fileLength = inputStream.available();
System.out.println("fileLength = " + fileLength);
ServletContext context = getServletContext();
// sets MIME type for the file download
String mimeType = context.getMimeType(fileID);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
// set content properties and header attributes for the response
response.setContentType(mimeType);
response.setContentLength(fileLength);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileID);
response.setHeader(headerKey, headerValue);
// writes the file to the client
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
else {
// no file found
response.getWriter().print("File not found for the fn: " + fileName);
}
} catch (Exception e) {
throw new ServletException(e);
}
}

How to convert XML SOAP String to JSONObject (com.ibm.json.java.JSONObject)

Good Day,
I have created a java class in Adapter IBM Mobilefirst Platform that will get response from the Jax-ws service.
// read direct to soap service - 4/4/2017
protected JSONObject createJsonObjectFrmSOAPRequest(Map mapsData) throws IOException, SOAPException {
JSONObject jsonObj = new JSONObject();
String responseSoap="";
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
try {
// Send SOAP Message to SOAP Server
String url = "http://XXXXX:001/test-pvr-ws/empl_get";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(mapsData), url);
// Process the SOAP Response
responseSoap = printSOAPResponse(soapResponse);
// how to convert to jsonobject, the output is in xml string
// XMLToJSONTransformer.transform(responseSoap); - don't know how to use XMLToJSONTransformer
//JSONObject.parse(responseSoap); // convert String to JSONObject
logger.info("jsonObject : " + jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObj;
}
protected String printSOAPResponse(SOAPMessage soapResponse) throws Exception {
String finalstringEnv = "";
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
System.out.print("\nResponse SOAP Message = ");
//create a StringWriter for the output
StringWriter outWriter = new StringWriter();
// StreamResult result = new StreamResult(System.out); // this is for print line output
StreamResult result = new StreamResult(outWriter);
transformer.transform(sourceContent, result);
// how to convert Transformer.transform() to String java
StringBuffer sb = outWriter.getBuffer();
finalstringEnv = sb.toString();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return finalstringEnv;
}
2 . This code will get the Response in XML string, but I don't know how to use library com.ibm.json.*. Which I wanted to convert the String Response to JSONObject.
2.1. Result Response in XML Soap Envelope (example successful Result i got).
<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<a:getTheResponse xmlns:a="http://XXXXX:001/test-pvr-ws/empl_get/">
<getTheRecord>
<statusCode>0</statusCode>
<getTheRecord>
<userid>1212</userid>
</a:getTheResponse>
</soapenv:Body>
</soapenv:Envelope>
2.2. responseSoap String variable i need to convert String XML Soap response To JSONObject
// Process the SOAP Response
responseSoap = printSOAPResponse(soapResponse);
//.............. code to convert String XML Soap response To JSONObject
I answer my Question:
Recently I just trying , I need to use this method XMLToJSONTransformer (com.ibm.json.xml.XMLToJSONTransformer) to convert the XML string to JSONObject.
String jsonObjectStr ="";
// convert String to JSONObject
jsonObjectStr = xmlToJsonTransformer.transform(responseSoap);
jsonObj = JSONObject.parse(jsonObjectStr);

java restful web services retrieving post data

I am getting a JSON object POST request from android volley.I am trying to read the json using the following code.
#POST
#Path("/driver/insertTripLog")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.TEXT_PLAIN)
public String insertTripLog(InputStream incomingData) throws Exception
{
StringBuilder sb = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
String line = null;
while ((line = in.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
System.out.println("Error Parsing: - ");
}
String data=sb.toString();
System.out.println("Data Received: " +data );
return data;
}
The output i am getting json object but the special characters are encoded with %XX format.
Sample Output:
json=%5B%7B%22name%22%3A%22value%22%7D%5D
how to read properly post json data sent from volley.
Use the URLDecoder class to handle the percent encoded content which you are seeing:
String data = sb.toString();
data = java.net.URLDecoder.decode(data, "UTF-8");
Output:
json=[{"name":"value"}]

How to retrieve series of images from mysql and display them in JSP

I'm trying to build an array by fetching data from mysql. The array include text and pictures. So far everything went good but now I have no idea how to display these picture from the memolist on the JSP page. All I can see are just bunch of bytes. Let's see:
My DBQueries looks like this:
public static ArrayList<Memo> selectAllMemoList()
{
DBConnectionPool pool = DBConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT Users.picture, Users.username, Messages.subject, Messages.date, Messages.msg_id " +
"FROM Messages, Users " +
"WHERE Messages.uid_fk = Users.uid " +
"ORDER BY date DESC";
try
{
ps = connection.prepareStatement(query);
rs = ps.executeQuery();
ArrayList<Memo> memolist = new ArrayList<Memo>();
String dbSqlTimestamp = "";
while (rs.next()) {
m.setUserpicture(rs.getString("picture"));
m.setUsername(rs.getString("username"));
m.setSubject(rs.getString("subject"));
m.setDate(dbSqlTimestamp = new SimpleDateFormat("dd-MM-yy HH:mm").format(rs.getTimestamp("date")));
m.setMessageid(rs.getInt("msg_id"));
memolist.add(m);
}
return memolist;
}
catch (SQLException e){
e.printStackTrace();
return null;
}
finally
{
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
My MemoShowAll looks like this:
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession();
ArrayList<Memo> memolist = DBQueries.selectAllMemoList();
request.setAttribute("listmemo", memolist);
String url = "/restricted/MemoList.jsp";
// forward the request and response to the view
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
MemoList.jsp
<z:rows>
<core:forEach var="each" items="${listmemo}">
<z:row>
<img src="${each.userpicture}" border=0 >
<z:label value="${each.username}"/>
<z:label value="${each.subject}"/>
<z:label value="${each.date}"/>
</z:row>
</core:forEach>
</z:rows>
Cheers,
BB
The way that i bypass this issue is by using a servlet to expose the image to the client. For this to work, you should store the image bytes retrieved from the database to the user's session object.
In the html i have < img src="/imageRender?id=someimageid"/ >
Therefore when the browser will try to render the image, it will make a call to /imageRender where my servlet listens to. And the servlet will read the input parameter and then render the image from the session object based on the parameter.
Some helpful links are:
1) Display servlet as img src using session attribute
2) Writing image to servlet response with best performance
Pay special attention to link 2 #BalusC answer to the place where it says In the ImageDAO#find() you can use ResultSet#getBinaryStream() to get the image as an InputStream from the database.
In your case you can create a List of DAO objects that will represent each row from db.

passing values to url using http get

i need to pass 2 string json parameters to a url and i need to get the json response. how can i pass parameters in get method. Here is my code
public void get()
{
HttpConnection con = null;
String url = "my url";
try
{
URLEncodedPostData data = new URLEncodedPostData("UTF-8", false);
data.append("method", "session.getToken");
data.append("phonenumber:=", "1212345687");
data.append("PIN:=", "1234");
url = url + data.toString();
con = (HttpConnection)Connector.open(url);
con.setRequestMethod(HttpConnection.GET);
res = con.getResponseMessage();
res1 = Integer.toString(con.getResponseCode());
screen.add(new RichTextField("Reponce Message: "+res));
screen.add(new RichTextField("Reponce Code: "+res1));
}
catch(Exception ex)
{
screen.add(new RichTextField(""+ex));
}
}
Depending on your server-side language, you can pass the json parameters by adding parameter as a string e.g
For passing parameters to a PHP server-side
String url = "http://www.test.com/test.php?";
url += "method=" + session.getToken;
url += "&phonenumber:=1212345687";
url += "&PIN:=1234";
For your response.. try this
public void get()
{
HttpConnection connection = null;
String results;
byte responseData[] = null;
try {
connection = (HttpConnection) new
ConnectionFactory().getConnection(URL).getConnection();
int len = (int) connection.getLength();
responseData = new byte[len];
DataInputStream dis;
dis = new DataInputStream(connection.openInputStream());
dis.readFully(responseData);
results = new String(responseData);
screen.add(new RichTextField("Reponce Message: "+results));
} catch (Exception e) {
// TODO Handle exception
screen.add(new RichTextField(""+e));
}
}