How to receive bytes from a lib to update the JProgressBar? - java

I've tried to receive bytes from a lib to set my JProgressBar update for a long time but unfortunately
I didn't get the result I wanted.
The problem is that I don't know how to receive bytes from a lib and how to update the JProgressBar while receiving bytes all that to make a browser with java
This is the code I've tried:
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER){
String az = jTextField1.getText();
if(az.contains("1")){
String hh = WorkSpace.jTextField1.getText();
URLConnection conn = null;
InputStream in = null;
try {
URL url = new URL(hh);
conn = url.openConnection();
in = conn.getInputStream();
int length = conn.getContentLength();
int current = 0;
WorkSpace.jProgressBar1.setMaximum(length);
WorkSpace.jProgressBar1.setValue(0);
byte[] buffer = new byte[1024];
int numRead = 0;
while ((numRead = in.read(buffer)) != -1) {
current=0;
current += numRead;
WorkSpace.jProgressBar1.setValue(current);
}
} catch (Exception e) {
}
}
If there's someone who knows how to do this please let me know.

Just wrap the input stream in a ProgressMonitorInputStream. It will manage its own JProgressBar for you.

Related

Stream Closed IO Exception Java

I am running the following program and get the Stream Closed IO Error.
but only in the second loop. the first one works fine.
Can anybody please tell me why? (I checked that the file is existing and not empty.)
private static TimerTask perform(){
//logging on to FTP-Server
InputStream in = client.retrieveFileStream("./htdocs/pwiMain/main.txt");
InputStream pw = client.retrieveFileStream("./htdocs/pwiMain/cred_pwd.txt");
BufferedInputStream inbf = new BufferedInputStream(in);
int bytesRead;
byte[] buffer = new byte[1024];
String wholeFile = null;
String[] contents;
while((bytesRead = inbf.read(buffer)) != -1){
wholeFile = new String(buffer,0,bytesRead);
}
sentPassword = wholeFile.substring(wholeFile.indexOf("#lap"));
inbf.close();
inbf = new BufferedInputStream(pw);
while((bytesRead = inbf.read(buffer)) != -1){ // this is line72 where the error occurrs...
wholeFile = new String(buffer,0,bytesRead);
}
md5hash = wohleFile;
inbf.close();
contents = sentPassword.split("\\r\\n|\\n|\\r");
System.out.println("contents: " + contents[0] + " " + contents[1]);
//check the password
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("ioexception");
} finally {
}
return null;
}
Here is the error message:
java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:159)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at java.io.FilterInputStream.read(FilterInputStream.java:107)
at com.protonmail.taylor.faebl.development.main.perform(main.java:72)
at com.protonmail.taylor.faebl.development.main.main(main.java:23)
Thanks a lot for your help :)
You evidently can't have two retrieval streams active at the same time, which isn't surprising. Just reorder your code:
private static TimerTask perform(){
try {
//logging on to FTP-Server
InputStream in = client.retrieveFileStream("./htdocs/pwiMain/main.txt");
BufferedInputStream inbf = new BufferedInputStream(in);
int bytesRead;
byte[] buffer = new byte[1024];
String wholeFile = null;
String wholeCred = null;
String[] contents;
while((bytesRead = inbf.read(buffer)) != -1){
wholeFile = new String(buffer,0,bytesRead);
}
inbf.close(); // ADDED
InputStream pw = client.retrieveFileStream("./htdocs/pwiMain/cred_pwd.txt");
BufferedInputStream pwbf = new BufferedInputStream(pw);
int pwBytesRead; // YOU DON'T NEED THIS, you could reuse the previous one
byte[] pwBuffer = new byte [1024]; // DITTO
while((pwBytesRead = pwbf.read(pwBuffer)) != -1){
wholeCred = new String(pwBuffer,0,pwBytesRead);
}
pwbf.close(); // ADDED
sentPassword = wholeFile.substring(sentPassword.indexOf("#lap"));
md5hash = wholeCred;
contents = sentPassword.split("\\r\\n|\\n|\\r");
System.out.println("contents: " + contents[0] + " " + contents[1]);
//check the password
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("ioexception");
} finally {
}
return null;
}
There's no point or advantage in the way you're doing it now, you're just wasting space, and as you've discovered it doesn't work.
Of course you will then discover that if either of the inputs exceeds one buffer it won't work, but you didn't ask about that.

Upload Image to FTP Server using ADF Mobile Application

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();
}
}

Java openConnection calculate progress

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?

swing download not works in windows xp

I have a sample code to download some data (pdf,gif and mp3) from a web and its a swing application.It works perfectly in Windows 7 but not working in Windows xp.
My code is
public static Float downloadFile(String targetUrl,File filePath)
{
try
{
Integer count=0;
URL url = new URL(targetUrl);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(10000);
connection.connect();
int lenghtOfFile = connection.getContentLength();
Thread.sleep(100);
InputStream input = new BufferedInputStream(url.openStream());
Thread.sleep(100);
OutputStream output = new FileOutputStream(filePath);
byte data[] = new byte[input.available()];
long total = 0;
while ((count = input.read(data)) != -1)
{
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return 2.5f;
}
}
It enters into the infinite while loop by setting the code to 0
Q: What is "input.available()" when you initialize your buffer? If it happens to be "0" at that moment, you'd be sad.
One solution is to use a fixed-length buffer (e.g. 8192).

Progress bar freezing while downloading file in java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JProgressBar wont update
So I am trying to show the download progress of a file being downloaded in Java. I can output the current percentage as a String to the console, but when I try to update the UI, it freezes until the download is complete.
public void downloadFile(String fileName) {
try {
long startTime = System.currentTimeMillis();
System.out.println("Connecting to site...\n");
URL url = new URL("http://assets.minecraft.net/"+fileName+"/minecraft.jar");
URLConnection connection = url.openConnection();
try (InputStream reader = url.openStream(); FileOutputStream writer = new FileOutputStream("minecraft.jar")) {
byte[] buffer = new byte[153600];
int totalBytesRead = 0;
int bytesRead = 0;
int totalSize = connection.getContentLength();
jProgressBar1.setMaximum(totalSize);
System.out.println("Downloading\n");
while ((bytesRead = reader.read(buffer)) > 0) {
writer.write(buffer, 0, bytesRead);
buffer = new byte[153600];
totalBytesRead += bytesRead;
jProgressBar1.setValue(totalBytesRead);
System.out.println(totalBytesRead*100/totalSize+"% complete");
}
long endTime = System.currentTimeMillis();
System.out.println("Done. " + (new Integer(totalBytesRead).toString()) + " bytes read (" + (new Long(endTime - startTime).toString()) + " millseconds).\n");
}
}
catch (MalformedURLException e) {
}
catch (IOException e) {
}
}
I read somewhere that you need to use another thread but I was unable to successfully do that.
One option would be using SwingWorker. Here are some useful answers you may consider:
Need to have JProgress bar to measure progress when copying directories and files
How SwingWorker works

Categories

Resources