Issue in populating combobox using Json from postgresql in ExtJs and Servlets - json

In my Java EE web application there is a combobox in a form panel. I tried to populate this combobox from my postgresql database using JsonReader. I am using ExtJs 3.0 and JSP & Sevlets.
This is my ExtJs code segment for combobox and JsonReader.
var vehicleStore = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : "http://" + host + ":" + port + "/" + projectName + "/"
+ "DeliveryVehicle"
}),
reader : new Ext.data.JsonReader({
idProperty : 'vCode',
root : 'vehicles',
fields : [ {
name : 'vCode'
}, {
name : 'vRegNum'
} ]
}),
autoLoad : true
});
{
xtype : 'combo',
name : 'include_type',
fieldLabel : 'Delivery Vehicle',
emptyText : 'Delivery Vehicle',
editable : false,
hideLabel : true,
style : 'marginleft:10px',
displayField : 'vRegNum',
valueField : 'vCode',
store : vehicleStore,
flex : 1
}
And this is my DeliveryVehicle.java servlet.
package com.xontworld.ornox.Geotrack;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xontworld.ornox.connection.ConnectionManager;
public class DeliveryVehicle extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DeliveryVehicle() {
//super();
// TODO Auto-generated constructor stub
}
#Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContext context = getServletContext();
String dbName = context.getInitParameter("ConnectionDB");
String connectionHost = context.getInitParameter("ConnectionHost");
String connectionUser = context.getInitParameter("ConnectionUser");
String connectionPassword = context.getInitParameter("ConnectionPassword");
String port = "5433";
Statement statement = null;
ResultSet vehicleResultSet = null;
Connection pgConnection = null;
String lineString = "";
try {
pgConnection = ConnectionManager.getPostgresConnection(
connectionHost, connectionUser, connectionPassword,
dbName, port);
out.println(connectionHost+","+ connectionUser+","+ connectionPassword+","+ dbName);
statement = pgConnection.createStatement();
out.print(pgConnection);
String sql = "";
sql = "select distinct vehiclecode, registrationnumber from hoobtvehicles v WHERE v.status='1'";
vehicleResultSet = statement.executeQuery(sql);
String jsonData = "{'vehicles':[";
while (vehicleResultSet.next()) {
jsonData += "{ 'vCode' : '";
jsonData += vehicleResultSet.getString(1).trim();
jsonData += "', ";
jsonData += "'vRegNum' : '";
jsonData += vehicleResultSet.getString(2).trim();
if (vehicleResultSet.isLast()) {
jsonData += "' } ";
} else {
jsonData += "' } , ";
}
}
jsonData += "]}";
out.print(jsonData);
} catch (Exception e) {
// TODO Auto-generated catch block
out.println(e.toString());
e.printStackTrace();
}
}
}
And this is my Json data.
{'vehicles':[{ 'vCode' : '1001', 'vRegNum' : 'XY-100-123' } , { 'vCode' : '1002', 'vRegNum' : 'GY-122-120' } , { 'vCode' : '1000000001', 'vRegNum' : 'XY-100-123' } ]}
The problem is it doesn't load the combobox and it doesn't even print anything in my eclipse console. And also it doesn't show any error message in firebug console. I use alert to check the size of the vehicleStore. It'a zero. Anyone has an idea what's going on here.
I would be much obliged if anyone please be so kind enough to explain what's wrong with my codes and how should I correct it?
Thanks a lot

Related

Upload pdf in HTML and Deserialize json file

