Writing data to an excel(CSV) file - java

I have created one servlet code. The main goal is to write data from a database to a csv file. In my code, the csv file gets downloaded successfully, but the file remains empty. The project contains javacsv.jar file. I don't have any clue why that is. Please shed some light on how I can achieve this. For a summary please read the points below:
Access data from database table.
Then write that data into the csv file with table format like < td >data here< / td> . [I want this format because I can format that data as per my requirements.]
Please shed some light guys peace :) Refer this Servlet code below:
public class excelServletFile extends HttpServlet {
String name = "";
String email = "";
String eid = "Username";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
String fileName = eid + "Data.csv";
ServletContext context = getServletContext();
String mimeType = context.getMimeType(fileName);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileName);
response.setHeader(headerKey, headerValue);
OutputStream outStream = response.getOutputStream();
ConnectionClass cn = new ConnectionClass();
Connection con = cn.connectDb();
PreparedStatement ps;
ResultSet rs;
Charset cs = Charset.forName("UTF-8");
Writer writer = new PrintWriter(System.out);
writer.flush();
writer.append("NAME");
writer.append("EMAIL");
ps = con.prepareStatement("select name,email from user");
rs = ps.executeQuery();
while (rs.next()) {
name = rs.getString("name");
email = rs.getString("email");
PrintWriter out = response.getWriter();
out.println(name);
out.println(email);
writer.append(name);
writer.append(email);
}
writer.close();
} catch (Exception e) {
System.out.println(e);
}
}

package servletProject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/govinds")
public class CSVServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req, resp);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
FileWriter writer = null;
ResultSet rs = null;
Connection con = null;
PreparedStatement ps = null;
try {
String fileName = "D:/Data.csv";
System.out.println(fileName);
ConnectionClass cn = new ConnectionClass();
con = cn.connectDb();
System.out.println("fileName" + fileName);
writer = new FileWriter(fileName);
// Write the CSV file header
CSVUtils.writeLine(writer, Arrays.asList("NAME", "email"));
ps = con.prepareStatement("select firstName,email from employees");
rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("firstName"));
CSVUtils.writeLine(writer, Arrays.asList(rs.getString("firstName"), rs.getString("email")));
}
writer.flush();
writer.close();
download(request, response);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
ps.close();
con.close();
} catch (Exception e) {
}
}
}
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
String filePath = "D:/Data.csv";
File downloadFile = new File(filePath);
FileInputStream inStream = new FileInputStream(downloadFile);
// if you want to use a relative path to context root:
String relativePath = getServletContext().getRealPath("");
System.out.println("relativePath = " + relativePath);
// obtains ServletContext
ServletContext context = getServletContext();
// gets MIME type of the file
String mimeType = context.getMimeType(filePath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// modifies response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// forces download
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName() + ".csv");
response.setHeader(headerKey, headerValue);
// obtains response's output stream
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inStream.close();
outStream.close();
}
}
// DB connection File
public class ConnectionClass {
public Connection connectDb() {
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels","root","root");
}catch (Exception e) {
con=null;
}
if(con!=null)
System.out.println("connected");
else
System.out.println("not connected");
return con;
}
}
//CSVUtil Files
package servletProject;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
public class CSVUtils {
private static final char DEFAULT_SEPARATOR = ',';
public static void writeLine(Writer w, List<String> values) throws IOException {
writeLine(w, values, DEFAULT_SEPARATOR, ' ');
}
public static void writeLine(Writer w, List<String> values, char separators) throws IOException {
writeLine(w, values, separators, ' ');
}
// https://tools.ietf.org/html/rfc4180
private static String followCVSformat(String value) {
String result = value;
if (result.contains("\"")) {
result = result.replace("\"", "\"\"");
}
return result;
}
public static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException {
boolean first = true;
// default customQuote is empty
if (separators == ' ') {
separators = DEFAULT_SEPARATOR;
}
StringBuilder sb = new StringBuilder();
for (String value : values) {
if (!first) {
sb.append(separators);
}
if (customQuote == ' ') {
sb.append(followCVSformat(value));
} else {
sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
}
first = false;
}
sb.append("\n");
w.append(sb.toString());
}
}

