I have the following method from which i am trying to update a progressBar as to how far the download has progressed:
private void wget(java.net.URL url, String destination) throws MalformedURLException, IOException {
java.net.URLConnection conn = url.openConnection();
java.io.InputStream in = conn.getInputStream();
File dstfile = new File(destination);
OutputStream out = new FileOutputStream(dstfile);
byte[] buffer = new byte[512];
int length;
int readBytes = 0;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
// Get progress
int contentLength = conn.getContentLength();
if (contentLength != -1) {
//System.out.println((length / contentLength) * 100); ??
UpdateForm.progressBar.setValue(2);
} else {
}
}
in.close();
out.close();
}
However i cannot seem to figure out how to calculate how many % have gone..
Any ideas?
Related
I am writing a raw socket server (for learning purpose), which on any request, should parse the Content-Length header and should then extract bytes equal to Content-Length from the socket input stream and echo it back to the client.
I found only one class 'DataInputStream' in Java IO system that provides with the capabilities of reading both, characters and bytes. However, the method readLine() of 'DataInputStream' is deprecated which I am using in my code. How can I get rid of the deprecated readLine() method in following code? Is there any class in Java IO system that allows reading of both, characters and bytes. Code follows:
class Server {
public Server() {
}
public void run() throws IOException {
ServerSocket serverSocket = new ServerSocket(7000);
while (true) {
Socket socket = serverSocket.accept();
DataInputStream requestStream = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
byte[] responseContent = null;
int contentLength = getContentLength(requestStream);
if (contentLength == 0)
responseContent = new byte[0];
else {
int totalBytesRead = 0, bytesRead = 0;
final int bufferSize = 5120;
final byte[] buffer = new byte[bufferSize];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
while (totalBytesRead != contentLength) {
bytesRead = requestStream.read(buffer, 0, bufferSize);
outputStream.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
}
responseContent = outputStream.toByteArray();
}
OutputStream outputStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream);
writer.println(String.format("HTTP/1.1 %s", 200));
writer.println(String.format("Content-Length: %d", contentLength));
writer.println("");
writer.flush();
outputStream.write(responseContent);
outputStream.flush();
socket.close();
}
}
private int getContentLength(DataInputStream requestStream)
throws IOException {
int contentLength = 0;
String headerLine;
// TODO - Get rid of deprecated readLine() method
while ((headerLine = requestStream.readLine()) != null
&& headerLine.length() != 0) {
final String[] headerTokens = headerLine.split(":");
if (headerTokens[0].equalsIgnoreCase("Content-Length")) {
contentLength = Integer.valueOf(headerTokens[1].trim());
}
}
return contentLength;
}
}
I'm trying to download BLOB data from MySQL, but all I can get is a file with 1 KB size.
I've got a table which contains checkboxes, and I'm looking for the checked ones. The values are the IDs.
This is the code:
public class FileDownloadServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DBConnection DBC = new DBConnection();
Connection con = DBC.connection();
String[] checkBoxValues = request.getParameterValues("files");
for (int i = 0; i < checkBoxValues.length; i++) {
String fileDL = "select * from uploads where file_id='"+checkBoxValues[i]+"'";
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(fileDL);
while(rs.next()){
String fileName = rs.getString("file_name");
Blob blob = rs.getBlob("file");
InputStream input = blob.getBinaryStream();
int fileSize = (int) blob.length();
System.out.println(fileSize);
ServletContext context = getServletContext();
String mimeType = context.getMimeType(fileName);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.setContentLength(fileSize);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileName);
response.setHeader(headerKey, headerValue);
OutputStream output = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
input.close();
output.close();
}
} catch (SQLException ex) {
Logger.getLogger(FileDownloadServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
I have no idea where I went wrong. Thanks in advance!
output.write(buffer, 0, bytesRead)
always uses the same offset. You are never really advancing in your resulting stream. You'd have to increment your offset by bytesRead
EDIT: Explanation
You are using https://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html#write%28byte[],%20int,%20int%29
This method writes the bytes in your buffer to the outputstream, starting at position 0.
Now, in the next iteration, you read the next 4k bytes and again write it to the outputstream. But your offset hasn't changed, so you are not appending the new buffer-content but overwriting the previsously written bytes, because you said to write from position 0 again. Therefor, you need to advance the offset by the same amount of bytes you have previously written.
EDIT: Spoiler
So here's the spoiler:
int bytesRead = -1;
int offset = 0;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, offset, bytesRead);
offset += bytesRead;
}
Not tested.
Additionally, why do you want to write in 4k chunks?
Why not just
byte[] buffer = new byte[1];
while (input.read(buffer) > 0) {
output.write(buffer);
}
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();
}
}
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.
Following is the snippet from a servlet that attempts to fetch image from the URL. I have fetched the bytes. Now how do I display the image on the webpage ?
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
URL url = new URL("https://abc/zhdhaG1z_bigger.jpeg");
InputStream stream = new BufferedInputStream(url.openStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int n = 0;
while(-1 != (n = stream.read(buf)) ) {
bos.write(buf, 0, n);
}
byte res[] = bos.toByteArray();
} finally {
out.close();
}
You Can Rewrite your code like this...see if this helps
public void doGet(HttpRequest request,HttpResponse response)throws ServletException{
response.setContentType("image/jpeg;charset=UTF-8");
response.addHeader("content-disposition", "inline;filename=Default.jpeg");
try {
URL url = new URL("https://abc/zhdhaG1z_bigger.jpeg");
InputStream stream = new BufferedInputStream(url.openStream());
ByteArrayOutputStream bos = new OutputStream();
byte buf[] = new byte[1024];
int n = 0;
while(-1 != (n = stream.read(buf)) ) {
bos.write(buf, 0, n);
}
}
catch(Exception e){
e.printStackTarce();
}
finally {
out.close();
}
}