I'm trying to upload a file in html and then send it to my database via restangular.
My frontend is a combination of angular with typescript but the upload is a form.
<form enctype="multipart/form-data">
<fieldset class="form-group" ng-repeat="field in $ctrl.metadata.fields">
<label ng-if="field.inputType !== 'hidden'" for="{{field.propertyKey}}"><strong>{{field.name}}</strong></label>
<input ng-if="field.inputType !== 'select' && field.inputType !== 'file'" class="form-control" type="{{field.inputType}}" name="{{field.propertyKey}}" id="{{field.propertyKey}}" ng-model="$ctrl.data[field.propertyKey]"/>
<input ng-if="field.inputType === 'file'" class="form-control" ngf-select type="{{field.inputType}}" name="{{field.propertyKey}}" id="{{field.propertyKey}}" ng-model="$ctrl.data[field.propertyKey]"/>
<sp-dropdown ng-if="field.inputType === 'select'" value="$ctrl.data[field.propertyKey]" api-domain="field.linkedObjectApiDomain" linked-object-name="field.linkedObjectName"></sp-dropdown>
</fieldset>
<button class="btn btn-primary" ng-click="$ctrl.save({item: $ctrl.data})">Save</button>
<button ng-if="$ctrl.metadata.buttons.hasOpen" class="btn btn-primary" ng-click="$ctrl.open()">Open</button>
</form>
I did the databinding of the file with ng-file-upload.
Upon saving we enter this typescript save method.
public save(item: any): any {
console.log("item to save is ", item);
console.log("rapport is ", item["rapport"]);
if (item.id === undefined) {
this.restService.save(this.metadata.apiDomain, item).then((addedItem: any) => {
toastr.success(`${addedItem.naam} successfully created.`, `Overzicht Dossiers Created`);
});
} else {
this.restService.update(this.metadata.apiDomain, item).then((updatedItem: any) => {
toastr.success(`${updatedItem.naam} successfully updated.`, `Overzicht Dossiers Updated`);
});
}
}
The second log with the file gives the json:
lastModified:1463402787393
lastModifiedDate:Mon May 16 2016 14:46:27 GMT+0200 (Romance (zomertijd))
name:"Rapport.pdf"
size:83605
type:"application/pdf"
upload:Promise
webkitRelativePath:""
__proto__:File
On server side I'm using a spring project which I didn't set up myself but the important files are my class which should store this data
Dossier
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package be.ugent.lca.data.entities;
import be.ugent.sherpa.entity.BaseEntity;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
/**
*
* #author Sam
*/
#Entity
//#JsonDeserialize(using = DossierDeserializer.class)
//#JsonSerialize(using = DossierSerializer.class)
public class Dossier extends BaseEntity{
private String externDossierNr;
private String internDossierNr;
private Date datum;
private Boolean doc;
private Date refKlantDatum;
private String refKlantVerwijzing;
private String verantw;
#OneToOne(fetch=FetchType.LAZY, mappedBy="dossier")
private Offerte offerte;
private String status;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "persoon")
private Persoon persoon;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "OrganisatieFirma")
private OrganisatieFirma organisatieFirma;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "OrganisatieIntern")
private OrganisatieIntern organisatieIntern;
#Lob
#Column(length=100000)
private byte[] rapport;
public Offerte getOfferte() {
return offerte;
}
public void setOfferte(Offerte offerte) {
this.offerte = offerte;
}
public byte[] getRapport() {
return rapport;
}
public void setRapport(byte[] rapport) {
this.rapport = rapport;
}
public OrganisatieFirma getOrganisatieFirma() {
return organisatieFirma;
}
public String getExternDossierNr() {
return externDossierNr;
}
public void setExternDossierNr(String externDossierNr) {
this.externDossierNr = externDossierNr;
}
public String getInternDossierNr() {
return internDossierNr;
}
public void setInternDossierNr(String internDossierNr) {
this.internDossierNr = internDossierNr;
}
public void setOrganisatieFirma(OrganisatieFirma organisatieFirma) {
this.organisatieFirma = organisatieFirma;
}
public OrganisatieIntern getOrganisatieIntern() {
return organisatieIntern;
}
public void setOrganisatieIntern(OrganisatieIntern organisatieIntern) {
this.organisatieIntern = organisatieIntern;
}
public Persoon getPersoon() {
return persoon;
}
public void setPersoon(Persoon persoon) {
this.persoon = persoon;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getDatum() {
return datum;
}
public void setDatum(Date datum) {
this.datum = datum;
}
public Date getRefKlantDatum() {
return refKlantDatum;
}
public void setRefKlantDatum(Date refKlantDatum) {
this.refKlantDatum = refKlantDatum;
}
public String getRefKlantVerwijzing() {
return refKlantVerwijzing;
}
public void setRefKlantVerwijzing(String refKlantVerwijzing) {
this.refKlantVerwijzing = refKlantVerwijzing;
}
public String getVerantw() {
return verantw;
}
public void setVerantw(String verantw) {
this.verantw = verantw;
}
public Boolean getDoc() {
return doc;
}
public void setDoc(Boolean doc) {
this.doc = doc;
}
}
and my repository for this class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package be.ugent.lca.data.repository;
import be.ugent.lca.data.entities.Dossier;
import be.ugent.lca.data.query.DossierQuery;
import be.ugent.sherpa.repository.RestRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
/**
*
* #author Sam
*/
#RepositoryRestResource(collectionResourceRel = "dossiers", path = "dossiers")
public interface DossierRepository extends RestRepository<Dossier, DossierQuery<?>>{
}
When trying to save a file to my database the server gives this exception
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of byte[] out of START_OBJECT token
This led me to believe that I have to write my own deserializer for Dossier
Thus:
package be.ugent.lca.data.entities.deserializers;
import be.ugent.lca.data.entities.Dossier;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
public class DossierDeserializer extends JsonDeserializer {
#Override
public Dossier deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode root = oc.readTree(jsonParser);
Dossier dossier = new Dossier();
dossier.setExternDossierNr(root.get("externDossierNr").asText());
dossier.setInternDossierNr(root.get("internDossierNr").asText());
return dossier;
}
}
But my problem is that I don't know how exactly to deserialize the file json, since writing out root.get("rapport") gives back an empty string.
Any help would be much appreciated.
I've worked out the file upload.
First of all I split the file upload from the rest of my data so I won't have to rewrite the automatic deserialization for everything that does work.
this.restService.save(this.metadata.apiDomain, item).then((addedItem: any) => {
toastr.success(`${addedItem.naam} successfully created.`, `Overzicht Dossiers Created`);
console.log("created item ", addedItem);
var fd = new FormData();
fd.append("rapport", item["rapport"]);
this.restService.one('dossiers/' + addedItem.id + '/rapport').withHttpConfig({transformRequest: angular.identity}).customPOST(fd, '', undefined, {'Content-Type': undefined}).then(
(addedDossier: any) => {
console.log("posted dossier ", addedDossier);
}
);
});
In the callback of my normal save I do the custom post to dossiers/{id}/rapport for this I need a custom controller.
#BasePathAwareController
#RequestMapping("/dossiers/{id}")
#ExposesResourceFor(Dossier.class)
public class DossierController {
The BasePathAwawareController makes sure that all automatically generated paths that you don't override keep existing.
#Autowired
private DossierRepository dossierRepository;
With this I inject my repository to connect to my database.
#RequestMapping(path = "/rapport", method = RequestMethod.POST)//,headers = "content-type=multipart/form-data")
public #ResponseBody String postRapport(#PathVariable("id") Long id,#RequestParam("rapport") MultipartFile file) {
String name = "rapport";
System.out.println("Entered custom file upload with id " + id);
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
Dossier dossier = dossierRepository.findOne(id);
dossier.setRapport(bytes);
dossierRepository.save(dossier);
return "You successfully uploaded " + name + " into " + name + "-uploaded !";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}
Like this I'm able to successfully upload my file.