Related

Web server hanging. I have no idea why

I'm writing a very tiny, very sh*tty web server just for fun. It was working fine with GET requests or returning a 404. And worked very briefly working with POST requests. And now it just hangs on any POST request.
Here is the relevant bit of code. As you can see I put in some logging to both System.out and to a file. The logging to System.out works, but the logging to file never happens. If I remove the logging to file, it still hangs on the line after System.out log. I included the few lines previous so you can see that it is the exact same code as returning a 404. 404 works, but POST doesn't. This is using a ServerSocket. I'm at a complete loss at this point. Would appreciate any insight.
Edit: Have included the main and sendResponse methods in case there is anything in there that might be causing this.
Edit #2: Ima just post the whole thing.
package beerio;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Beerio {
public static void main( String[] args ) throws Exception {
try (ServerSocket serverSocket = new ServerSocket(80)) {
while (true) {
try (Socket client = serverSocket.accept()) {
handleClient(client);
}
catch(Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
BufferedWriter writer = new BufferedWriter(new FileWriter("errorlog.txt", true));
writer.append(System.lineSeparator());
writer.append(sw.toString());
writer.append(System.lineSeparator());
writer.close();
continue;
}
}
}
}
private static void handleClient(Socket client) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
//make request into string. this only parses until the first blank line
StringBuilder requestBuilder = new StringBuilder();
String line;
while (!(line = br.readLine()).isBlank()) {
requestBuilder.append(line + "\r\n");
}
//split string and parse into request info
String request = requestBuilder.toString();
String[] requestsLines = request.split("\r\n");
String[] requestLine = requestsLines[0].split(" ");
String method = requestLine[0];
String path = requestLine[1];
String version = requestLine[2];
String host = requestsLines[1].split(" ")[1];
List<String> headers = new ArrayList<>();
for (int h = 2; h < requestsLines.length; h++) {
String header = requestsLines[h];
headers.add(header);
}
//rest of request contains post info. parse that here
if(method.equals("POST")) {
String parameters;
parameters = br.readLine();
String[] temp = parameters.split("&");
String[][] params = new String[temp.length][2];
for(int i=0; i<temp.length; i++) {
params[i][0] = temp[i].substring(0,temp[i].indexOf("="));
params[i][1] = temp[i].substring(temp[i].indexOf("=")+1);
}
}
Path filePath = getFilePath(path);
if (method.equals("GET")) {
System.out.println("doGet");
if (Files.exists(filePath)) {
// file exist
String contentType = guessContentType(filePath);
sendResponse(client, "200 OK", contentType, Files.readAllBytes(filePath));
} else {
// 404
byte[] notFoundContent = "<h1>Not found :(</h1>".getBytes();
sendResponse(client, "404 Not Found", "text/html", notFoundContent);
}
} else if(method.equals("POST")){
byte[] postContent = "<h1>POST Failed Successfully</h1>".getBytes();
sendResponse(client, "200 OK", "text/html", postContent);
}
}
private static void sendResponse(Socket client, String status, String contentType, byte[] content) throws IOException {
OutputStream clientOutput = client.getOutputStream();
clientOutput.write(("HTTP/1.1 " + status+"/r/n").getBytes());
clientOutput.write(("ContentType: " + contentType + "\r\n").getBytes());
clientOutput.write("\r\n".getBytes());
clientOutput.write(content);
clientOutput.write("\r\n\r\n".getBytes());
clientOutput.flush();
client.close();
}
private static Path getFilePath(String path) {
if ("/".equals(path)) {
path = "\\index.html";
}
return Paths.get("C:\\Users\\shawn\\beerio\\beerio\\tmp\\www", path);
}
private static String guessContentType(Path filePath) throws IOException {
return Files.probeContentType(filePath);
}
}

