i have a java program to download a file through https connection.The program is as follows,
public class Download extends Observable implements Runnable {
private static final int MAX_BUFFER_SIZE = 1024;
public static final int DOWNLOADING = 0;
public static final int PAUSED = 1;
public static final int COMPLETE = 2;
public static final int CANCELLED = 3;
public static final int ERROR = 4;
private URL url; // download URL
private static float size; // size of download in bytes
private int downloaded; // number of bytes downloaded
private int status; // current status of download
private String location;
public Download(URL url,String location){
this.url = url;
size=-1;
downloaded=0;
status=DOWNLOADING;
this.location=location;
download();
}
public String getURL(){
return url.toString();
}
public static float getSize(){
return size;
}
public float getProgress(){
return ((float) downloaded / size) * 100;
}
public void pause(){
status = PAUSED;
stateChanged();
}
public void resume(){
status = DOWNLOADING;
stateChanged();
download();
}
public void cancel(){
status = CANCELLED;
stateChanged();
}
public void error(){
status = ERROR;
stateChanged();
}
private String getFileName(URL url){
String filepath = url.getFile();
int slashIndex = filepath.lastIndexOf("/");
String fileName = filepath.substring(slashIndex+1,filepath.length());
String downloadPath = location+"/"+fileName;
return downloadPath;
}
private void download(){
Thread thread = new Thread(this);
thread.start();
}
#Override
public void run() {
RandomAccessFile randomAccessFile = null;
InputStream inputStream = null;
int responseCode = 0;
try{
HttpsURLConnection connection = getSSLCertificate(getURL());
connection.setRequestMethod("GET");
connection.setRequestProperty("Range","bytes=" + downloaded + "-");
connection.connect();
responseCode=connection.getResponseCode();
if(responseCode/100 != 2){
error();
}
int contentLength = connection.getContentLength();
if(contentLength <1){
error();
}
if(size == -1){
size = contentLength;
stateChanged();
}
randomAccessFile = new RandomAccessFile(getFileName(url),"rw");
randomAccessFile.seek(downloaded);
inputStream = connection.getInputStream();
while(status == DOWNLOADING){
//byte buffer[]=new byte[3000000];
byte buffer[];
float finalSize=size - downloaded;
if ( finalSize > MAX_BUFFER_SIZE) {
buffer = new byte[(int) finalSize];
} else {
buffer = new byte[MAX_BUFFER_SIZE];
}
int read = inputStream.read(buffer);
if(read == -1)
break;
randomAccessFile.write(buffer, 0, read);
downloaded += read;
stateChanged();
}
}catch (Exception e) {
e.printStackTrace();
}finally{
try {
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stateChanged(){
setChanged();
notifyObservers();
}
private HttpsURLConnection getSSLCertificate(String urlPath) throws NoSuchAlgorithmException, KeyManagementException, IOException{
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0],new TrustManager[]{new DefaultTrustManager()},new SecureRandom());
SSLContext.setDefault(ctx);
URL url = new URL(urlPath);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
return conn;
}
public static void main(String[] args) throws MalformedURLException {
System.out.println("Enter the URL and Press ENTER:");
Scanner scanner = new Scanner(System.in);
String link = scanner.nextLine();
System.out.println("Enter the destination location and Press ENTER:");
String destination=scanner.nextLine();
if(link.length() >0 && destination.length()>0){
Download d = new Download(new URL(link),destination);
System.out.println("Downloading... ");
d.run();
System.out.println("Downloaded Successfully" +" " +"Size:"+(getSize()/1048576) + " MB");
}else{
System.out.println("Error! Please provide url and destination location");
System.exit(1);
}
}
I need to implement a resume download,ie if there is internet breakdown while downloading and again internet comes,the download needs to starts from the point where it stops.
randomAccessFile = new RandomAccessFile(getFileName(url),"rw");
There is one problem i found. I think everytime you are creating a new file. If file is already exists, then you donot need to write this line. so make it change first.
one more issue is about "Downloaded" variable. In Constructor, Everytime it is initialized by 0. You need to take the last value from where it stops. you can get it by below line.
downloaded = (int) randomAccessFile.length();
Moreover, you can check this post's answers.
how to resume an interrupted download - part 2
Related
I'm using Encog and I ran the ocr sample. It works fine. However, I want to pass an image file (png, jpg,...) as a parameter. This image contains the text to to be recognized. Then, the system should return a string with the "same" text.
Has someone already did something similar? How should I start?
Thanks!
Step 1: In GUI create file input and take file from user
JFileChooser fc;
JButton b, b1;
JTextField tf;
FileInputStream in;
Socket s;
DataOutputStream dout;
DataInputStream din;
int i;
public void actionPerformed(ActionEvent e) {
try {
if (e.getSource() == b) {
int x = fc.showOpenDialog(null);
if (x == JFileChooser.APPROVE_OPTION) {
fileToBeSent = fc.getSelectedFile();
tf.setText(f1.getAbsolutePath());
b1.setEnabled(true);
} else {
fileToBeSent = null;
tf.setText(null;);
b1.setEnabled(false);
}
}
if (e.getSource() == b1) {
send();
}
} catch (Exception ex) {
}
}
public void copy() throws IOException {
File f1 = fc.getSelectedFile();
tf.setText(f1.getAbsolutePath());
in = new FileInputStream(f1.getAbsolutePath());
while ((i = in.read()) != -1) {
System.out.print(i);
}
}
public void send() throws IOException {
dout.write(i);
dout.flush();
}
Step 2: Down sample it
private void processNetwork() throws IOException {
System.out.println("Downsampling images...");
for (final ImagePair pair : this.imageList) {
final MLData ideal = new BasicMLData(this.outputCount);
final int idx = pair.getIdentity();
for (int i = 0; i < this.outputCount; i++) {
if (i == idx) {
ideal.setData(i, 1);
} else {
ideal.setData(i, -1);
}
}
final Image img = ImageIO.read(fc.getFile());
final ImageMLData data = new ImageMLData(img);
this.training.add(data, ideal);
}
final String strHidden1 = getArg("hidden1");
final String strHidden2 = getArg("hidden2");
this.training.downsample(this.downsampleHeight, this.downsampleWidth);
final int hidden1 = Integer.parseInt(strHidden1);
final int hidden2 = Integer.parseInt(strHidden2);
this.network = EncogUtility.simpleFeedForward(this.training
.getInputSize(), hidden1, hidden2,
this.training.getIdealSize(), true);
System.out.println("Created network: " + this.network.toString());
}
Step 3: Begin Training with training set
private void processTrain() throws IOException {
final String strMode = getArg("mode");
final String strMinutes = getArg("minutes");
final String strStrategyError = getArg("strategyerror");
final String strStrategyCycles = getArg("strategycycles");
System.out.println("Training Beginning... Output patterns="
+ this.outputCount);
final double strategyError = Double.parseDouble(strStrategyError);
final int strategyCycles = Integer.parseInt(strStrategyCycles);
final ResilientPropagation train = new ResilientPropagation(this.network, this.training);
train.addStrategy(new ResetStrategy(strategyError, strategyCycles));
if (strMode.equalsIgnoreCase("gui")) {
TrainingDialog.trainDialog(train, this.network, this.training);
} else {
final int minutes = Integer.parseInt(strMinutes);
EncogUtility.trainConsole(train, this.network, this.training,
minutes);
}
System.out.println("Training Stopped...");
}
Step 4: Give down sampled file to neural network
public void processWhatIs() throws IOException {
final String filename = getArg("image");
final File file = new File(filename);
final Image img = ImageIO.read(file);
final ImageMLData input = new ImageMLData(img);
input.downsample(this.downsample, false, this.downsampleHeight,
this.downsampleWidth, 1, -1);
final int winner = this.network.winner(input);
System.out.println("What is: " + filename + ", it seems to be: "
+ this.neuron2identity.get(winner));
}
Step 5: Check Result
i have created a list filed which contains a Picture and some data in one row
the picture and data i am getting from Json. My code is working but after getting the list my UI is hanging,
There are Two steps
1) parse the data and image URL from json
2) and show in list field
I'll post my code and screen shot of List below
http://supportforums.blackberry.com/t5/image/serverpage/image-id/19759iD4089A71454F66E0/image-size/large/is-moderation-mode/true?v=mpbl-1&px=600
public final class MyScreen extends MainScreen implements ListFieldCallback
{
HttpConnection httpConn;
int responseCode;
private static ListField _list;
private static Vector listElements = new Vector();
private static Vector elements = new Vector();
private static Vector contentelements = new Vector();
private static Vector datelements = new Vector();
private static Vector Imageselements = new Vector();
LabelField label;
String imagename;
Bitmap bit ;
Connection connectionthread;
public MyScreen()
{
// Set the displayed title of the screen
//setTitle("MyTitle");
_list = new ListField();
_list.invalidate();
_list.setEmptyString("please wait..", DrawStyle.HCENTER);
_list.setRowHeight(100);
_list.setCallback(this);
add(_list);
connectionthread = new Connection();
connectionthread.start();
}
public class Connection extends Thread{
public void run() {
try {
String httpURL = "http://192.168.1.91/bjp_app/program"+ getConnectionString();
httpConn = (HttpConnection) Connector.open(httpURL);
httpConn.setRequestMethod(HttpConnection.GET);
responseCode = httpConn.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
throw new IOException("HTTP response code: "+ responseCode);
//System.out.println("\n Internaet problem HttpConnection. = "+responseCode);
}else{
System.out.println("\n elseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee= ");
System.out.println("\nHttpConnection.HTTP_OK = "+responseCode);
DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
byte[] request_body = httpURL.getBytes();
for (int i = 0; i < request_body.length; i++) {
_outStream.writeByte(request_body[i]);
}
DataInputStream _inputStream = new DataInputStream(
httpConn.openInputStream());
StringBuffer _responseMessage = new StringBuffer();
int ch;
while ((ch = _inputStream.read()) != -1) {
_responseMessage.append((char) ch);
}
String res = (_responseMessage.toString());
String responce = res.trim();
System.out.println("\nresponce= "+responce);
JSONArray jsnarry = new JSONArray(responce);
System.out.println("\n--length----- "+jsnarry.length());
for (int i = 0; i < jsnarry.length(); i++){
JSONArray inerarray = jsnarry.getJSONArray(i);
System.out.println("\n-innerarray-length----- "+inerarray.length());
//for (int i1 = 0; i1 < inerarray.length(); i1++) {
//System.out.println("\n-inerarray-values----- "+inerarray.getString(i1));
String ID = inerarray.getString(0);
String TITTLE = inerarray.getString(1);
String CONTENT = inerarray.getString(2);
String DATE = inerarray.getString(3);
String IMAGE = inerarray.getString(4);
String six = inerarray.getString(5);
System.out.println("................................................");
System.out.println("ID= "+ID);
System.out.println("TITTLE= "+TITTLE);
System.out.println("CONTENT= "+CONTENT);
System.out.println("DATE= "+DATE);
System.out.println("IMAGE= "+IMAGE);
imagename = "http://sanjaytandon.in/admin/image/"+IMAGE.trim();
System.out.println("imagename= "+imagename);
//System.out.println("six "+six);
System.out.println("....................................................=");
// String jsonresponse = ""+inerarray.getString(i1);
//label = new LabelField(jsonresponse,LabelField.FOCUSABLE);
//add(label);
//}
elements.addElement(TITTLE);
contentelements.addElement(CONTENT);
datelements.addElement(DATE);
Imageselements.addElement(imagename);
}
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
_list.setSize(elements.size());
_list.setSize(contentelements.size());
_list.setSize(datelements.size());
_list.setSize(Imageselements.size());
//invalidate();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("error _list.setSize"+e.toString());
}
}
});
}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("\nresponce code error "+e.toString());
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Status.show("Check your internet connection!", 2000);
}
});
}
}
}
public void drawListRow (ListField listField, Graphics graphics, int index, int y, int w) {
try {
graphics.setGlobalAlpha(255);
final int margin =5;
String tittle = (String)elements.elementAt(index);
String content = (String)contentelements.elementAt(index);
String date = (String)datelements.elementAt(index);
String imagesurl = (String)Imageselements.elementAt(index);
UrlToImage img = new UrlToImage( imagesurl);
bit =img.getbitmap();
graphics.drawText(tittle.trim(), 3*margin+bit.getWidth(), y+margin);
graphics.drawText(content.trim(), 3*margin+bit.getWidth(), y+ margin+30);
graphics.drawText(date.trim(), 3*margin+bit.getWidth(), y+ margin+60);
graphics.drawBitmap(2, y+margin+5, bit.getWidth(), bit.getHeight(), bit, 0, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("error drawListRow"+e.toString());
}
}
public Object get(ListField listField, int index) {
// TODO Auto-generated method stub
return null;
}
public int getPreferredWidth(ListField listField) {
// TODO Auto-generated method stub
return 0;
}
public int indexOfList(ListField listField, String prefix, int start) {
// TODO Auto-generated method stub
return 0;
}
and MY UrlToImage.java class whcih downloads the images from URL
public class UrlToImage {
public static Bitmap _bmap;
UrlToImage(final String url){
HttpConnection connection = null;
InputStream inputStream = null;
EncodedImage bitmap;
byte[] dataArray = null;
try {
connection = (HttpConnection) Connector.open(url+ getConnectionString(), Connector.READ, true);
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData)))
{
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
throw new IOException("HTTP response code: "+ responseCode);
}else{
System.out.println("\nHttpConnection.HTTP_OK = "+responseCode);
}
final String result = rawResponse.toString();
dataArray = result.getBytes();
/*System.out.println("\ndataArray.length = "+dataArray.length);
System.out.println("\ndataArray.length = "+dataArray[0]);
System.out.println("\ndataArray.length = "+dataArray[1]);
System.out.println("\ndataArray.length = "+dataArray[2]);
System.out.println("\ndataArray.length = "+dataArray[3]);*/
} catch (final Exception ex) {
}finally {
try {
inputStream.close();
inputStream = null;
connection.close();
connection = null;
}
catch(Exception e){
}
}
bitmap = EncodedImage.createEncodedImage(dataArray, 0,dataArray.length);
// this will scale your image acc. to your height and width of bitmapfield
int multH;
int multW;
int currHeight = bitmap.getHeight();
int currWidth = bitmap.getWidth();
multH= Fixed32.div(Fixed32.toFP(currHeight),Fixed32.toFP(80));//height
multW = Fixed32.div(Fixed32.toFP(currWidth),Fixed32.toFP(80));//width
bitmap = bitmap.scaleImage32(multW,multH);
_bmap=bitmap.getBitmap();
}
public String getConnectionString() {
String connectionString = null;
// Simulator behaviour is controlled by the USE_MDS_IN_SIMULATOR
// variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceside=true";
System.out.println("11111111111111111");
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connectionString = ";interface=wifi";
System.out.println("222222222222222222");
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
{
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
System.out.println("33333333333333333");
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier BIBS
// request
System.out.println("444444444444444444");
connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
{
System.out.println("55555555555555555555");
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid hassling the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
{
System.out.println("66666666666666666666");
connectionString = "none";
}
// In theory, all bases are covered by now so this shouldn't be reachable.But hey, just in case ...
else {
System.out.println("77777777777777777777777");
connectionString = ";deviceside=true";
}
return connectionString;
}
/**//**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The uid used to connect to that network.
*//*
*/ private synchronized String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
public Bitmap getbitmap()
{
return _bmap;
}
}
For a ListField, this method:
public void drawListRow (ListField listField, Graphics graphics, int index, int y, int w)
will be called on the main (a.k.a. "UI") thread. This method is intended for drawing. However, you have these lines of code in that method:
UrlToImage img = new UrlToImage( imagesurl);
bit =img.getbitmap();
As you have implemented the UrlToImage class, that code is making a network call. Network calls should not be made on the UI thread. If you do so, your UI will hang/freeze.
What you should do is create a background worker (thread) that will go to the network to fetch your images. You can decide whether you need to load all images immediately in the background, or only load images as the user scrolls the ListField. When the images arrive (on the background thread), then you should tell the list field to redraw itself, row by row.
You might want to take a look at this recent answer, which performs lazy loading of imagery in the background. That answer is a little different, in that it uses a custom list, not the standard ListField. For a standard ListField, you can trigger a redraw of a list row with ListField#invalidate(int):
// image for row 'x' download complete. save image as member data
// that can be accessed in drawListRow().
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_list.invalidate(x);
}
});
i have written a java code to transfer files from one server to another using the concept of socket programming. now in the same code i also want to check for the network connection availability before each file is transferred. i also want that the files transferred should be transferred according to their numerical sequence. And while the files are being transferred the transfer progress of each file i.e the progress percentage bar should also be visible on the screen.
i will really appreciate if someone can help me with the code. i am posting the code i have written for file transfer.
ClientMain.java
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ClientMain {
private DirectoryTxr transmitter = null;
Socket clientSocket = null;
private boolean connectedStatus = false;
private String ipAddress;
String srcPath = null;
String dstPath = "";
public ClientMain() {
}
public void setIpAddress(String ip) {
this.ipAddress = ip;
}
public void setSrcPath(String path) {
this.srcPath = path;
}
public void setDstPath(String path) {
this.dstPath = path;
}
private void createConnection() {
Runnable connectRunnable = new Runnable() {
public void run() {
while (!connectedStatus) {
try {
clientSocket = new Socket(ipAddress, 3339);
connectedStatus = true;
transmitter = new DirectoryTxr(clientSocket, srcPath, dstPath);
} catch (IOException io) {
io.printStackTrace();
}
}
}
};
Thread connectionThread = new Thread(connectRunnable);
connectionThread.start();
}
public static void main(String[] args) {
ClientMain main = new ClientMain();
main.setIpAddress("10.6.3.92");
main.setSrcPath("E:/temp/movies/");
main.setDstPath("D:/tcp/movies");
main.createConnection();
}
}
(DirectoryTxr.java)
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class DirectoryTxr {
Socket clientSocket = null;
String srcDir = null;
String dstDir = null;
byte[] readBuffer = new byte[1024];
private InputStream inStream = null;
private OutputStream outStream = null;
int state = 0;
final int permissionReqState = 1;
final int initialState = 0;
final int dirHeaderSendState = 2;
final int fileHeaderSendState = 3;
final int fileSendState = 4;
final int fileFinishedState = 5;
private boolean isLive = false;
private int numFiles = 0;
private int filePointer = 0;
String request = "May I send?";
String respServer = "Yes,You can";
String dirResponse = "Directory created...Please send files";
String fileHeaderRecvd = "File header received ...Send File";
String fileReceived = "File Received";
String dirFailedResponse = "Failed";
File[] opFileList = null;
public DirectoryTxr(Socket clientSocket, String srcDir, String dstDir) {
try {
this.clientSocket = clientSocket;
inStream = clientSocket.getInputStream();
outStream = clientSocket.getOutputStream();
isLive = true;
this.srcDir = srcDir;
this.dstDir = dstDir;
state = initialState;
readResponse(); //starting read thread
sendMessage(request);
state = permissionReqState;
} catch (IOException io) {
io.printStackTrace();
}
}
private void sendMessage(String message) {
try {
sendBytes(request.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* Thread to read response from server
*/
private void readResponse() {
Runnable readRunnable = new Runnable() {
public void run() {
while (isLive) {
try {
int num = inStream.read(readBuffer);
if (num > 0) {
byte[] tempArray = new byte[num];
System.arraycopy(readBuffer, 0, tempArray, 0, num);
processBytes(tempArray);
}
} catch (SocketException se) {
System.exit(0);
} catch (IOException io) {
io.printStackTrace();
isLive = false;
}
}
}
};
Thread readThread = new Thread(readRunnable);
readThread.start();
}
private void sendDirectoryHeader() {
File file = new File(srcDir);
if (file.isDirectory()) {
try {
String[] childFiles = file.list();
numFiles = childFiles.length;
String dirHeader = "$" + dstDir + "#" + numFiles + "&";
sendBytes(dirHeader.getBytes("UTF-8"));
} catch (UnsupportedEncodingException en) {
en.printStackTrace();
}
} else {
System.out.println(srcDir + " is not a valid directory");
}
}
private void sendFile(String dirName) {
File file = new File(dirName);
if (!file.isDirectory()) {
try {
int len = (int) file.length();
int buffSize = len / 8;
//to avoid the heap limitation
RandomAccessFile raf = new RandomAccessFile(file, "rw");
FileChannel channel = raf.getChannel();
int numRead = 0;
while (numRead >= 0) {
ByteBuffer buf = ByteBuffer.allocate(1024 * 100000);
numRead = channel.read(buf);
if (numRead > 0) {
byte[] array = new byte[numRead];
System.arraycopy(buf.array(), 0, array, 0, numRead);
sendBytes(array);
}
}
System.out.println("Finished");
} catch (IOException io) {
io.printStackTrace();
}
}
}
private void sendHeader(String fileName) {
try {
File file = new File(fileName);
if (file.isDirectory())
return;//avoiding child directories to avoid confusion
//if want we can sent them recursively
//with proper state transitions
String header = "&" + fileName + "#" + file.length() + "*";
sendHeader(header);
sendBytes(header.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private void sendBytes(byte[] dataBytes) {
synchronized (clientSocket) {
if (outStream != null) {
try {
outStream.write(dataBytes);
outStream.flush();
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
private void processBytes(byte[] data) {
try {
String parsedMessage = new String(data, "UTF-8");
System.out.println(parsedMessage);
setResponse(parsedMessage);
} catch (UnsupportedEncodingException u) {
u.printStackTrace();
}
}
private void setResponse(String message) {
if (message.trim().equalsIgnoreCase(respServer) && state == permissionReqState) {
state = dirHeaderSendState;
sendDirectoryHeader();
} else if (message.trim().equalsIgnoreCase(dirResponse) && state == dirHeaderSendState) {
state = fileHeaderSendState;
if (LocateDirectory()) {
createAndSendHeader();
} else {
System.out.println("Vacant or invalid directory");
}
} else if (message.trim().equalsIgnoreCase(fileHeaderRecvd) && state == fileHeaderSendState) {
state = fileSendState;
sendFile(opFileList[filePointer].toString());
state = fileFinishedState;
filePointer++;
} else if (message.trim().equalsIgnoreCase(fileReceived) && state == fileFinishedState) {
if (filePointer < numFiles) {
createAndSendHeader();
}
System.out.println("Successfully sent");
} else if (message.trim().equalsIgnoreCase(dirFailedResponse)) {
System.out.println("Going to exit....Error ");
// System.exit(0);
} else if (message.trim().equalsIgnoreCase("Thanks")) {
System.out.println("All files were copied");
}
}
private void closeSocket() {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean LocateDirectory() {
boolean status = false;
File file = new File(srcDir);
if (file.isDirectory()) {
opFileList = file.listFiles();
numFiles = opFileList.length;
if (numFiles <= 0) {
System.out.println("No files found");
} else {
status = true;
}
}
return status;
}
private void createAndSendHeader() {
File opFile = opFileList[filePointer];
String header = "&" + opFile.getName() + "#" + opFile.length() + "*";
try {
state = fileHeaderSendState;
sendBytes(header.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
}
}
private void sendListFiles() {
createAndSendHeader();
}
}
(ServerMain.java)
public class ServerMain {
public ServerMain() {
}
public static void main(String[] args) {
DirectoryRcr dirRcr = new DirectoryRcr();
}
}
(DirectoryRcr.java)
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class DirectoryRcr {
String request = "May I send?";
String respServer = "Yes,You can";
String dirResponse = "Directory created...Please send files";
String dirFailedResponse = "Failed";
String fileHeaderRecvd = "File header received ...Send File";
String fileReceived = "File Received";
Socket socket = null;
OutputStream ioStream = null;
InputStream inStream = null;
boolean isLive = false;
int state = 0;
final int initialState = 0;
final int dirHeaderWait = 1;
final int dirWaitState = 2;
final int fileHeaderWaitState = 3;
final int fileContentWaitState = 4;
final int fileReceiveState = 5;
final int fileReceivedState = 6;
final int finalState = 7;
byte[] readBuffer = new byte[1024 * 100000];
long fileSize = 0;
String dir = "";
FileOutputStream foStream = null;
int fileCount = 0;
File dstFile = null;
public DirectoryRcr() {
acceptConnection();
}
private void acceptConnection() {
try {
ServerSocket server = new ServerSocket(3339);
socket = server.accept();
isLive = true;
ioStream = socket.getOutputStream();
inStream = socket.getInputStream();
state = initialState;
startReadThread();
} catch (IOException io) {
io.printStackTrace();
}
}
private void startReadThread() {
Thread readRunnable = new Thread() {
public void run() {
while (isLive) {
try {
int num = inStream.read(readBuffer);
if (num > 0) {
byte[] tempArray = new byte[num];
System.arraycopy(readBuffer, 0, tempArray, 0, num);
processBytes(tempArray);
}
sleep(100);
} catch (SocketException s) {
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException i) {
i.printStackTrace();
}
}
}
};
Thread readThread = new Thread(readRunnable);
readThread.start();
}
private void processBytes(byte[] buff) throws InterruptedException {
if (state == fileReceiveState || state == fileContentWaitState) {
//write to file
if (state == fileContentWaitState)
state = fileReceiveState;
fileSize = fileSize - buff.length;
writeToFile(buff);
if (fileSize == 0) {
state = fileReceivedState;
try {
foStream.close();
} catch (IOException io) {
io.printStackTrace();
}
System.out.println("Received " + dstFile.getName());
sendResponse(fileReceived);
fileCount--;
if (fileCount != 0) {
state = fileHeaderWaitState;
} else {
System.out.println("Finished");
state = finalState;
sendResponse("Thanks");
Thread.sleep(2000);
System.exit(0);
}
System.out.println("Received");
}
} else {
parseToUTF(buff);
}
}
private void parseToUTF(byte[] data) {
try {
String parsedMessage = new String(data, "UTF-8");
System.out.println(parsedMessage);
setResponse(parsedMessage);
} catch (UnsupportedEncodingException u) {
u.printStackTrace();
}
}
private void setResponse(String message) {
if (message.trim().equalsIgnoreCase(request) && state == initialState) {
sendResponse(respServer);
state = dirHeaderWait;
} else if (state == dirHeaderWait) {
if (createDirectory(message)) {
sendResponse(dirResponse);
state = fileHeaderWaitState;
} else {
sendResponse(dirFailedResponse);
System.out.println("Error occurred...Going to exit");
System.exit(0);
}
} else if (state == fileHeaderWaitState) {
createFile(message);
state = fileContentWaitState;
sendResponse(fileHeaderRecvd);
} else if (message.trim().equalsIgnoreCase(dirFailedResponse)) {
System.out.println("Error occurred ....");
System.exit(0);
}
}
private void sendResponse(String resp) {
try {
sendBytes(resp.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private boolean createDirectory(String dirName) {
boolean status = false;
dir = dirName.substring(dirName.indexOf("$") + 1, dirName.indexOf("#"));
fileCount = Integer.parseInt(dirName.substring(dirName.indexOf("#") + 1, dirName.indexOf("&")));
if (new File(dir).mkdir()) {
status = true;
System.out.println("Successfully created directory " + dirName);
} else if (new File(dir).mkdirs()) {
status = true;
System.out.println("Directories were created " + dirName);
} else if (new File(dir).exists()) {
status = true;
System.out.println("Directory exists" + dirName);
} else {
System.out.println("Could not create directory " + dirName);
status = false;
}
return status;
}
private void createFile(String fileName) {
String file = fileName.substring(fileName.indexOf("&") + 1, fileName.indexOf("#"));
String lengthFile = fileName.substring(fileName.indexOf("#") + 1, fileName.indexOf("*"));
fileSize = Integer.parseInt(lengthFile);
dstFile = new File(dir + "/" + file);
try {
foStream = new FileOutputStream(dstFile);
System.out.println("Starting to receive " + dstFile.getName());
} catch (FileNotFoundException fn) {
fn.printStackTrace();
}
}
private void writeToFile(byte[] buff) {
try {
foStream.write(buff);
} catch (IOException io) {
io.printStackTrace();
}
}
private void sendBytes(byte[] dataBytes) {
synchronized (socket) {
if (ioStream != null) {
try {
ioStream.write(dataBytes);
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
}
ClientMain.java and DirectoryTxr.java are the two classes under client application. ServerMain.java and DirectoryRcr.java are the two classes under Server application.
run the ClientMain.java and ServerMain.java
You can sort an array using Arrays.sort(...)
ie
String[] childFiles = file.list();
Arrays.sort(childFiles);
As I understand it, this will sort the files in natural order, based on the file name.
You can modify this by passing a custom Comparator...
Arrays.sort(childFiles, new Comparator<File>() {...}); // Fill out with your requirements...
Progress monitoring will come down to your requirements. Do you want to see only the overall progress of the number of files, the individual files, a combination of both?
What I've done in the past is pre-iterated the file list, calculated the total number of bytes to be copied and used a ProgressMonitor to display the overall bytes been copied...
Otherwise you will need to supply your own dialog. In either case, you will need use SwingUtilities.invokeLater to update them correctly.
Check out Concurrency in Swing for more details.
Network connectivity is subjective. You could simply send a special "message" to there server and wait for a response, but this only suggests that the message was sent and a recipt was received. It could just as easily fail when you start transfering the file again...
I used following code to preview an image from an url.
Bitmap bannerImage=Bitmap.getBitmapResource("http://www.asianmirror.lk/english/images/stories/demo/hot_news/top_news/sanga1_latest.jpg");
BitmapField banner=new BitmapField(bannerImage);
add(banner);
But the image doesn't preview in the UI. Is there is special way to preview images from a url in blackberry.(I means, shall I put the Image in to a temporary Array to preview the Image?) Thank you
try this -
URLBitmapField wmf= new util.URLBitmapField("http://www.asianmirror.lk/english/images/stories/demo/hot_news/top_news/sanga1_latest.jpg")
add(wmf);
//URLBitmapField class is given below-
public class URLBitmapField extends BitmapField implements URLDataCallback {
EncodedImage result=null ;
public static Bitmap myImage;
public static EncodedImage _encoded_img=null ;
int _imgWidth = 140;
int _imgHeight = 140;
int _imgMargin = 10;
public URLBitmapField(String url) {
try {
http_image_data_extrator.getWebData(url, this);
}
catch (Exception e) {}
}
public Bitmap getBitmap() {
if (_encoded_img == null) return null;
return _encoded_img.getBitmap();
}
public void callback(final String data) {
if (data.startsWith("Exception")) return;
try {
byte[] dataArray = data.getBytes();
//bitmap = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length);//no scale
_encoded_img = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length); // with scale
_encoded_img = sizeImage(_encoded_img, _imgWidth, _imgHeight);
constants.image=_encoded_img;
//myImage=cropImage(_encoded_img.getBitmap());
setImage(_encoded_img);
UiApplication.getUiApplication().getActiveScreen().invalidate();
}
catch (final Exception e){}
}
public EncodedImage sizeImage(EncodedImage image, int width, int height) {
int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
int currentHeightFixed32 = Fixed32.toFP(image.getHeight());
int requiredWidthFixed32 = Fixed32.toFP(width);
int requiredHeightFixed32 = Fixed32.toFP(height);
int scaleXFixed32 = Fixed32.div(currentWidthFixed32,
requiredWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32,
requiredHeightFixed32);
result = image.scaleImage32(scaleXFixed32, scaleYFixed32);
return result;
}
public class http_image_data_extrator {
static String url_="";
static StringBuffer rawResponse=null;
//static String result = null;
public static void getWebData(String url, final URLDataCallback callback) throws IOException {
//url_=url;
HttpConnection connection = null;
InputStream inputStream = null;
try {
if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
&& RadioInfo
.areWAFsSupported(RadioInfo.WAF_WLAN)) {
url += ";interface=wifi";
}
connection = (HttpConnection) Connector.open(url, Connector.READ, true);
String location=connection.getHeaderField("location");
if(location!=null){
if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
&& RadioInfo
.areWAFsSupported(RadioInfo.WAF_WLAN)) {
location += ";interface=wifi";
}
connection = (HttpConnection) Connector.open(location, Connector.READ, true);
}else{
connection = (HttpConnection) Connector.open(url, Connector.READ, true);
}
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData))) {
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK){
throw new IOException("HTTP response code: "+ responseCode);
}
final String result = rawResponse.toString();
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run(){
callback.callback(result);
}
});
}
catch (final Exception ex) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
callback.callback("Exception (" + ex.getClass() + "): " + ex.getMessage());
}
});
}
}
}
public interface URLDataCallback {
public void callback(String data);
}
This is code i am using to fetch image form url but i am getting blanck screen please help.
Code For HttpConnection:
StringBuffer raw = new StringBuffer();
HttpConnection _c = null;
InputStream _is = null;
try
{
_c = (HttpConnection)Connector.open(url);
_c.getHeaderField("Location");
int rc = _c.getResponseCode();
if (rc != HttpConnection.HTTP_OK)
{
throw new IOException("HTTP response code: " + rc);
}
_is = _c.openInputStream();
_c.getType();
int len = (int)_c.getLength();
{
data = new byte[256];
int size = 0;
while ( -1 != (len = _is.read(data)) )
{
raw.append(new String(data, 0, len));
size += len;
}
String retVal = raw.toString();
// .alert(retVal);
return retVal+"URL is"+url;
}
}
catch (Exception e)
{
throw new IllegalArgumentException("Not an HTTP URL");
}
finally
{
if (_is != null)
_is.close();
if (_c != null)
_c.close();
}
Code to get Image from perticuler URL:
public static Bitmap getImage(String url)
{
Bitmap bitmap;
EncodedImage bmp = EncodedImage.createEncodedImage(data, 0, data.length);
bitmap=bmp.getBitmap();
return bitmap;
}
Following code i am using to display image on MainScreen:
Bitmap bt=HttpUtils.getImage("http://www.eng.chula.ac.th/files/building.jpg");
BitmapField bmp=new BitmapField(bt);
bmp.setBitmap(bt);
add(bmp);
Try this code -
URLBitmapField post_img= new URLBitmapField(image_url);
add(post_img);
import net.rim.device.api.math.Fixed32;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
public class URLBitmapField extends BitmapField implements URLDataCallback {
EncodedImage result = null;
public static EncodedImage _encoded_img = null;
int _imgWidth = 52;
int _imgHeight = 62;
int _imgMargin = 10;
public URLBitmapField(String url) {
try {
http_image_data_extrator.getWebData(url, this);
}
catch (Exception e) {}
}
public Bitmap getBitmap() {
if (_encoded_img == null) return null;
return _encoded_img.getBitmap();
}
public void callback(final String data) {
if (data.startsWith("Exception")) return;
try {
byte[] dataArray = data.getBytes();
//bitmap = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length);//no scale
_encoded_img = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length); // with scale
_encoded_img = sizeImage(_encoded_img, _imgWidth, _imgHeight);
setImage(_encoded_img);
UiApplication.getUiApplication().getActiveScreen().invalidate();
}
catch (final Exception e){}
}
public EncodedImage sizeImage(EncodedImage image, int width, int height) {
int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
int currentHeightFixed32 = Fixed32.toFP(image.getHeight());
int requiredWidthFixed32 = Fixed32.toFP(width);
int requiredHeightFixed32 = Fixed32.toFP(height);
int scaleXFixed32 = Fixed32.div(currentWidthFixed32,
requiredWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32,
requiredHeightFixed32);
result = image.scaleImage32(scaleXFixed32, scaleYFixed32);
return result;
}
}
public interface URLDataCallback {
public void callback(String data);
}
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.system.WLANInfo;
import net.rim.device.api.ui.UiApplication;
public class http_image_data_extrator {
static String url_="";
static StringBuffer rawResponse=null;
//static String result = null;
public static void getWebData(String url, final URLDataCallback callback) throws IOException {
//url_=url;
HttpConnection connection = null;
InputStream inputStream = null;
try {
if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
&& RadioInfo
.areWAFsSupported(RadioInfo.WAF_WLAN)) {
url += ";interface=wifi";
}
connection = (HttpConnection) Connector.open(url, Connector.READ, true);
String location=connection.getHeaderField("location");
if(location!=null){
if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
&& RadioInfo
.areWAFsSupported(RadioInfo.WAF_WLAN)) {
location += ";interface=wifi";
}
connection = (HttpConnection) Connector.open(location, Connector.READ, true);
}else{
connection = (HttpConnection) Connector.open(url, Connector.READ, true);
}
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData))) {
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK){
throw new IOException("HTTP response code: "+ responseCode);
}
final String result = rawResponse.toString();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run(){
callback.callback(result);
}
});
}
catch (final Exception ex) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
callback.callback("Exception (" + ex.getClass() + "): " + ex.getMessage());
}
});
}
}
}