How can I retrieve and display images from mysql in a JSP page? [duplicate]

How can I retrieve and display images from a database in a JSP page?
Let's see in steps what should happen:
JSP is basically a view technology which is supposed to generate HTML output.
To display an image in HTML, you need the HTML <img> element.
To let it locate an image, you need to specify its src attribute.
The src attribute needs to point to a valid http:// URL and thus not a local disk file system path file:// as that would never work when the server and client run at physically different machines.
The image URL needs to have the image identifier in either the request path (e.g. http://example.com/context/images/foo.png) or as request parameter (e.g. http://example.com/context/images?id=1).
In JSP/Servlet world, you can let a Servlet listen on a certain URL pattern like /images/*, so that you can just execute some Java code on specific URL's.
Images are binary data and are to be obtained as either a byte[] or InputStream from the DB, the JDBC API offers the ResultSet#getBytes() and ResultSet#getBinaryStream() for this, and JPA API offers #Lob for this.
In the Servlet you can just write this byte[] or InputStream to the OutputStream of the response the usual Java IO way.
The client side needs to be instructed that the data should be handled as an image, thus at least the Content-Type response header needs to be set as well. You can obtain the right one via ServletContext#getMimeType() based on image file extension which you can extend and/or override via <mime-mapping> in web.xml.
That should be it. It almost writes code itself. Let's start with HTML (in JSP):
<img src="${pageContext.request.contextPath}/images/foo.png">
<img src="${pageContext.request.contextPath}/images/bar.png">
<img src="${pageContext.request.contextPath}/images/baz.png">
You can if necessary also dynamically set src with EL while iterating using JSTL:
<c:forEach items="${imagenames}" var="imagename">
<img src="${pageContext.request.contextPath}/images/${imagename}">
</c:forEach>
Then define/create a servlet which listens on GET requests on URL pattern of /images/*, the below example uses plain vanilla JDBC for the job:
#WebServlet("/images/*")
public class ImageServlet extends HttpServlet {
// content=blob, name=varchar(255) UNIQUE.
private static final String SQL_FIND = "SELECT content FROM Image WHERE name = ?";
#Resource(name="jdbc/yourDB") // For Tomcat, define as <Resource> in context.xml and declare as <resource-ref> in web.xml.
private DataSource dataSource;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String imageName = request.getPathInfo().substring(1); // Returns "foo.png".
try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_FIND)) {
statement.setString(1, imageName);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
byte[] content = resultSet.getBytes("content");
response.setContentType(getServletContext().getMimeType(imageName));
response.setContentLength(content.length);
response.getOutputStream().write(content);
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
}
}
} catch (SQLException e) {
throw new ServletException("Something failed at SQL/DB level.", e);
}
}
}
That's it. In case you worry about HEAD and caching headers and properly responding on those requests, use this abstract template for static resource servlet.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
How to upload an image and save it in database?
Simplest way to serve static data from outside the application server in a Java web application
I suggest you address that as two problems. There are several questions and answer related to both.
How to load blob from MySQL
See for instance Retrieve image stored as blob
How to display image dynamically
See for instance Show thumbnail dynamically
I've written and configured the code in JSP using Oracle database.
Hope it will help.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class displayfetchimage
*/
#WebServlet("/displayfetchimage")
public class displayfetchimage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public displayfetchimage() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
Statement stmt = null;
String sql = null;
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
InputStream in = null;
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
Connection conn = employee.DbConnection.getDatabaseConnection();
HttpSession session = (HttpSession) request.getSession();
String ID = session.getAttribute("userId").toString().toLowerCase();
try {
stmt = conn.createStatement();
sql = "select user_image from employee_data WHERE username='" + ID + "' and rownum<=1";
ResultSet result = stmt.executeQuery(sql);
if (result.next()) {
in = result.getBinaryStream(1);// Since my data was in first column of table.
}
bin = new BufferedInputStream(in);
bout = new BufferedOutputStream(out);
int ch = 0;
while ((ch = bin.read()) != -1) {
bout.write(ch);
}
} catch (SQLException ex) {
Logger.getLogger(displayfetchimage.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (bin != null)
bin.close();
if (in != null)
in.close();
if (bout != null)
bout.close();
if (out != null)
out.close();
if (conn != null)
conn.close();
} catch (IOException | SQLException ex) {
System.out.println("Error : " + ex.getMessage());
}
}
}
// response.getWriter().append("Served at: ").append(request.getContextPath());
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Statement stmt = null;
String sql = null;
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
InputStream in = null;
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
Connection conn = employee.DbConnection.getDatabaseConnection();
HttpSession session = (HttpSession) request.getSession();
String ID = session.getAttribute("userId").toString().toLowerCase();
try {
stmt = conn.createStatement();
sql = "select user_image from employee_data WHERE username='" + ID + "' and rownum<=1";
ResultSet result = stmt.executeQuery(sql);
if (result.next()) {
in = result.getBinaryStream(1);
}
bin = new BufferedInputStream(in);
bout = new BufferedOutputStream(out);
int ch = 0;
while ((ch = bin.read()) != -1) {
bout.write(ch);
}
} catch (SQLException ex) {
Logger.getLogger(displayfetchimage.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (bin != null)
bin.close();
if (in != null)
in.close();
if (bout != null)
bout.close();
if (out != null)
out.close();
if (conn != null)
conn.close();
} catch (IOException | SQLException ex) {
System.out.println("Error : " + ex.getMessage());
}
}
}
}
Try to flush and close the output stream if it does not display.
Blob image = rs.getBlob(ImageColName);
InputStream in = image.getBinaryStream();
// Output the blob to the HttpServletResponse
response.setContentType("image/jpeg");
BufferedOutputStream o = new BufferedOutputStream(response.getOutputStream());
byte by[] = new byte[32768];
int index = in.read(by, 0, 32768);
while (index != -1) {
o.write(by, 0, index);
index = in.read(by, 0, 32768);
}
o.flush();
o.close();
I used SQL SERVER database and so the answer's code is in accordance. All you have to do is include an <img> tag in your jsp page and call a servlet from its src attribute like this
<img width="200" height="180" src="DisplayImage?ID=1">
Here 1 is unique id of image in database and ID is a variable. We receive value of this variable in servlet. In servlet code we take the binary stream input from correct column in table. That is your image is stored in which column. In my code I used third column because my images are stored as binary data in third column. After retrieving input stream data from table we read its content in an output stream so it can be written on screen. Here is it
import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import model.ConnectionManager;
public class DisplayImage extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException
{
Statement stmt=null;
String sql=null;
BufferedInputStream bin=null;
BufferedOutputStream bout=null;
InputStream in =null;
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
Connection conn = ConnectionManager.getConnection();
int ID = Integer.parseInt(request.getParameter("ID"));
try {
stmt = conn.createStatement();
sql = "SELECT * FROM IMAGETABLE WHERE ID="+ID+"";
ResultSet result = stmt.executeQuery(sql);
if(result.next()){
in=result.getBinaryStream(3);//Since my data was in third column of table.
}
bin = new BufferedInputStream(in);
bout = new BufferedOutputStream(out);
int ch=0;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}
} catch (SQLException ex) {
Logger.getLogger(DisplayImage.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try{
if(bin!=null)bin.close();
if(in!=null)in.close();
if(bout!=null)bout.close();
if(out!=null)out.close();
if(conn!=null)conn.close();
}catch(IOException | SQLException ex){
System.out.println("Error : "+ex.getMessage());
}
}
}
}
After the execution of your jsp or html file you will see the image on screen.
You can also create custom tag for displaying image.
1) create custom tag java class and tld file.
2) write logic to display image like conversion of byte[] to string by Base64.
so it is used for every image whether you are displaying only one image or multiple images in single jsp page.