How can i make the content of a webpage downloadable for the client

Im working on a project and i cant find a way to make the content of a page that prints out a table from my database downloadable. I want there to be a button that gives the client the opportunity to download the content of the table in form of either pdf or csv.
this is the servlet fo
package bacit.web.bacit_web;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.sql.*;
#WebServlet(name = "BookingHistorikk", value = "/BookingHistorikk")
public class GetBookingHistorikk extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
{
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<html><body>");
try
{
Class.forName("org.mariadb.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mariadb:**********", "root", "pass");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from BOOKING");
out.println("<table style=text-align:center border=1 width=50% height=10% >");
out.println("<tr><th>Start Dato</th><th>Slutt Dato</th><th>Kommentar</th><th>Levert</th><th>Total Pris</th></tr>");
while (rs.next())
{
Date startDate = rs.getDate("StartDate");
Date endDate = rs.getDate("EndDate");
String cmnt = rs.getString("Cmnt");
Boolean isDelivered = rs.getBoolean("IsDelivered");
int totalPrice = rs.getInt("TotalPrice");
out.println("<tr><td>" + startDate + "</td><td>" + endDate + "</td><td>" + cmnt + "</td><td>" + isDelivered + "</td><td>" + totalPrice + "</td></tr>");
}
out.println("</table>");
out.println("</html></body>");
con.close();
}
catch (Exception e)
{
out.println("error");
}
}
}
There are 2 things you need to do here ...
Create CSV file.
Send it to the user with the help of HttpServletResponse.
You can create a CSV file contents like this:
String getMyCsvFileAsString() {
StringBuilder sb = new StringBuilder();
sb.append("id");
sb.append(',');
sb.append("Name");
sb.append('\n');
sb.append("1");
sb.append(',');
sb.append("Prashant Ghimire");
sb.append('\n');
writer.write(sb.toString());
}
And then you can attach it to the request like this:
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=\"myCsvFile.csv\"");
try
{
OutputStream outputStream = response.getOutputStream();
// Get CSV file as string
String outputResult = getMyCsvFileAsString();
outputStream.write(outputResult.getBytes());
outputStream.flush();
outputStream.close();
}
catch(Exception e)
{
System.out.println(e.toString());
}
}

Why downloaded excel file is not containg any data ? the file is empty

