Consuming both MULTIPART_FORM_DATA and APPLICATION_JSON in same webservice java - java

This is my code that saves image in directory:
#POST
#Path("/imagestore")
#Consumes(MediaType.MULTIPART_FORM_DATA)
// #Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public JSONObject uploadFile(#FormDataParam("file") InputStream file) {
String dirPath = servletContext.getContextPath()+"/images";
File imagesDir = new File(dirPath);
boolean dirCreated = true;
if (!imagesDir.exists()) {
try {
dirCreated = imagesDir.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
}
if (dirCreated) {
String filePath = dirPath + "/1.jpg";
JSONObject obj = new JSONObject();
// save the file to the server
try {
File newFile = new File(filePath);
boolean fileCreated = true;
if (!newFile.exists()) {
fileCreated = newFile.createNewFile();
}
if (fileCreated) {
FileOutputStream outpuStream = new FileOutputStream(newFile);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = file.read(bytes)) != -1) {
outpuStream.write(bytes, 0, read);
}
outpuStream.flush();
outpuStream.close();
}
} catch (IOException e) {
try {
obj.put("error", e.getMessage());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
String output = "File saved to server location : " + filePath;
try {
obj.put("output", output);
return obj;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
return obj;
}
Now this works perfectly but i also need to save data to database and for that i need to consume Json data as well but i don't know how to do both these things are the same time because you can only write one consumes.
In Simple words i want to consume both json (containing user info) and Mulipart_form_data (containing image to upload on server) . So how do i do it.I'll appreciate the help :)

Related

JAX-RS upload file via WebService

I've implemented a REST webservice for uploading a file to my server:
#Path("/upload")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_XML)
public javax.ws.rs.core.Response uploadNewAdvJson(#FormDataParam("file") InputStream is) {
boolean res = true;
OutputStream out = null;
try {
File directory = new File("myFolder");
if (!directory.exists()) {
directory.mkdirs();
}
out = new FileOutputStream(new File("myFolder" + File.separator + "myFile.png"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
res = false;
if (out != null) {
try {
out.close();
out.flush();
} catch (IOException e1) {
// do nothing
}
}
}
return new Response();
}
(where Response is my JAXB response Object).
I'm testing this service with this client:
public class Test {
public static void main(String[] args) {
final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
final FileDataBodyPart filePart = new FileDataBodyPart("file", new File("pathToImage/imgToUpload.png");
FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart.field("foo", "bar").bodyPart(filePart);
final WebTarget target = client.target("http://localhost:8080/myServer/rest/uploadNewAdv");
final Response response = target.request().post(Entity.entity(multipart, multipart.getMediaType()));
try {
formDataMultiPart.close();
multipart.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
But it doesn't work as i expect. In fact, a myFile.png is created and saved, but has different size than imageToUpload.png and i can't open it as an image (looks like a corrupted file).
What's wrong?

Using Java ByteArrayInputStream with File

I have this code:
public void uploadToFTP(File file) {
try {
final ByteArrayInputStream stream = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
String date = dateFormat.format(new Date());
String filename = date.replaceAll(":", "-");
sessionFactory.getSession().write(stream, "dir/" + filename + ".txt");
} catch (IOException e) {
e.printStackTrace();
}
}
The parameter I got in this case File I want to upload to some FTP, but the problem each time I do this the file actually is empty. When I try for example final ByteArrayInputStream stream = new ByteArrayInputStream("Text here".getBytes()); it is working fine, and stores the information inside the file, what could be the problem here, may I have problem maybe with converting the File to bytes or ?
Use thsi code :
public List<ProcessedFile> uploadFTPFilesByCridational(List<ProcessedFile> processedFiles, String sourceDir,
String destinationPath, String hostName, String userName, String password, String portNo, String extation,
int fileHours, int fileMint) {
List<ProcessedFile> processedFilesList = new ArrayList<>();
try {
FTPClient ftpClient = new FTPClient();
// client FTP connection
ftpClient = connectToFTPClient(hostName, userName, password, portNo);
// check if FTP client is connected or not
if (ftpClient.isConnected()) {
if (processedFiles != null && processedFiles.size() > 0) {
for (ProcessedFile processedFile : processedFiles) {
FileInputStream inputStream = null;
try {
File file = new File(sourceDir + "/" + processedFile.getOriginalFileName());
inputStream = new FileInputStream(file);
if (!ftpClient.isConnected()) {
ftpClient = connectToFTPClient(hostName, userName, password, portNo);
}
ByteArrayInputStream in = null;
try {
ftpClient.changeWorkingDirectory(destinationPath);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
in = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
ftpClient.storeFile(file.getName(), in);
} catch (Exception e) {
logger.error(e.getMessage());
}
inputStream.close();
in.close();
processedFile.setProcessedStatus(ProcessedStatus.COMPLETED);
processedFilesList.add(processedFile);
} catch (Exception e) {
logger.error(e);
processedFile.setProcessedStatus(ProcessedStatus.FAILED);
processedFilesList.add(processedFile);
}
}
}
}
if (ftpClient.isConnected()) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
logger.error(e.getMessage());
} finally {
try {
ftpClient.disconnect();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
}
} catch (Exception e) {
logger.error("FTP not connected exception: " + e);
}
return processedFilesList;
}

while downloading the object from amazon s3 i cant able to download it to diffrent folder rather then the file uploaded path

while downloading the object from amazon s3 i cant able to download it to diffrent folder rather then the file uploaded path...why it is happening like this may be it is metaData problem....please post your valuable comments Thanks in advance..below am posting the code for upload and download
public void AmazonUpload(String fileObj) throws IOException {
try {
this.key = fileObj;
try {
if (this.key == null) {
} else {
if (readFile(this.key) != null) {
// this.key="1";
this.putObjResult = this.amzObj.putObject(new PutObjectRequest(this.bucketName, this.key, readFile(this.key)));
}
}
} catch (AmazonServiceException ae) {
System.out.println(ae.getMessage());
}
} catch (AmazonServiceException ex) {
Logger.getLogger(AthinioCloudMigration.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void AmazonDownload(String dirName, String xmlFilename, String amazonid) throws ParserConfigurationException, SAXException, TransformerException, IOException {
String cloudid;
cloudid = amazonid;
this.comm = new CommonResources(xmlFilename);
this.RequestFiles=new ArrayList();
try {
this.RequestFiles = this.comm.getXML(cloudid);
if (this.RequestFiles != null) {
int len = this.RequestFiles.size();
System.out.println(len);
for (int index = 0; index < len; index++) {
this.CRobj = (CommonResources) this.RequestFiles.get(index);
if (cloudid.equals(this.CRobj.getCloudID())) {
this.newFile = new File(dirName + this.CRobj.getFileName().concat(".rec"));
System.out.println(newFile);
newFile.createNewFile();
this.metaData = this.amzObj.getObject(new GetObjectRequest(this.bucketName, (dirName + this.CRobj.getFileName())), this.newFile);
System.out.println(metaData);
java.io.File tmp = new java.io.File(dirName + this.CRobj.getFileName());
System.out.println(tmp);
tmp.delete();
76,23 87%
Since in Amazon S3 there is no folder structure you receive everything as a object.
For Example: In your bucket you store file in a folder like structure but when you request fro the objects from S3 you will receve your file like folder1/folder2/demo.txt.
So try this one, Get the InputStream for the S3 for your file like amazonS3.getObject(bucket, "folder1/folder2/demo.txt").getObjectContent();. After getting your InputStream pass your File Name, Download location and InputStream to the below method. If you use Java 7 use FileSystems.getDefault().getPath(fullPathWithFileName).getFileName().toString() to get file name from your object name.
public void saveFile(String uploadFileName, String path, InputStream inputStream) throws Exception {
DataOutputStream dos = null;
OutputStream out = null;
try {
File newDirectory = new File(path);
if (!newDirectory.exists()) {
newDirectory.mkdirs();
}
File uploadedFile = new File(path, uploadFileName);
out = new FileOutputStream(uploadedFile);
byte[] fileAsBytes = new byte[inputStream.available()];
inputStream.read(fileAsBytes);
dos = new DataOutputStream(out);
dos.write(fileAsBytes);
} catch (IOException io) {
io.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (dos != null) {
dos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

tomcat servlet sessions get merged

I'm developing a server that should receive ,multiple files instantaneously and be able to save them to the local hard drive. After the file received the server should send a response to the client and confirm that the file passed. When i'm trying to send multiple files instantaneously the result is that 1 client received the answer of the second and vice versa.
Does any one have a clue what is the problem with this server?
Here is my servlet code:
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
response.setCharacterEncoding("UTF-8");
PrintWriter writer = null;
try {
writer = response.getWriter();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
// get access to file that is uploaded from client
Part p1 = request.getPart("File");
InputStream is = p1.getInputStream();
// read filename which is sent as a part
Part p2 = request.getPart("MetaData");
Scanner s = new Scanner(p2.getInputStream());
String stringJson = s.nextLine(); // read filename from stream
s.close();
json = new JSONObject(stringJson);
fileName = new String(json.getString("FileName").getBytes("UTF-8"));
fileDirectory = BASE + request.getSession().getId();
File dir = new File(fileDirectory);
dir.mkdir();
// get filename to use on the server
String outputfile = BASE + dir.getName() + "/" + fileName; // get path on the server
FileOutputStream os = new FileOutputStream (outputfile);
// write bytes taken from uploaded file to target file
byte[] buffer = new byte[1024];
int ch = is.read(buffer);
final Object lock = new Object();
while (ch != -1) {
synchronized (lock) {
os.write(buffer);
ch = is.read(buffer);
}
}
os.close();
is.close();
}
catch(Exception ex) {
writer.println("Exception -->" + ex.getMessage());
}
finally {
try {
myRequest = request;
try {
printFile(request.getSession().getId(), writer);
} catch (IOException e) {
// TODO Auto-generated catch block
writer.println("Exception -->" + e.getMessage());
}
writer.close();
} catch (InterruptedException e) {
writer.println("Exception -->" + e.getMessage());
}
}
}
Thanks in advance :)

How to get Audio file through HTTP get?

I am trying to get an Audio file through http get from a secure restful service, I have successfully receive and parse text XML service but a bit confused that how to do with Audio file.
code to call the secure restful service with XML response
String callWebService(String serviceURL) {
// http get client
HttpClient client = getClient();
HttpGet getRequest = new HttpGet();
try {
// construct a URI object
getRequest.setURI(new URI(serviceURL));
} catch (URISyntaxException e) {
Log.e("URISyntaxException", e.toString());
}
// buffer reader to read the response
BufferedReader in = null;
// the service response
HttpResponse response = null;
try {
// execute the request
response = client.execute(getRequest);
} catch (ClientProtocolException e) {
Log.e("ClientProtocolException", e.toString());
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
try {
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
} catch (IllegalStateException e) {
Log.e("IllegalStateException", e.toString());
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
StringBuffer buff = new StringBuffer("");
String line = "";
try {
while ((line = in.readLine()) != null) {
buff.append(line);
}
} catch (IOException e) {
Log.e("IO exception", e.toString());
return e.getMessage();
}
try {
in.close();
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
// response, need to be parsed
return buff.toString();
}
may this one help you..
public static void downloadFile(String fileURL, String fileName) {
try {
// fileURL=fileURL.replaceAll("amp;", "");
Log.e(fileURL, fileName);
String RootDir = Environment.getExternalStorageDirectory()
.toString();
File RootFile = new File(RootDir);
new File(RootDir + Commons.dataPath).mkdirs();
File file = new File(RootFile + Commons.dataPath + fileName);
if (file.exists()) {
file.delete();
}
file.createNewFile();
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(
"mnt/sdcard"+Commons.dataPath + fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Categories