How can I pass value from JSP page to Servlet and save in MySQL database?

I want to upload a file in apache tomcat and save data in the MySQL from text field using JSP. On doing so, I could not pass the value from JSP page to Servlet and save in Database.
How can I do it?
I tried the following lines of code:
JSP:
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input name="a" type="text"/>
<br />
<input type="submit" value="Upload File" />
</form>
And also I used the following lines of code in Servlet:
Servlet
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 10000 * 1024;
private int maxMemSize = 5 * 1024;
private File file;
String gi;
#Override
public void init() {
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
}
protected void processRequest(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
gi =request.getParameter("a");
if (!isMultipart) {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("D:\\Software\\apache-tomcat-7.0.29\\webapps\\Hello\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);
try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
} else {
file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
}
fi.write(file);
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
} catch (Exception ex) {
out.println("Your file size should be less than 10 or equal to 10kb" + ex);
}
try {
/* TODO output your page here. You may use following sample code. */
out.println("<h1>"+gi+"</h1>");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webSiteTest", "root", "root");
PreparedStatement stat = conn.prepareStatement("insert into abc(name) values (?)");
stat.setString(1, gi);
int aa = stat.executeUpdate();
JOptionPane.showMessageDialog(null, "Database Connected Successfully.");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Query Error!");
} catch (ClassNotFoundException ee) {
JOptionPane.showMessageDialog(null, "Database not Found!");
}
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
processRequest(request, response);
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
//throw new ServletException("GET method used with " + getClass().getName() + ": POST method required.");
processRequest(request, response);
}
}
How can I do this.
Create file object that points to a file specified by you in JSP.
and in JSP do,
request.setAttribute("file",fileObject);
and in Servlet get that object using
request.getAttribute("file");
try this.it should work.
To send a file through a JSP/servlet we need a commonsio.jar file and this will be easily found in the google. Now place that jar file in the lib directory of the tomcat folder and Now it will work.

