What should I do to upload the file using jsp/servlet and storing in the ms-access db - file-upload

this is my productregistration.jsp I want to upload the image and want to also send the data to servlet which is ProductRegistartionServlet.java....can you help me? how it can be possible...
I have already added both jar files named as common-io and common-file-upload
<form action="/eauction/ProductRegistrationServlet" ENCTYPE="multipart/form-data" method="post">
<div class="form_row">
<label class="contact"><strong>Product Image:</strong></label>
<input type="file" class="contact_input" required="required" name="file" />
</div>
<div class="form_row">
<label class="contact"><strong>Product Name:</strong></label>
<input type="text" class="contact_input" required="required" name="p_name" />
</div>
<div class="form_row">
<label class="contact"><strong>Product Type:</strong></label>
<input type="text" class="contact_input" name="p_type" />
</div>
<div class="form_row">
<label class="contact"><strong>Product Prize:</strong></label>
<input type="text" class="contact_input" name="p_prize" required="required" />
</div>
<div class="form_row">
<label class="contact"><strong>Product:</strong></label>
<input type="text" class="contact_input" min="8" max="10" name="p_product" required="required" />
</div>
<div class="form_row">
<label class="contact"><strong>Product Details:</strong></label>
<textarea name="p_detail" class="contact_input" size="200"></textarea>
</div>
<p> </p>
<p> </p>
<div class="form_row">
<input type="image" src="images/GoDf5.gif" alt="submit form"/>
</div>
</form>
here is my servlet help me to figure out the problem please
and this is my ProductRegistrationServlet.java
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
/**
*
* #author Samkit
*/
public class ProductRegistrationServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
// ... (do your job here)
String p_name =request.getParameter("p_name");
String p_type=request.getParameter("p_type");
String p_prize=request.getParameter("p_prize");
String p_product=request.getParameter("p_product");
String p_detail=request.getParameter("p_detail");
System.out.print(p_name);
} else {
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
DataInputStream in = new DataInputStream(item.getInputStream());
// ... (do your job here)
String contentType = request.getContentType();
String saveFile="";
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while(totalBytesRead < formDataLength){
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
File ff = new File("C:/"+saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
// ...
}}
/*
Connection con = null;
ResultSet rst = null;
Statement st = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:register");
st =con.createStatement();
rst = st.executeQuery("Select * from productregisteration");
int i = st.executeUpdate("INSERT INTO productregisteration VALUES('"+ff.getPath()+"','"+p_name+"','"+p_type+"','"+p_prize+"','"+p_product+"','"+p_detail+"')");
} catch (ClassNotFoundException ex) {
Logger.getLogger(WelcomeServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch(SQLException se){
}
}
}}*/

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class ProductRegistrationServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
File savedFile = null;
PrintWriter out = response.getWriter();
String p_name="",p_type="",p_detail="",p_prize="",p_product="",itemName="",User_Name="";
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
// ... (do your job here)
if(fieldname.equals("p_type")){
p_type = fieldvalue;
}
if(fieldname.equals("p_name")){
p_name = fieldvalue;
out.println(p_name);
}
if(fieldname.equals("p_prize")){
p_prize = fieldvalue;
}
if(fieldname.equals("p_product")){
p_product = fieldvalue;
}
if(fieldname.equals("p_detail")){
p_detail = fieldvalue;
}
}
else {
itemName = item.getName();
savedFile = new File("C:\\Users\\Samkit\\Documents\\NetBeansProjects\\eauction\\web\\upload\\"+itemName);
out.println(savedFile);
item.write(savedFile);
}
}
Connection con = null;
ResultSet rst = null;
Statement st = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:register");
st=con.createStatement();
//Getting the date only
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String p_date = dateFormat.format(date);
System.out.println(p_date);
//Getting the time only
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";

Related

FlyingSaucerPdf , Greek alphabet, Helvetica