hello everyone i have created one Servlet file. it is downloading as a excel file but not containing any data in it while the code is made build for writing a data in excel file. Basically i have done this steps :-
1. access the data from the database
2.print that data to excel file.
now up to this working as per the expectation but now at time of excel file gets downloaded. that time it is a blank excel file no data contains in that file. Why it is so Please Shed some light i have just started learning JAVA and SERVLET really new to this.
package servletProject;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/ExcelFile")
public class CSVServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
String emails = "xyz#gmail.com";
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req, resp);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
FileWriter writer =null;
ResultSet rs=null;
Connection con=null;
PreparedStatement ps=null;
try {
String fileName = emails+"data.csv";
System.out.println(fileName);
ServletContext context = getServletContext();
String mimeType = context.getMimeType(fileName);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileName);
response.setHeader(headerKey, headerValue);
ConnectionClass cn = new ConnectionClass();
con = cn.connectDb();
System.out.println("fileName"+fileName);
writer = new FileWriter(fileName);
//Write the CSV file header
CSVUtils.writeLine(writer,Arrays.asList("NAME","email"));
ps = con.prepareStatement("select firstName,email from employees");
rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("firstName"));
CSVUtils.writeLine(writer,Arrays.asList(rs.getString("firstName"),rs.getString("email")));
}
writer.flush();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
try{ rs.close();ps.close();con.close();}catch (Exception e) {}
}
}
}
// DB connection File
public class ConnectionClass {
public Connection connectDb() {
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels","root","root");
}catch (Exception e) {
con=null;
}
if(con!=null)
System.out.println("connected");
else
System.out.println("not connected");
return con;
}
}
//CSVUtil Files
package servletProject;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
public class CSVUtils {
private static final char DEFAULT_SEPARATOR = ',';
public static void writeLine(Writer w, List<String> values) throws IOException {
writeLine(w, values, DEFAULT_SEPARATOR, ' ');
}
public static void writeLine(Writer w, List<String> values, char separators) throws IOException {
writeLine(w, values, separators, ' ');
}
// https://tools.ietf.org/html/rfc4180
private static String followCVSformat(String value) {
String result = value;
if (result.contains("\"")) {
result = result.replace("\"", "\"\"");
}
return result;
}
public static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException {
boolean first = true;
// default customQuote is empty
if (separators == ' ') {
separators = DEFAULT_SEPARATOR;
}
StringBuilder sb = new StringBuilder();
for (String value : values) {
if (!first) {
sb.append(separators);
}
if (customQuote == ' ') {
sb.append(followCVSformat(value));
} else {
sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
}
first = false;
}
sb.append("\n");
w.append(sb.toString());
}
}
Here is a version that writes to the response's outputstream.
Note that I changed 'writer' to be an OutputStream instead of a FileWriter, as that is what you get from response.getOutputStream().
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
OutputStream writer = response.getOutputStream();
:
//Write the CSV file header
//(no change from your code here.)
CSVUtils.writeLine(writer,Arrays.asList("NAME","email"));
This requires you to alter your CSVUtils class to accept an OutputStream instead of a Writer object, but there isn't much difference there...
public static void writeLine(OutputStream w, etc...) throws IOException {
:
sb.append("\n");
String str = sb.toString();
byte[] bytes = str.getBytes(Charset.forName("UTF-8"));
w.write(bytes);
}
I highly recommend using a library for CSV files, such as http://opencsv.sourceforge.net/ as they provide lots of great functionality.

Java JAX-RS 2.0 + Jersey + Jetty Security