Google docs api for Java (exception)

I have a problem with google docs. I want to retrieve all your files by using OAuth 2.0. The problem is that once you do, and authorization when trying to download a file gives me this error:
Exception in thread "main" java.lang.NullPointerException
at GoogleBlack.readUrl(GoogleBlack.java:95)
at GoogleBlack.getDocument(GoogleBlack.java:87)
at GoogleBlack.go(GoogleBlack.java:187)
at GoogleBlack.main(GoogleBlack.java:222)
Here's the code I use
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.GoogleAuthTokenFactory.UserToken;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.util.ServiceException;
public class GoogleBlack {
private static final String APPLICATION_NAME = "Homework";
public DocsService service;
public GoogleService spreadsheetsService;
static String CLIENT_ID = "***********";
static String CLIENT_SECRET = "**************";
static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
static List<String> SCOPES = Arrays.asList("https://docs.google.com/feeds");
public void getSpreadSheet(String id, String i, String ids, String type) throws Exception {
UserToken docsToken = (UserToken) service.getAuthTokenFactory()
.getAuthToken();
UserToken spreadsheetsToken = (UserToken) spreadsheetsService
.getAuthTokenFactory().getAuthToken();
service.setUserToken(spreadsheetsToken.getValue());
URL url = null;
if(type.equals("doc"))
{
url = new URL("https://docs.google.com/feeds/download/documents/Export?id="+ ids);
}
else
{
url = new URL("https://docs.google.com/feeds/download/spreadsheets/Export?key="+ ids +"&exportFormat="+ type + "&gid=0");
i += ".xls";
}
System.out.println("Spred = " + url.toString());
readUrl1(url.toString(), i, type);
service.setUserToken(docsToken.getValue());
}
public void readUrl1(String url, String i, String type) throws IOException, ServiceException
{
MediaContent mc = new MediaContent();
mc.setUri(url);
MediaSource ms = service.getMedia(mc);
System.out.println("Name: "+i);
BufferedInputStream bin = new BufferedInputStream(ms.getInputStream());
OutputStream out = new FileOutputStream(i);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
}
public void getDocument(String id, String i) throws Exception {
URL url = new URL(id);
readUrl(url,i);
}
public void readUrl(URL url, String i) throws Exception {
MediaContent mc = new MediaContent();
mc.setUri(url.toString());
System.out.println("Url "+ url.toString());
System.out.println("MC: " + mc.toString());
MediaSource ms = service.getMedia(mc);
System.out.println("Name: "+i);
BufferedInputStream bin = new BufferedInputStream(ms.getInputStream());
OutputStream out = new FileOutputStream(i);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
// FileOutputStream fout = null;
// fout = new FileOutputStream(i);
// fout.write(cbuf.);
// fout.close();
}
static Credential getCredentials() {
HttpTransport transport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
// Step 1: Authorize -->
String authorizationUrl =
new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URI, SCOPES).build();
// Point or redirect your user to the authorizationUrl.
System.out.println("Go to the following link in your browser:");
System.out.println(authorizationUrl);
// Read the authorization code from the standard input stream.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is the authorization code?");
String code = null;
try {
code = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Step 1 <--
// Step 2: Exchange -->
GoogleTokenResponse response = null;
try {
response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
code, REDIRECT_URI).execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Step 2 <--
// Build a new GoogleCredential instance and return it.
return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.setJsonFactory(jsonFactory).setTransport(transport).build()
.setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken());
}
public void go() throws Exception {
DocsService service = new DocsService(APPLICATION_NAME);
service.setOAuth2Credentials(getCredentials());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
DocumentListFeed feed = service.getFeed(feedUrl, DocumentListFeed.class);
System.out.println("Feed " + feed.getEntries().size());
for(int i = 0; i < feed.getEntries().size(); i++)
{
DocumentListEntry entry = feed.getEntries().get(i);
if(entry.getType().equals("file"))
{
MediaContent mc1 = (MediaContent) entry.getContent();
String UrlForDownload = mc1.getUri();
System.out.println("Type is: " + entry.getType());
System.out.println("File Name is: " + entry.getTitle().getPlainText());
System.out.println("URL "+ UrlForDownload);
getDocument(UrlForDownload, entry.getFilename());
}
else
{
MediaContent mc1 = (MediaContent) entry.getContent();
String UrlForDownload = mc1.getUri();
System.out.println("URL "+ UrlForDownload);
System.out.println("Type is: " + entry.getType());
System.out.println("File Name is: " + entry.getTitle().getPlainText());
if(entry.getTitle().getPlainText().equals("Web Design 2011/2012 - Материали"))
{
continue;
}
if(entry.getType().equals("spreadsheet"))
{
String name = entry.getTitle().getPlainText().replaceAll(" ", "");
System.out.println("name: " + name);
getSpreadSheet(UrlForDownload, name, entry.getDocId(),"xls");
}
else
{
String name = entry.getTitle().getPlainText().replaceAll(" ", "");
System.out.println("name: " + name);
getSpreadSheet(UrlForDownload, name, entry.getDocId(),"doc");
}
}
}
}
public static void main(String[] args) throws Exception {
new GoogleBlack().go();
}
}
95 row - MediaSource ms = service.getMedia(mc);
87 row - readUrl(url,i);
187 row - getDocument(UrlForDownload, entry.getFilename());
222 row - new GoogleBlack().go();
I apologize if I am not well explained!!!
You never initialized the "public DocsService service;" member of your GoogleBlack class, so when you call "service.getMedia(mc);" you're getting a NullPointerException.

