This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have a Servlet that uploads an image, and saves the path in a MySQL db. I use the same code for another image upload on a different jsp page, and I get a null pointer exception on "getFileName();"
I do not see any difference in this code. Please help:
addlientimage.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("clientname");
String id = request.getParameter("clientid");
String password = request.getParameter("clientpassword");
String email = request.getParameter("clientemail");
final String path = getServletContext().getRealPath("/imgs");
final Part filePart = request.getPart("imageurl");
final String fileName = getFileName(filePart);
String url = "imgs/" + fileName;
OutputStream outStream;
outStream = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
response.sendRedirect("clients.jsp");
try {
outStream = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
outStream.write(bytes, 0, read);
}
Mysqlconnector dbconnect = new Mysqlconnector();
/* TODO output your page here. You may use following sample code. */
try (PreparedStatement clientinfo = dbconnect.getConnection().prepareStatement("INSERT INTO clients VALUES ( ?, ?, ?, ?, ? )")) {
clientinfo.setString(1, id);
//setting the first placeholder to the password recieved from the client
clientinfo.setString(2, password);
clientinfo.setString(3, name);
clientinfo.setString(4, url);
clientinfo.setString(5, email);
clientinfo.executeUpdate();
String clients = new PopulateClientsTable().getClientRows();
HttpSession session = request.getSession();
session.setAttribute("clients", clients);
}
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());
} finally {
if (outStream != null) {
outStream.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
addmanager.java
response.setContentType("text/html;charset=UTF-8");
String personName = request.getParameter("mediapersonname");
String productName = request.getParameter("productname");
String mediainfoid = request.getParameter("mediainfoid");
String mediaAbout = request.getParameter("mediaabout");
String personAbout = request.getParameter("personabout");
String productAbout = request.getParameter("productabout");
final String path = getServletContext().getRealPath("/imgs");
final Part filePart = request.getPart("personurl");
final String fileName = getFileName(filePart);
String url = "imgs/" + fileName;
OutputStream outStream;
outStream = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
response.sendRedirect("adminmediainfo.jsp");
try {
outStream = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
outStream.write(bytes, 0, read);
}
Mysqlconnector dbconnect = new Mysqlconnector();
/* TODO output your page here. You may use following sample code. */
try (PreparedStatement clientinfo = dbconnect.getConnection().prepareStatement("INSERT INTO mediainfo VALUES ( ?, ?, ?, ?, ?, ?, ? )")) {
//setting the first placeholder to the password recieved from the client
clientinfo.setString(1, mediainfoid);
clientinfo.setString(2, mediaAbout);
clientinfo.setString(3, personName);
clientinfo.setString(4, productName);
clientinfo.setString(5, productAbout);
clientinfo.setString(6, personAbout);
clientinfo.setString(7, url);
clientinfo.executeUpdate();
String clients = new PopulateMediaInfoTable().getClientRows();
HttpSession session = request.getSession();
session.setAttribute("mediainfo", clients);
}
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());
} finally {
if (outStream != null) {
outStream.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
The code for addclientimage.java works. The code for addmanager.java does not.
ERROR LOG
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
AddMediaInfo.getFileName(AddMediaInfo.java:115)
AddMediaInfo.processRequest(AddMediaInfo.java:53)
AddMediaInfo.doPost(AddMediaInfo.java:158)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.15 logs.
I find just two possible reasons for getFileName to throw a NPE:
final String partHeader = part.getHeader("content-disposition");
for (String content : part.getHeader("content-disposition").split(";")) {
Either part is null, so you have to ensure that the caller method is not passing a null to getFileName. I.E.: There exists a "personurl" part within the input request.
Wither partHeader is null, so you have to ensure that the client is actually including a "content-disposition" header within the sent request.
Related
I'm trying to add blob data in a zip file. But files are getting corrupted while adding to a zip file. Below code executes, but not zipping the files:
public class BlobDataExtract {
static ZipOutputStream zos = null;
private static ZipOutputStream zosFile;
private static ZipOutputStream zipExtract() throws ClassNotFoundException, SQLException, IOException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, "user", "password");
String sql = "SELECT ORIG_NM,DOC_EXT_NM,DOC_INDX_NB,DOC_BO FROM zgdt099_document";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
java.sql.Blob docBlob = null;
DocumentTO dto = null;
List<DocumentTO> test = new ArrayList<DocumentTO>();
while (rs.next()) {
dto = new DocumentTO();
dto.setDocIndxNb(new Long(rs.getLong(AmpoDBConstants.DOC_INDX_NB)));
dto.setOrigNm(rs.getString(AmpoDBConstants.D_ORIG_NM));
dto.setDocExtNm(rs.getString(AmpoDBConstants.D_DOC_EXT_NM));
docBlob = rs.getBlob(AmpoDBConstants.D_DOC_BO);
// String filepathzipped =rs.getString(AmpoDBConstants.D_ORIG_NM) + ".zip";
InputStream blobStream = docBlob.getBinaryStream();
byte[] newFile = new byte[(int) docBlob.length()];
blobStream.read(newFile);
blobStream.close();
String contentType = "";
String extName = dto.getDocExtNm();
if ("pdf".equalsIgnoreCase(extName))
contentType = "application/pdf";
else if ("html".equalsIgnoreCase(extName) || "htm".equalsIgnoreCase(extName)
|| "stm".equalsIgnoreCase(extName) || "jpeg".equalsIgnoreCase(extName)
|| "jpg".equalsIgnoreCase(extName) || "bmp".equalsIgnoreCase(extName)
|| "gif".equalsIgnoreCase(extName))
contentType = "text/html";
else if ("xls".equalsIgnoreCase(extName) || "xla".equalsIgnoreCase(extName)
|| "xlc".equalsIgnoreCase(extName) || "xlm".equalsIgnoreCase(extName)
|| "xlw".equalsIgnoreCase(extName) || "csv".equalsIgnoreCase(extName)
|| "xlt".equalsIgnoreCase(extName))
contentType = "application/vnd.ms-excel";
else if ("doc".equalsIgnoreCase(extName) || "rtf".equalsIgnoreCase(extName)
|| "rtx".equalsIgnoreCase(extName))
contentType = "application/msword";
else if ("ppt".equalsIgnoreCase(extName) || "pps".equalsIgnoreCase(extName))
contentType = "application/vnd.ms-powerpoint";
else if ("mpp".equalsIgnoreCase(extName))
contentType = "application/vnd.ms-project";
else if ("txt".equalsIgnoreCase(extName))
contentType = "text/plain";
else if ("zip".equalsIgnoreCase(extName))
contentType = "application/zip";
else if ("ics".equalsIgnoreCase(extName))
contentType = "text/calendar";
else if ("snp".equalsIgnoreCase(extName))
contentType = "application/octet-stream";
else
contentType = "text/html";
FileContent fileCont = new FileContent(dto.getOrigNm(), newFile, contentType);
System.out.println("fileCont-->" + fileCont);
dto.setDocBO(fileCont);
test.add(dto);
try {
File file = new File(filePath);
FileOutputStream fos = new FileOutputStream("C:/Users/user/Desktop/test.zip");
zos = new ZipOutputStream(fos);
zos.putNextEntry(new ZipEntry(dto.getDocBO().getFullName()));
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
zos.write(bytes, 0, bytes.length);
} catch (FileNotFoundException ex) {
System.err.println("A file does not exist: " + ex);
} catch (IOException ex) {
System.err.println("I/O error: " + ex);
}
zos.closeEntry();
zos.close();
}
return zos;
}
}
Please help in modifying this code
Your code seems overly complex. It can be reduced to:
public class BlobDataExtract {
private static void zipExtract() throws SQLException, IOException {
String sql = "SELECT ORIG_NM,DOC_EXT_NM,DOC_INDX_NB,DOC_BO FROM zgdt099_document";
try (
Connection conn = DriverManager.getConnection("url", "user", "password");
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("C:/Users/user/Desktop/test.zip"));
) {
while (rs.next()) {
zos.putNextEntry(new ZipEntry(rs.getString(AmpoDBConstants.D_ORIG_NM)));
zos.write(rs.getBytes(AmpoDBConstants.D_DOC_BO));
}
}
}
}
Issue is resolved with the below code,
public class BlobDataExtract {
static ZipOutputStream zos =null;
static String url = "jdbc:oracle:thin:#hostname:1521:SID";
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, "user", "password");
String sql="select Blob_Data,ORIG_NM from table";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
byte[] docBlob = null;
String filename = null;
FileOutputStream fos = new FileOutputStream("C:/Users/test.zip");
zos = new ZipOutputStream(fos);
while (rs.next()) {
docBlob = rs.getBytes("Blob_Data");
filename = rs.getString("ORIG_NM");
try {
zos.putNextEntry(new ZipEntry(filename));
zos.write(docBlob, 0, Blob_Data.length);
}
catch (FileNotFoundException ex) {
System.err.println("A file does not exist: " + ex);
} catch (IOException ex) {
System.err.println("I/O error: " + ex);
}
zos.closeEntry();
}
}
}
I want to make a program that downloads some files that are needed to run a gain. It's like a launcher that automatically downloads updates. This is the enum I have:
public class Configuration {
public enum downloadFiles {
load1 ("load1.png", "https://dl.dropboxusercontent.com/u/51947680/Xenolith/load1.png"),
load2 ("load2.png", "https://dl.dropboxusercontent.com/u/51947680/Xenolith/load2.png"),
load3 ("load3.png", "https://dl.dropboxusercontent.com/u/51947680/Xenolith/load3.png");
public String fileName, URL;
private downloadFiles(String fileName, String URL) {
this.fileName = fileName;
this.URL = URL;
}
public String getFileName() {
return fileName;
}
public String getURL() {
return URL;
}
}
}
I also have a class that downloads the files, which is:
public class DownloadUtility {
private static final int BUFFER_SIZE = 4096;
/**
* Downloads a file from a URL
* #param fileURL HTTP URL of the file to be downloaded
* #param saveDir path of the directory to save the file
* #throws IOException
*/
public static void downloadFile(String fileName, String fileURL)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = System.getProperty("user.home") + "/Desktop" + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
}
So what I want to do is that the downloadFiles method downloads all the files in the enum sequentially. Btw is this a good way of doing this? If there is a better way, can you please tell me, because I'm trying to learn to code java in a neat way.
You can do the following:
for(Configuration.downloadFiles df : Configuration.downloadFiles.values()){
DownloadUtility.downloadFile(df.getFileName(), df.getURL());
}
I am trying to to download the report generated in server to the local machine for that i have written a servlet and calling the servelt from my jsp. But its not ont invoking my servlet... i have added some S.O.P for testing and i am not getting those s.o.ps in log and and the screen display blank.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
System.out.println("In RRR DownLoadServlet");
outs = response.getOutputStream();
String action = request.getParameter("action");
String strInfodom = "DMINFO88";
//String filename = request.getParameter("filename");
String filename = "/Report_Income Statement.xls";
if (action.equals("6")) {
Vector<String> vProperties = new Vector<String>();
vProperties.addElement("DOCUMENT_UPLOAD_SAVE");
vProperties.addElement("DOCUMENT_UPLOAD_TEMP");
// Properties prop = SMSServices.getConfiguration(vProperties);
// String strUploadSave = (String) prop.get("DOCUMENT_UPLOAD_SAVE");
// String strUploadTemp = (String) prop.get("DOCUMENT_UPLOAD_TEMP");
String completePath = RRRConstants.RRR_PATH+RRRConstants.OUTPUT;
System.out.println("Report File path :::::::::::::::: "+completePath);
if (completePath != null) {
byte arrByte[] = new byte[1024];
int readBytes = -1;
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment; filename=" + completePath.substring(completePath.lastIndexOf("/") + 1));
fin = new FileInputStream(new File(completePath));
BufferedInputStream bout = new BufferedInputStream(fin);
while ((readBytes = bout.read(arrByte)) > 0) {
outs.write(arrByte, 0, readBytes);
}
outs.flush();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (outs != null)
outs.close();
if (fin != null)
fin.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
jsp code :
<%
String infodom = request.getParameter("infodom");
String user = (String) session.getAttribute("gsUsrID");
String strURL = "";
FileHandler objFileHandler = new FileHandler(null);
WebServerInfo objWebServer = objFileHandler.getPrimaryWebServerInfo();
String protocol = objWebServer.getServletProtocol();
try
{
strURL = protocol+ "://" + getServletConfig().getServletContext().getInitParameter("FIC_WEBSERVER_IP") + ":" + getServletConfig().getServletContext().getInitParameter("FIC_WEBSERVER_PORT") + request.getContextPath() + "/RRRDownLoadServlet?infodom="+infodom+"&filename=";
}
catch(Exception e)
{
System.out.println(" [Download.jsp] Exception "+e);
}
%>
function downloareport()
{
alert("downloading");
var filename = "/Report_Income Statement.xls";
downloadExcel(filename);
}
function downloadExcel(excelFile)
{
window.location.href = "<%=strURL%>"+ excelFile+"&mode=excel";
}
The jsp code contains some javascript. Check these points:
In javascript; writing just function body doesn't automatically invoke that, one has to make call to the function somewhere.
Also tags for java-scripts seems missing.
The request from the JSP is get, not post. Use doGet(...){} instead of doPost(...){...} in servlet.
I'm trying here to add a specific dialog bean for action on Alfresco Explorer that supposed to download a specific docx file. The code is working fine when I hit the download action, it downloads the file but as mentioned in my question title, the file size is 0 bytes.
I'm using this to do that:
public class NewFormDialog extends BaseDialogBean {
protected String aspect;
protected String finishImpl(FacesContext context, String outcome)
throws Exception {
download(aspect);
// // get the space the action will apply to
// NodeRef nodeRef = this.browseBean.getActionSpace().getNodeRef();
//
// // resolve the fully qualified aspect name
// QName aspectToAdd = Repository.resolveToQName(this.aspect);
//
// // add the aspect to the space
// getNodeService().addAspect(nodeRef, aspectToAdd, null);
//
// // return the default outcome
return outcome;
}
public boolean getFinishButtonDisabled() {
return false;
}
public String getFinishButtonLabel() {
return "Download";
}
public void download(String pAspect) throws ServletException, IOException {
String filename = pAspect;
String filepath = "\\";
BufferedInputStream buf = null;
ServletOutputStream myOut = null;
try {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc
.getExternalContext().getResponse();
myOut = response.getOutputStream();
File myfile = new File(filepath + filename);
// set response headers
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename="
+ filename);
response.setContentLength((int) myfile.length());
FileInputStream input = new FileInputStream(myfile);
buf = new BufferedInputStream(input);
int readBytes = 0;
// read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
myOut.write(readBytes);
myOut.flush();
response.flushBuffer();
} catch (IOException ioe) {
throw new ServletException(ioe.getMessage());
} finally {
// close the input/output streams
if (myOut != null)
myOut.close();
if (buf != null)
buf.close();
FacesContext.getCurrentInstance().responseComplete();
}
}
public String getAspect() {
return aspect;
}
public void setAspect(String aspect) {
this.aspect = aspect;
}
}
I tried every solution that I found by none works.
Thank you in advance.
The File.length() method returns 0 if the file does not exist. Check to make sure that the file exists.
Tip: The Apache Commons IO library simplifies many I/O related tasks. For example, the following code snippet streams the contents of a file to the servlet response:
HttpServletResponse response = ...
File myfile = ...
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(myfile);
out = response.getOutputStream();
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in); //checks for null
IOUtils.closeQuietly(out); //checks for null
}
I wrote this HttpRequest method, but for some reason it always goes to 404 Not Found, even though the file location exists when the java process isn't running.
import java.io.*;
import java.net.*;
import java.util.*;
final class HttpRequest implements Runnable {
final static String CRLF = "\r\n";
Socket socket;
// Constructor
public HttpRequest(Socket socket) throws Exception {
this.socket = socket;
}
// Implement the run() method of the Runnable interface.
public void run() {
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private static void sendBytes(FileInputStream fis, OutputStream os)
throws Exception {
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while((bytes = fis.read(buffer)) != -1 ) {
os.write(buffer, 0, bytes);
}
}
private static String contentType(String fileName) {
if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
return "text/html";
}
if(fileName.endsWith(".jpeg") || fileName.endsWith(".jpg")) {
return "image/jpeg";
}
if(fileName.endsWith(".gif")) {
return "image/gif";
}
return "application/octet-stream";
}
private void processRequest() throws Exception {
// Get a reference to the socket's input and output streams.
InputStream is = socket.getInputStream();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
// Set up input stream filters.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// Get the request line of the HTTP request message.
String requestLine = new String(br.readLine());
// Display the request line.
System.out.println();
System.out.println(requestLine);
// Get and display the header lines.
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
// Extract the filename from the request line.
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken(); // skip over the method, which should be "GET"
String fileName = tokens.nextToken();
// Prepend a "." so that file request is within the current directory.
fileName = "." + fileName;
// Open the requested file.
FileInputStream fis = null;
boolean fileExists = true;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
// Construct the response message.
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine = "200 OK" + CRLF;
contentTypeLine = "Content-type: " +
contentType( fileName ) + CRLF;
} else {
statusLine = "404 NOT FOUND" + CRLF;
contentTypeLine = "Content Not Found!" + CRLF;
entityBody = "<HTML>" +
"<HEAD><TITLE>Not Found</TITLE></HEAD>" +
"<BODY>Not Found</BODY></HTML>";
}
// Send the status line.
os.writeBytes(statusLine);
// Send the content type line.
os.writeBytes(contentTypeLine);
// Send a blank line to indicate the end of the header lines.
os.writeBytes(CRLF);
// Send the entity body.
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes("File DNE: Content Not Found!");
}
// Close streams and socket.
os.close();
br.close();
socket.close();
}
}
Any help would be greatly appreciated...I feel like it's something simple I'm missing.
I ran your code; it works fine (except for some minor issues with not printing the headers correctly, which every browser I've tried is willing to completely ignore).
Are you sure your working directory is where you expect? Try changing the 404 message to something like:
contentTypeLine = "Content Not Found: " + new File(fileName).getAbsolutePath() + CRLF;
For reference, I ran it with a test harness of:
public static void main(String[] args) throws Exception {
final ServerSocket ss = new ServerSocket(8080);
while (true)
new HttpRequest(ss.accept()).run();
}