Upload Image to FTP Server using ADF Mobile Application - java

I want to upload an image to FTP Server. Currently i am using JDeveloper 12c(12.1.3.0).
My Code:
private static final int BUFFER_SIZE = 4096;
public String fileUploadMethod(String imagePath){
String ftpUrl = "ftp://";
String host = "http://192.168.0.42";
String user = "XXXXXX";
String pass = "XXXXXX";
String filePath = "783771-1.jpg";
String uploadPath = imagePath;
ftpUrl =ftpUrl + user +":"+ pass+"#"+host+"/"+filePath+";";
System.out.println("Upload URL: " + ftpUrl);
try {
URL url = new URL(ftpUrl);
URLConnection conn = url.openConnection();
OutputStream outputStream = conn.getOutputStream();
FileInputStream inputStream = new FileInputStream(uploadPath);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
System.out.println("File uploaded");
return "File uploaded";
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
I am getting an error MalFormedURLException i.e. in detail message "unknown protocol:ftp"
Is there any other option to upload an image using JDeveloper.
Any idea regarding this.
Thanks, Siddharth

Your ftpUrl is wrong. Remove http:// in the host variable. Should be ok then

I haven't really tried ftp upload. But I had tried with multipart form upload. As far as I know, MAF doesnt provide Out-Of-Box support for file upload. What I did was essential recreating the HTTP stream for the image upload.
The POC code is attached below. This may be definitely the CRUDEST implementation but I am not sure if there is a better way.
public void doUpload() {
try {
DeviceManager dm = DeviceManagerFactory.getDeviceManager();
String imgData =
dm.getPicture(50, DeviceManager.CAMERA_DESTINATIONTYPE_FILE_URI, DeviceManager.CAMERA_SOURCETYPE_CAMERA,
false, DeviceManager.CAMERA_ENCODINGTYPE_PNG, 0, 0);
imgData = imgData.substring(7, imgData.length());
int start = imgData.lastIndexOf('/');
String fileName = imgData.substring(start+1, imgData.length());
RestServiceAdapter restServiceAdapter = Model.createRestServiceAdapter();
restServiceAdapter.clearRequestProperties();
String requestMethod = RestServiceAdapter.REQUEST_TYPE_POST;
String requestEndPoint = restServiceAdapter.getConnectionEndPoint("serverBaseUrl");
String requestURI = "/workers/100000018080264";
String request = requestEndPoint + requestURI;
HashMap httpHeadersValue = new HashMap();
httpHeadersValue.put("X-ANTICSRF", "TRUE");
httpHeadersValue.put("Connection", "Keep-Alive");
httpHeadersValue.put("content-type","multipart/form-data; boundary=----------------------------4abf1aa47e18");
// Get the connection
HttpConnection connection = restServiceAdapter.getHttpConnection(requestMethod, request, httpHeadersValue);
OutputStream os = connection.openOutputStream();
byte byteBuffer[] = new byte[50];
int len;
//String temp is appended before the image body
String temp = "------------------------------4abf1aa47e18\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" +fileName+ "\"\r\nContent-Type: image/jpeg\r\n\r\n";
InputStream stream = new ByteArrayInputStream(temp.getBytes("UTF-8"));
if (stream != null) {
while ((len = stream.read(byteBuffer)) >= 0) {
os.write(byteBuffer, 0, len);
}
stream.close();
}
FileInputStream in = new FileInputStream(imgData);
if (in != null) {
while ((len = in.read(byteBuffer)) >= 0) {
os.write(byteBuffer, 0, len);
}
in.close();
}
//The below String is appended after the image body
InputStream stream2 =new ByteArrayInputStream("\r\n------------------------------4abf1aa47e18--\r\n".getBytes("UTF-8"));
if (stream2 != null) {
while ((len = stream2.read(byteBuffer)) >= 0) {
os.write(byteBuffer, 0, len);
}
stream2.close();
}
int status = connection.getResponseCode();
InputStream inputStream = restServiceAdapter.getInputStream(connection);
ByteArrayOutputStream incomingBytes = new ByteArrayOutputStream() // get and process the response.
while ((len = inputStream.read(byteBuffer)) >= 0) {
incomingBytes.write(byteBuffer, 0, len);
}
String ret = incomingBytes.toString();
incomingBytes.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Related

How do I download and save a Zip file using Java/Spring Boot code from a server?

I need to develop an API which can open connection to an URL which returns a ZIP file. This URL works perfectly fine when accessed from browser or Postman but when I try to access it from Java Code (tried HttpClient/RestTemplate etc) it returns an HTML file. I want to get the zip file and want to store it at particular directory.
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpGet request = new HttpGet(url);
logger.info("Request to Asset Store: URL " + request.getURI());
HttpResponse response = client.execute(request);
if (response != null) {
for (Header header : response.getAllHeaders()) {
System.out.println(header.getName() + " - " + header.getValue());
}
BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent());
final ZipInputStream is = new ZipInputStream(bis);
try {
ZipEntry entry;
while ((entry = is.getNextEntry()) != null) {
System.out.printf("File: %s Size %d Modified on %TD %n", entry.getName(),
entry.getSize(), new Date(entry.getTime()));
extractEntry(entry, is);
}
System.out.println("OUT");
} finally {
is.close();
}
}
private static void extractEntry(final ZipEntry entry, InputStream is) throws IOException {
String exractedFile = "D://" + entry.getName();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(exractedFile);
final byte[] buf = new byte[2048];
int read = 0;
int length;
while ((length = is.read(buf, 0, buf.length)) >= 0) {
fos.write(buf, 0, length);
}
} catch (IOException ioex) {
fos.close();

How to download NSE Bhavcopy (NSE market closing price) in Java?

I need to download a file from the following link in Java
[http://www.nseindia.com/content/historical/EQUITIES/2017/OCT/cm30OCT2017bhav.csv.zip][1]
I have the code written in C#, can some one suggest Java equivalent code
WebClient webClient = new WebClient();
String accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
String agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1";
webClient.Headers.Add(HttpRequestHeader.Accept, accept);
webClient.Headers.Add(HttpRequestHeader.UserAgent, agent);
webClient.UseDefaultCredentials = true;
webClient.DownloadFile(source, target);
I myself found a solution
source = "http://www.bseindia.com/download/Bhavcopy/Derivative/bhavcopy07-11-17.zip";
target = "d:\Market Feeds\EQD BSE Bhavcopy\"
public static void downloadFileHttp(String source, String destination) throws Exception {
try{
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ipaddress, port));
URL oracle = new URL(source);
URLConnection yc = oracle.openConnection(proxy);
InputStream in = yc.getInputStream();
FileOutputStream out = new FileOutputStream(destination + "\\bhavcopy.zip");
copySource2Dest(in, out, 1024);
out.close();
extractFolder(destination + "\\bhavcopy.zip", destination);
//Path path = FileSystems.getDefault().getPath(destination, "bhavcopy.zip");
//boolean succ = Files.deleteIfExists(path);
System.out.println("Download is successfull");
}
catch(Exception e){
System.out.println("Error in downloading : " + e);
}
}
public static void copySource2Dest(InputStream input, OutputStream output, int bufferSize)
throws IOException {
byte[] buf = new byte[bufferSize];
int n = input.read(buf);
while (n >= 0) {
output.write(buf, 0, n);
n = input.read(buf);
}
output.flush();
}
public static void extractFolder(String zipFile,String extractFolder)
{
try
{
int BUFFER = 2048;
File file = new File(zipFile);
ZipFile zip = new ZipFile(file);
String newPath = extractFolder;
new File(newPath).mkdir();
Enumeration zipFileEntries = zip.entries();
ZipEntry entry;
// Process each entry
while (zipFileEntries.hasMoreElements())
{
// grab a zip file entry
entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(newPath, currentEntry);
File destinationParent = destFile.getParentFile();
// create the parent directory structure if needed
destinationParent.mkdirs();
if (!entry.isDirectory())
{
BufferedInputStream is = new BufferedInputStream(zip
.getInputStream(entry));
int currentByte;
// establish buffer for writing file
byte data[] = new byte[BUFFER];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest = new BufferedOutputStream(fos,
BUFFER);
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
}
zip.close();
}
catch (Exception e){
System.out.println("ERROR: "+e.getMessage());
}
}

How to get file name while downloading a file in Java?

I have FileDownloader class that downloads the file from google drive and than these files can be used by other classes. I need also to extract filename somehow. The problem is that this solution below works good for direct links, but it doesn't work when links are shorten with bit.ly for example...
Could you please advise how I can change the code to get the right file name?
public class FileDownloader {
private static final int BUFFER_SIZE = 4096;
public static void downloadFile(String fileURL, String saveDir)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// checking HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename*=UTF-8''");
if (index > 0) {
fileName = disposition.substring(index + 17,
disposition.length());
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
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 = saveDir + 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();
}
Alternate Code to get File details from any HTTP URL using Java API:
URL url = new URL("http://www.example.com/somepath/filename.extension");
System.out.println(FilenameUtils.getBaseName(url.getPath()));
// filename
System.out.println(FilenameUtils.getName(url.getPath()));
// filename.extension

Code that download empty file and supposed not to

I have this part of function where it supposed to download file like pdf from server and store in new directory. It does do this but an empty pdf or text file.How to fix it.
`File urlfile = new File(host + "/" + path);
urlfile.getParentFile().mkdirs();
// create outputstream for request and inputstream for data
// download
FileOutputStream outS = new FileOutputStream(urlfile);
DataInputStream instream = new DataInputStream(newsocket.getInputStream());
// get rid of head part to get to actual file
String l = null;
String lastmodtime = null;
boolean done = false;
while (!(l = DAA.readLine()).equals("")) {
if (!done && l.contains("Last-Modified:")) {
lastmodtime = l.substring(l.indexOf(' ') + 1, l.length());
done = true;
System.out.println(l);
}
}
// read in bytes to correct file name
try {
byte[] inbytes = new byte[16384];
int input;
while ((input = instream.read(inbytes)) != -1) {
outS.write(inbytes, 0, input);
}
}`
You can try this simple code if you want to create a copy of the file or you can even use apache commons io (FileUtils.copyFile(source, dest)) for java copy file operation.
private static void copyFileUsingStream(File source, File dest)
throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}

Unable to upload file with jersey

I am using this webservice to upload a file using jersey
public class upload {
#POST
#Path(value = "upload")
#Consumes("image/jpg")
public Response uploadPng(File file) throws IOException {
file = new File("C:/Users/Marwa/Desktop/Capture.jpg");
String uploadedFileLocation = "C:/Users/Desktop/" + file.getName();
DataInputStream diStream =new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
byte[] fileBytes = new byte[(int) len];
int read = 0;
int numRead = 0;
while (read < fileBytes.length && (numRead =diStream.read(fileBytes, read,fileBytes.length - read)) >= 0) {
read = read + numRead;
}
// save it
writeToFile(diStream, uploadedFileLocation);
System.out.println("File uploaded to : " + uploadedFileLocation);
return Response.status(200).entity(file).build();
}
// save uploaded file to new location
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();}}}
When I execute my code i get a 405 error !!
Are there any suggestions to this issue?
public Response uploadPng(FormDataMultiPart multiPart) throws IOException {
You should pass the FormDataMultiPart parameter in the method which you are calling while uploading file.
Not sure if this is perfect solution. But solved similar problem by following approach.
First thing, you should use
public Response uploadPng(FormDataMultiPart multiPart) throws IOException {
Next to avoid 405 error add
#Produces(MediaType.TEXT_PLAIN)
above uploadpng method.

Categories

Resources