SSE and Servlet 3.0

I have registered a typical SSE when page loads:
Client:
sseTest: function(){
var source = new EventSource('mySSE');
source.onopen = function(event){
console.log("eventsource opened!");
};
source.onmessage = function(event){
var data = event.data;
console.log(data);
document.getElementById('sse').innerHTML+=event.data + "<br />";
};
}
My Javascript-Debugger says, that "eventsource opened!" was successfully.
My Server Code is a Servlet 3.0:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(urlPatterns={"/mySSE"}, name = "hello-sse", asyncSupported=true)
public class MyServletSSE extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/event-stream");
resp.setCharacterEncoding("UTF-8");
Random random = new Random();
PrintWriter out = resp.getWriter();
//AsyncContext aCtx = req.startAsync(req, resp);
//ServletRequest sReq = aCtx.getRequest();
String next = "data: " + String.valueOf(random.nextInt(100) + 1) + "\n\n";
//out.print("retry: 600000\n"); //set the timeout to 10 mins in milliseconds
out.write(next);
out.flush();
// do not close the stream as EventSource is listening
//out.close();
//super.doGet(req, resp);
}
}
The code works! The Client-Code triggers the doGet()-Method every 3 seconds and retrieves the new data.
Questions:
However, I wonder how I can make this code better by using new Servlet 3.0 Futures such as Async-Support or asyncContext.addListener(asyncListener) or something else which I do not know. As I never closes the stream, I wonder how my server will scale?
Theoretically, the best approach would be to trigger the doGet()-Method via server-side-code explicitly when new data is there, so the client does not need to trigger the client-side "onmessage()"-Method and therefore the server side "doGet()"-Method every 3 seconds for new data.
This is an excellent question, here is a full working example (Servlet 3.0 / Java EE 6)
Some notes:
it handles "browser tab / window closed" via out.checkError() that also calls flush()
I wrote it quickly, so I'm sure it can be improved, just a POC, don't use in production before testing
Servlet: (omitted imports for brevity, will update a full gist soon)
#WebServlet(urlPatterns = {"/mySSE"}, asyncSupported = true)
public class MyServletSSE extends HttpServlet {
private final Queue<AsyncContext> ongoingRequests = new ConcurrentLinkedQueue<>();
private ScheduledExecutorService service;
#Override
public void init(ServletConfig config) throws ServletException {
final Runnable notifier = new Runnable() {
#Override
public void run() {
final Iterator<AsyncContext> iterator = ongoingRequests.iterator();
//not using for : in to allow removing items while iterating
while (iterator.hasNext()) {
AsyncContext ac = iterator.next();
Random random = new Random();
final ServletResponse res = ac.getResponse();
PrintWriter out;
try {
out = res.getWriter();
String next = "data: " + String.valueOf(random.nextInt(100) + 1) + "num of clients = " + ongoingRequests.size() + "\n\n";
out.write(next);
if (out.checkError()) { //checkError calls flush, and flush() does not throw IOException
iterator.remove();
}
} catch (IOException ignored) {
iterator.remove();
}
}
}
};
service = Executors.newScheduledThreadPool(10);
service.scheduleAtFixedRate(notifier, 1, 1, TimeUnit.SECONDS);
}
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res) {
res.setContentType("text/event-stream");
res.setCharacterEncoding("UTF-8");
final AsyncContext ac = req.startAsync();
ac.setTimeout(60 * 1000);
ac.addListener(new AsyncListener() {
#Override public void onComplete(AsyncEvent event) throws IOException {ongoingRequests.remove(ac);}
#Override public void onTimeout(AsyncEvent event) throws IOException {ongoingRequests.remove(ac);}
#Override public void onError(AsyncEvent event) throws IOException {ongoingRequests.remove(ac);}
#Override public void onStartAsync(AsyncEvent event) throws IOException {}
});
ongoingRequests.add(ac);
}
}
JSP:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function test() {
var source = new EventSource('mySSE');
source.onopen = function(event) {
console.log("eventsource opened!");
};
source.onmessage = function(event) {
var data = event.data;
console.log(data);
document.getElementById('sse').innerHTML += event.data + "<br />";
};
}
window.addEventListener("load", test);
</script>
</head>
<body>
<h1>Hello SSE!</h1>
<div id="sse"></div>
</body>
</html>
Useful example.
People might get "IllegalStateException: Not supported" for startAsync(), in which case either don't forget:
#WebServlet(urlPatterns = "/Sse", asyncSupported=true)
or use
request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
from this post