In the project, I am working on we use Flying Saucer Pdf (9.0.9) & iText (2.1.7) for the creation of pdfs. By setting the Helvetica font, the characters of the Greek alphabet are not represented on the PDF. While changing the font Arial or Times New Roman the characters are represented correctly.
<div>
<span style="font-family: Helvetica, Arial, sans-serif;">
<strong>
<span style="font-size: 16pt;">¶µαβω♥µ</span>
</strong>
</span>
</div>
Is there any workaround?
https://github.com/flyingsaucerproject/flyingsaucer
I was only able to fix it by removing the preloaded Helvetica font. After that, I added a new Helvetica font. For testing I used https://www.cufonfonts.com/download/font/helvetica-255 font.
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.Test;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.resource.FSEntityResolver;
import com.lowagie.text.pdf.BaseFont;
public class TestPdf2 {
private static final String FILE_OUT = "src/test/resources/file.pdf";
private static final String FONT_DIR = "src/test/resources/fonts/";
private static final String[] FONT_FILES = { //
"Helvetica.ttf", "Helvetica-Bold.ttf", //
"Helvetica-BoldOblique.ttf","helvetica-compressed-5871d14b6903a.otf", //
"helvetica-light-587ebe5a59211.ttf", "Helvetica-Oblique.ttf", //
"helvetica-rounded-bold-5871d05ead8de.otf" };
#Test
public void buildHelvetica() throws Exception {
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver fontRes = renderer.getFontResolver();
Field fontFagliesField = ITextFontResolver.class.getDeclaredField("_fontFamilies");
fontFagliesField.setAccessible(true);
Map<String, ?> fontFamiliesMap = (Map<String, ?>) fontFagliesField.get(fontRes);
fontFamiliesMap.remove("Helvetica");
loadFont(fontRes);
renderer.setDocument(getSampleDocument(), null);
doRenderToPDF(renderer, FILE_OUT);
}
private static void loadFont(ITextFontResolver poF) throws Exception {
for (String lsFontFile : FONT_FILES) {
File lfFile = new File(FONT_DIR + lsFontFile);
poF.addFont(lfFile.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}
}
private static void doRenderToPDF(ITextRenderer renderer, String pdf) throws Exception {
try (OutputStream os = new FileOutputStream(pdf)) {
renderer.layout();
renderer.createPDF(os);
}
}
private static Document getSampleDocument() throws Exception {
String lsSampleGreekDoc = //
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">" //
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n" //
+ "<head>\r\n" //
+ "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\r\n" //
+ "<title>Test</title>\r\n"//
+ "</head>\r\n" //
+ "<body>\r\n" //
+ "<div style=\"font-family: Helvetica; font-size: 16pt;\">\r\n" //
+ " <del>Helvetica:</del>1¶ 2µ 3α 4β 5δ 6ε " //
+ "7ζ 8ω 9♥ 10µ 11Θ 12Ξ 13Σ\r\n" //
+ "</div>\r\n" //
+ "</body>\r\n" //
+ "</html>"; //
DocumentBuilder loDocumentBuilderXml = DocumentBuilderFactory.
newInstance().newDocumentBuilder();
loDocumentBuilderXml.setEntityResolver(FSEntityResolver.instance());
ByteArrayInputStream loArrayInputStream = new ByteArrayInputStream(lsSampleGreekDoc.getBytes(StandardCharsets.UTF_8));
return loDocumentBuilderXml.parse(loArrayInputStream);
}
}

Handling multiple submit buttons with JSP and Servlets

I have a table that is generated from the database. This table will be enclosed in a form. Below is the result on a browser:
http://i.imgur.com/NLZzgwP.png (Low rep problems)
Below is the JSP/JSTL code:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Issues</title>
<style type="text/css">
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
td {
padding: 10px;
}
</style>
</head>
<body>
<sql:setDataSource
var="myDS"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/pdfdb"
user="user" password="*******"
/>
<sql:query var="listIssues" dataSource="${myDS}">
SELECT BookId from Book;
</sql:query>
<form method="get" action="fileDownload">
<div align="center">
<table>
<caption>List of Issues</caption>
<tr>
<th>Magazine Issue #</th>
<th>Download</th>
</tr>
<c:forEach var="issue" items="${listIssues.rows}">
<tr>
<td><c:out value="${issue.BookId}" /></td>
<td><input name='<c:out value="${issue.BookId}" />' type="submit" value="Download"></td>
</tr>
</c:forEach>
</table>
</div>
</form>
</body>
</html>
Now, what I want is for the download button to be kind of linked with the id/Issue number that is placed on the same row as the button such that, when the user clicks the download button, it passes the id/magazine issue number to the url telling the browser that the user wants to download the corresponding magazine issue number of that button clicked. Below is the servlet I use to implement this:
package com.mypackage.fileDownload;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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;
/**
* Servlet implementation class FileDownloadServlet
*/
#WebServlet("/fileDownload")
public class FileDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//size of byte buffer to send file
private static final int BUFFER_SIZE = 4096;
//database connection settings
private String dbUrl = "jdbc:mysql://localhost:3306/pdfdb";
private String dbUser = "user";
private String dbPass = "******";
/**
* #see HttpServlet#doGet(HttpServletRequesrequest,HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get upload id from URL's parameters
String uploadId = request.getParameter("name");
Connection con = null; //connects to the database
try {
//connects to the database
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbUrl, dbUser, dbPass);
//queries the database
String sql = "SELECT * FROM Book WHERE BookId = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, uploadId);
ResultSet result = pstmt.executeQuery();
if(result.next()) {
//gets file name and file blob data
String fileId = result.getString("BookId");
Blob blob = result.getBlob("BookContent");
InputStream inputStream = blob.getBinaryStream();
int fileLength = inputStream.available();
System.out.println("File length = " + fileLength);
ServletContext context = getServletContext();
//Sets MIME type for the file download
String mimeType = context.getMimeType(fileId);
if(mimeType == null) {
mimeType = "application/octet-stream";
}
//set content properties and header attributes for the response
response.setContentType(mimeType);
response.setContentLength(fileLength);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileId);
response.setHeader(headerKey, headerValue);
//writes the file to the client
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
} else {
//no file found
response.getWriter().print("File not found for the id: " + uploadId);
}
} catch(SQLException ex) {
ex.printStackTrace();
response.getWriter().print("SQL Error: " + ex.getMessage());
} catch(IOException ex) {
ex.printStackTrace();
response.getWriter().print("IO Error: " + ex.getMessage());
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
response.getWriter().print("Class Missing Error: " + ex.getMessage());
}
finally {
if(con != null) {
//closes the database connection
try {
con.close();
} catch(SQLException ex) {
ex.printStackTrace();
}
}
}
}
}
Well, from the way I have done this, it is not working the way I wanted it to. For example, if you run this code on the server and click any of the download buttons, the url will be something like
issue.jsp?1=Download
which is weird.It will also display on the browser
File not found for the id: null
I expect something like(on the url)
issue.jsp?Download=1
where 1 is the issue being downloaded. My database has two columns: the IssueId and fileContent(content of file stored in BLOB).
I think I have explained enough and the concept is clear. Any help will be appreciated and this is as far as I could go with my code & research. Thanks!
The simplest way is to just move the form inside the table and do multiple forms:
<div align="center">
<table>
<caption>List of Issues</caption>
<tr>
<th>Magazine Issue #</th>
<th>Download</th>
</tr>
<c:forEach var="issue" items="${listIssues.rows}">
<tr>
<td><c:out value="${issue.BookId}" /></td>
<td>
<form method="get" action="fileDownload">
<input type='hidden' name='bookid' value='<c:out value="${issue.BookId}" />' />
<input type="submit" value="Download">
</form>
</td>
</tr>
</c:forEach>
</table>
</div>
You also need to move the value out of the name attribute of the button and into the value attribute of a hidden input. That hidden input needs a name you will use to get the value in the servlet: request.getParameter("bookid");

Face Detection Null Pointer Exception

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.highgui.VideoCapture;
import org.opencv.objdetect.CascadeClassifier;
public class WebCam extends JPanel implements ActionListener{
private BufferedImage image;
public JButton button = new JButton("capture");
int count = 1;
public WebCam() {
super();
button.addActionListener((ActionListener) this);
this.add(button);
}
public BufferedImage getImage() {
return image;
}
public void setimage(BufferedImage newimage) {
image = newimage;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.image == null) {
return;
}
g.drawImage(this.image, 0, 0, this.image.getWidth(), this.image.getHeight(), null);
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("face capture");
frame.setSize(300,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
CascadeClassifier faceDetector = new CascadeClassifier("C:\\opencv\\sources\\data\\lbpcascades\\lbpcascade_frontalface.xml");
WebCam anan = new WebCam();
frame.add(anan);
frame.setVisible(true);
Mat webcam_image = new Mat();
MatToBufImg mat2Buf = new MatToBufImg();
VideoCapture capture = null;
try {
capture = new VideoCapture(0);
}
catch (Exception e){
}
if (capture.open(0)) {
while (true) {
capture.read(webcam_image);
if (!webcam_image.empty()) {
frame.setSize(webcam_image.width(), webcam_image.height());
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(webcam_image, faceDetections);
for (Rect rect : faceDetections.toArray()) {
Core.rectangle(webcam_image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));// mat2Buf, mat2Buf);
}
System.out.println("...............face detected: " + faceDetections.toArray().length);
if (faceDetections.toArray().length == 0) {
System.out.println("Face not detected!");
}
mat2Buf.setMatrix(webcam_image, ".jpg");
anan.setimage(mat2Buf.getBufferedImage());
anan.repaint();
}
else {
System.out.println("problem");
}
}
}
capture.release();
}
#Override
public void actionPerformed(ActionEvent e){
System.out.println("hellohellohellohellohello");
int width = 943;
int height = 640;
BufferedImage image = null;
File f = null;
String ans = JOptionPane.showInputDialog(null, "Color/Grey");
System.out.println(ans);
BufferedImage bi = image;
ImageIcon ii = null;
Image newimg = bi.getScaledInstance(320, 220, java.awt.Image.SCALE_SMOOTH);
ii = new ImageIcon(newimg);
Image i2 = ii.getImage();
image = new BufferedImage(i2.getWidth(null), i2.getHeight(null), BufferedImage.SCALE_SMOOTH);
image.getGraphics().drawImage(i2, 0, 0, null);
RenderedImage resim = null;
if (i2 instanceof RenderedImage) {
resim = (RenderedImage) i2;
} else {
BufferedImage anlikResim = null;
if (!ans.equalsIgnoreCase("color")) {
anlikResim = new BufferedImage(
ii.getIconWidth(),
ii.getIconHeight(),
BufferedImage.TYPE_BYTE_GRAY);
} else {
anlikResim = new BufferedImage(
ii.getIconWidth(),
ii.getIconHeight(),
BufferedImage.SCALE_SMOOTH);
}
Graphics2D g = anlikResim.createGraphics();
g.drawImage(i2, 0, 0, null);
g.dispose();
resim = anlikResim;
}
try {
f = new File("C:\\opencv\\build\\java\\x64\\");
ImageIO.write(resim, "jpg", f);
System.out.println("yes");
} catch (Exception ex) {
}
}
}
I am working on a face detection project. It used to work perfectly fine but suddenly ceased to work properly. When I run the program it gives a NullPointerException at line 120. How can I fix this problem?

JAX RS file upload

I am trying to set up file upload example using JAX RS. I could set up the project when the client is a JSP page and there are no issues. But i would like to have the client as a java class which sends post request to the service. My server side code is as shown below.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
#Path("/file")
public class UploadFileService {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "d://uploaded/"
+ fileDetail.getFileName();
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(
uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The client as a JSP page is as shown below.
<html>
<body>
<h1>File Upload with Jersey</h1>
<form action="http://localhost:9090/RESTfulExample/rest/file/upload" method="post" enctype="multipart/form-data">
<p>
Select a file : <input type="file" name="file" size="45" />
</p>
<input type="submit" value="Upload It" />
</form>
</body>
</html>
Can someone please help me with a class file as a client?
You can use Apache's httpclient and httpmime to accomplish this:
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
public class Uploader {
public void uploadFile(String endpoint, File file) throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(endpoint);
FileBody uploadFilePart = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", uploadFilePart);
httpPost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httpPost);
//Check response for success
}
}
Which works with your sample server code. See this question, as well.

Is there any way to configure jms transport for axis2 client programatically?

I know how to configure jms transport within axis2.xml, but i need to configure it with my specific application properties that could be changed in runtime.
I found solution, hope it will be helpful
package com.mycompany.client.config;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.naming.Context;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNode;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.description.ParameterInclude;
import org.apache.axis2.description.TransportInDescription;
import org.apache.axis2.description.TransportOutDescription;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.transport.TransportListener;
import org.apache.axis2.transport.TransportSender;
import org.apache.axis2.transport.jms.JMSConstants;
import org.apache.axis2.transport.jms.JMSListener;
import org.apache.axis2.transport.jms.JMSSender;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.mycompany.client.config.exceptions.ConfigurationException;
import com.mycompany.client.jms.JMSWebServiceClient;
import com.mycompany.stub.FtthRequestStub;
public class ConfigurationManager {
static Log log = LogFactory.getLog(ConfigurationManager.class);
private static final String DEFAULT_TRANSPORT_PARAMETER_NAME = "default";
public JMSWebServiceClient configureJMSClient() throws Exception {
FtthRequestStub stub;
ConfigurationContext ctx;
boolean isAuthenticationEnabled = false;
Map<String,String> jmsTransportProps = getAxisTransportConfiguration(isAuthenticationEnabled);
String url = buildUrlFromMap(jmsTransportProps);
ctx = ConfigurationContextFactory.createDefaultConfigurationContext();
//transport in
TransportListener tl = new JMSListener();
TransportInDescription transportIn = new TransportInDescription("jms");
addParameterToTransport(jmsTransportProps,transportIn);
transportIn.setReceiver(tl);
// transport out
TransportSender transportSender = new JMSSender();
TransportOutDescription transportOut = new TransportOutDescription("jms");
addParameterToTransport(jmsTransportProps, transportOut);
transportOut.setSender(transportSender);
transportSender.init(ctx, transportOut); //very important call because transport senders are not initialized during createDefaultConfigurationContext() invocation.
AxisConfiguration axisConfiguration = ctx.getAxisConfiguration();
axisConfiguration.addTransportIn(transportIn);
axisConfiguration.addTransportOut(transportOut);
stub = new FtthRequestStub(ctx,url);
String replyTo = getReplyDestination();
if(StringUtils.isNotEmpty(replyTo)) {
stub._getServiceClient().getServiceContext().setProperty(JMSConstants.JMS_REPLY_TO, replyTo);
}
JMSWebServiceClient client = new JMSWebServiceClient(stub);
return client;
}
private void addParameterToTransport(Map<String,String> jmsTransportProps,
ParameterInclude transportInOut) throws ConfigurationException {
try {
Parameter parameter = new Parameter();
parameter.setName(DEFAULT_TRANSPORT_PARAMETER_NAME);
parameter.setValue(buildParameterOMElementFromMap(DEFAULT_TRANSPORT_PARAMETER_NAME, jmsTransportProps, false));
transportInOut.addParameter(parameter);
} catch (AxisFault e) {
throw new ConfigurationException(e.getMessage());
}
}
private static OMElement createRootParameterOMElement(String name) {
OMFactory omFactory = OMAbstractFactory.getOMFactory();
OMElement defaultReceiverParameter = omFactory.createOMElement(new javax.xml.namespace.QName("parameter"));
OMAttribute nameAttribute = omFactory.createOMAttribute("name", null, name);
defaultReceiverParameter.addAttribute(nameAttribute);
return defaultReceiverParameter;
}
private static OMElement buildParameterOMElementFromMap(String rootElementName, Map<String,String> properties, boolean rootIsLocked) {
OMFactory omFactory = OMAbstractFactory.getOMFactory();
//creating root <parameter>
OMElement root = omFactory.createOMElement(new javax.xml.namespace.QName("parameter"));
OMAttribute attribute = omFactory.createOMAttribute("name", null, rootElementName);
root.addAttribute(attribute);
attribute = omFactory.createOMAttribute("locked", null, String.valueOf(rootIsLocked));
root.addAttribute(attribute);
//creating child <parameter> elements
for(String key : properties.keySet())
{
OMElement child = omFactory.createOMElement(new javax.xml.namespace.QName("parameter"));
attribute = omFactory.createOMAttribute("name", null, key);
child.addAttribute(attribute);
attribute = omFactory.createOMAttribute("locked", null, Boolean.FALSE.toString());
child.addAttribute(attribute);
OMNode text = omFactory.createOMText(properties.get(key));
child.addChild(text);
root.addChild(child);
}
return root;
}
private static String buildUrlFromMap(Map<String,String> properties) {
StringBuffer url = new StringBuffer();
url.append(JMSConstants.JMS_PREFIX);
url.append(getDestination()).append("?"); //send destination
for(String key : properties.keySet()) {
url.append(key).append("=").append(properties.get(key)).append("&");
}
return StringUtils.chop(url.toString());
}
private static String getDestination() {
return "testQueue";
}
private static String getReplyDestination() {
return "replyQueue";
}
private Map<String,String> getAxisTransportConfiguration(boolean authenticationEnabled) {
Map<String,String> properties = new HashMap<String,String>();
properties.put(JMSConstants.PARAM_CONFAC_JNDI_NAME, "QueueConnectionFactory");
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
properties.put(Context.PROVIDER_URL, "tcp://localhost:61616");
if(authenticationEnabled) {
properties.put(JMSConstants.PARAM_JMS_USERNAME, "username");
properties.put(JMSConstants.PARAM_JMS_PASSWORD, "password");
}
return properties;
}
}