I am building a RESTful Web Service in which I have a set of commands that should only be used by admins. Ideally I would have two ports setup, both with Server-side SSL, however one port would require client SSL. I would like to know how I could separate resources by port. Alternatively, I could have the system setup to use #RolesAllowed for each resource, In that case I would need to know how to set the role of the user (by port would be great). So far I have a http and https port setup and working. I also have all the resources setup.
It might also be good to know that the two files shown below are the only ones used to run with webservice. there are no container files etc.
keep in mind that not all code is complete. Here is the code:
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import java.io.File;
import java.io.FileNotFoundException;
public class Core {
static String jettyKeystore = "Assets/keys/keystore";
//http://www.eclipse.org/jetty/documentation/current/configuring-ssl.html
public static void main(String args[]) throws FileNotFoundException {
String keystorePath = System.getProperty(
"example.keystore", jettyKeystore);
File keyStoreFile = new File(keystorePath);
if (!keyStoreFile.exists()) {
throw new FileNotFoundException(keyStoreFile.getAbsolutePath());
}
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
int port = 8080;
int securePort = 8084;
HttpConfiguration httpConf = new HttpConfiguration();
httpConf.setSecureScheme("https");
httpConf.setSecurePort(securePort);
httpConf.setOutputBufferSize(32768);
Server jettyServer = new Server();
ServerConnector http = new ServerConnector(jettyServer,
new HttpConnectionFactory(httpConf));
http.setPort(port);
http.setIdleTimeout(30000);
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(keyStoreFile.getAbsolutePath());
sslContextFactory.setKeyStorePassword("password");
sslContextFactory.setKeyManagerPassword("password");
//sslContextFactory.setNeedClientAuth(true);
HttpConfiguration httpsConf = new HttpConfiguration(httpConf);
httpsConf.addCustomizer(new SecureRequestCustomizer());
ServerConnector https = new ServerConnector(jettyServer,
new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(httpsConf));
https.setPort(securePort);
https.setIdleTimeout(500000);
jettyServer.setConnectors(new Connector[]{http, https});
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(
org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter(
"jersey.config.server.provider.classnames",
RQHandler.class.getCanonicalName());
try {
jettyServer.start();
System.err.println("Server Started on port: " + port + "," + securePort);
jettyServer.join();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
}
Here is the resource file:
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ContentDisposition;
import java.io.*;
import java.net.UnknownHostException;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.websocket.server.PathParam;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
#Path("audio_archives")
public class RQHandler {
MongoClient mc;
DB db;
DBCollection audioCollection;
DBCollection videoCollection;
{
try {
mc = new MongoClient("localhost");
db = mc.getDB("ziondb");
audioCollection = db.getCollection("audio");
videoCollection = db.getCollection("video");
} catch (UnknownHostException e) {
e.printStackTrace();
System.out.println("exiting!");
System.exit(0);
}
}
#GET
#Path("getMedia")
#Produces(MediaType.TEXT_PLAIN)
public String getAllMedia(#QueryParam("type") String type){
String DBreturn = "";
if(type.toLowerCase().equals("audio")) {
DBCursor cursor = audioCollection.find();
try {
while (cursor.hasNext()) {
DBreturn += cursor.next();
}
} finally {
cursor.close();
}
} else if(type.toLowerCase().equals("video")) {
DBCursor cursor = videoCollection.find();
try {
while (cursor.hasNext()) {
DBreturn += cursor.next();
}
} finally {
cursor.close();
}
}
if (DBreturn.equals("")) {
DBreturn = "{ \"entries\" : \"null\" }";
}
return DBreturn;
}
#GET
#Path("getMediaFile")
#Produces({"video/mp4"}) //use application/type for downloadable file
public File getMediaFile(#QueryParam("type") String type,#QueryParam("resourceId") String id){
String DBreturn = "";
if(type.toLowerCase().equals("audio")) {
DBCursor cursor = audioCollection.find();
try {
while (cursor.hasNext()) {
DBreturn += cursor.next();
}
} finally {
cursor.close();
}
} else if(type.toLowerCase().equals("video")) {
DBCursor cursor = videoCollection.find();
try {
while (cursor.hasNext()) {
DBreturn += cursor.next();
}
} finally {
cursor.close();
}
}
if (DBreturn.equals("")) {
DBreturn = "{ \"entries\" : \"null\" }";
}
return (new File("/home/digitalblueeye/Downloads/SampleVideo_1280x720_50mb.mp4"));
}
#GET
#Path("getMediaStream")
#Produces({"video/mp4"}) //use application/type for downloadable file
public StreamingOutput getMediaStream(#QueryParam("type") String type, #QueryParam("resourceId") String id){
return new StreamingOutput() {
#Override
public void write(OutputStream outputStream) throws IOException, WebApplicationException {
File file = new File("/home/digitalblueeye/Downloads/SampleVideo_1280x720_50mb.mp4");
outputStream = new FileOutputStream(file);
outputStream.write(0);
}
};
}
//********************************************************
#GET
#Path("")
#Produces(MediaType.TEXT_HTML)
public static File home() {
return (new File("Assets/index.html"));
}
#GET
#Path("developers")
#Produces(MediaType.TEXT_HTML)
public static File sysInfo() {
return (new File("Assets/manual.html"));
}
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("list_by_date")
public String listByDate(#QueryParam("model") String model,
#QueryParam("from") String fromDate,
#QueryParam("to") String toDate,
#QueryParam("quota") String quota) {
return null;
}
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("list_by_param")
public String listByParam(#QueryParam("model") String model,
#QueryParam("param_type") String paramType,
#QueryParam("param") String param,
#QueryParam("quota") String quota) {
return null;
}
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("list_files")
public String listFile(#QueryParam("id") String id) {
return null;
}
#GET
#Produces("application/mp3,application/wav")
#Path("get_file")
public File getFile(#QueryParam("id") String id) {
return null;
}
#GET
#Produces("audio/mp3,audio/wav")
#Path("stream_file")
public File streamFile(#QueryParam("id") String id) {
return null;
}
private byte[] readFromStream(InputStream stream) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1000];
int wasRead = 0;
do {
wasRead = stream.read(buffer);
if (wasRead > 0) {
baos.write(buffer, 0, wasRead);
}
} while (wasRead > -1);
return baos.toByteArray();
}
#PUT
#Consumes(MediaType.APPLICATION_JSON)
#Path("get_auth_secret")
public void get_auth_secret(InputStream is) throws IOException {
byte[] bytes = readFromStream(is);
String input = new String(bytes);
System.out.println(input);
}
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Path("update")//update reources
public void putstuff(InputStream is) throws IOException {
byte[] bytes = readFromStream(is);
String input = new String(bytes);
System.out.println(input);
}
#DELETE
#Consumes(MediaType.APPLICATION_JSON)//use json for batch delete
#Path("delete")//delete reources
public void deletestuff(InputStream is) throws IOException {
byte[] bytes = readFromStream(is);
String input = new String(bytes);
System.out.println(input);
}
#PUT
#Consumes("application/mp3,application/wav")
#Path("create")//create resources
public void createstuff(InputStream is) throws IOException {
byte[] bytes = readFromStream(is);
String input = new String(bytes);
System.out.println(input);
}
/*
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormParam("file") InputStream fileInputStream,
#QueryParam("filename") String filename) {
String filePath = "FileStore/audio/" + filename;
// save the file to the server
saveFile(fileInputStream, filePath);
String output = "File saved to server location : " + filePath;
return Response.status(200).entity(output).build();
}
// save uploaded file to a defined location on the server
private void saveFile(InputStream uploadedInputStream,
String serverLocation) {
try {
OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
int read = 0;
byte[] bytes = new byte[1024];
outpuStream = new FileOutputStream(new File(serverLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
outpuStream.write(bytes, 0, read);
}
outpuStream.flush();
outpuStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream inputStream,
#FormDataParam("file") FormDataContentDisposition formDataContentDisposition) {
String fileName = formDataContentDisposition.getFileName();
String filePath = saveFile(inputStream, fileName);
String output = "File: " + filePath;
return Response.status(Response.Status.CREATED).entity(output).build();
}
#POST
#Path("/multi")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
FormDataMultiPart form) {
FormDataBodyPart filePart = form.getField("file");
ContentDisposition headerOfFilePart = filePart.getContentDisposition();
InputStream inputStream = filePart.getValueAs(InputStream.class);
String filePath = saveFile(inputStream, headerOfFilePart.getFileName());
String output = "File: " + filePath;
return Response.status(Response.Status.CREATED).entity(output).build();
}
private String saveFile(InputStream inputStream, String fileName) {
try {
File file = File.createTempFile("temp", ".txt");
OutputStream outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.flush();
outputStream.close();
return file.getAbsolutePath();
} catch (Exception e) {
}
return "";
}
*/
//Media streaming with JAX-RS https://github.com/aruld/jersey-streaming
}
The methods I am looking to protect are PUT, POST, and DELETE. I just want to make sure that only admins can create, update, and remove resources. Since a desktop program will be the only way to use admin methods, I am not concerned about ease of implementing the admin methods into a website.

getting HTTP Status 404 - 502.shtml The requested resource is not available.while uploading a file

I'm getting the above error while using servlet I've written. the war file is set on Tomcat ver 7.0.39 installed on cPanel. the servlet compiled and tested on local machine no problem. I've learnet that there is a problem that has something to do with the cPanel/PHP config. I tried to play with the cPanel configuration but no luck
I feel that it has nothing to do with the java code but I'll put the fileUploadServlet anyhow
EDIT: I was able to upload a very small-sized file so it has something to do with file size \ long procssing time
package servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import convertor.TextAnalayzer;
import exception.ZoharException;
import beans.ParashaBean;
import beans.UserBean;
import jdbcHandler.JDBCZhoarHandler;
import util.ParashaName;
import util.XmlUrelParaser;
#WebServlet(urlPatterns = { "/upload" }, loadOnStartup = 1)
#MultipartConfig
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 8626646959046203428L;
private JDBCZhoarHandler appHandler = new JDBCZhoarHandler();
public static final String ERROR_PARAMETER = "error";
public static final String COMMAND_PARAMETER = "command";
public static final String USER_ATTRIBUTE = "user";
public static final String HANDLER_ATTRIBUTE = "handler";
#Override
public void init() throws ServletException {
super.init();
try {
getServletConfig().getServletContext().setAttribute("list",
appHandler.viewParashot());
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String command = request.getParameter(COMMAND_PARAMETER);
String nextPage = "/login.jsp";
if ("convert".equals(command)) {
nextPage = this.upload(request, response);
} else if ("login".equals(command)) {
nextPage = this.login(request, response);
} else {
}// do nothing!!
this.getServletConfig().getServletContext()
.getRequestDispatcher(nextPage).forward(request, response);
}
private String login(HttpServletRequest request,
HttpServletResponse response) {
String name = request.getParameter("userName");
String password = request.getParameter("password");
JDBCZhoarHandler handler = new JDBCZhoarHandler();
try {
UserBean user = handler.getUser(name, password);
HttpSession session = request.getSession(true);
session.setAttribute(HANDLER_ATTRIBUTE, handler);
session.setAttribute(USER_ATTRIBUTE, user.getId());
return "/uploadFile.jsp";
} catch (Exception e) {
request.setAttribute(ERROR_PARAMETER, e.getMessage());
return "/login.jsp";
}
}
private String upload(HttpServletRequest request,
HttpServletResponse response) {
// view artifacts
HttpSession session = request.getSession(false);
ParashaName parashaName = new ParashaName();
JDBCZhoarHandler handler = (JDBCZhoarHandler) session
.getAttribute(HANDLER_ATTRIBUTE);
List<ParashaBean> list = null;
try {
list = handler.viewParashot();
} catch (SQLException e1) {
request.setAttribute(ERROR_PARAMETER, e1.getMessage());
}
session.setAttribute("list", list);
// Processing file
if ("convert".equals(request.getParameter("command"))) {
OutputStream out = null;
InputStream filecontent = null;
try {
// Create path components to save the file
XmlUrelParaser xml = new XmlUrelParaser();
SimpleDateFormat format = new SimpleDateFormat(
"dd-MM-yy_HH-mm-ss");
final Part filePart = request.getPart("file");
if (filePart.getSize() == 0) {
throw new ZoharException("you must upload a file first");
}
final String fileName = xml.getUR("incomingFilesDir")
+ session.getAttribute(USER_ATTRIBUTE)
+ parashaName.convert(Integer.parseInt(request
.getParameter("parasha")))
+ format.format(new Date()) + ".docx";
out = new FileOutputStream(new File(fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
TextAnalayzer ta = new TextAnalayzer();
Integer ID = (Integer)session.getAttribute("user");
ta.analayze(fileName,
Integer.parseInt(request.getParameter("parasha")),
Boolean.parseBoolean(request.getParameter("orginal")),
ID);
request.setAttribute(ERROR_PARAMETER, "Upload complete");
return "/uploadFile.jsp";
} catch (Exception e) {
request.setAttribute(ERROR_PARAMETER, e.getMessage());
} finally {
try {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
} catch (IOException e) {
request.setAttribute(ERROR_PARAMETER, e.getMessage());
}
}
}
return "/login.jsp";
}
}
This is a resault of memory lack. Better memory-managing code solved the problem.

Categories