Handwriting recognition from image to string - java

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

Related

showing data and images in list field from json Like Lazy loading Blackberry

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

program to show a progress bar while transferring all files from one server to another in java

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...

Validating image dimensions in Wicket

im developing a webbapp wich receives image resources from users, but i want to validate these image to be uploaded to have specific dimensions like 600X800 etc.
I am trying to fin answers but im running out of options :).
It would be great if someone has done this before.
Thanks your help will be apreciated
Try
BufferedImage bi = ImageIO.read (file);
bi.getWidth();//width
bi.getHeight ();//height
Finally i did find the way to do it: we first get the file that its going to be uploaded, then i use a created class wich i found here on stack overflow, to find width and height of dimesions, i just play with if's then, heres the code, hope helps someone!!
public class AddPromo extends WebPage {
/**
*
*/
private FileUploadField fileUpload;
private String UPLOAD_FOLDER = "..\\Promociones\\";
private static final long serialVersionUID = 1L;
#SuppressWarnings({ "rawtypes", "unchecked" })
public AddPromo(){
add(new Label("user",ActiveUser.USER));
//Add Feedback panel
add(new FeedbackPanel("feedback_2"));
//LOGOUT LINK
Logout logoutLink = new Logout("logout");
add(logoutLink);
//Add backlink to SuccesPage
add(new Link("link_atras"){
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public void onClick(){
SuccesPage nueva = new SuccesPage("",1);
setResponsePage(nueva);
}
});
//Definitions for date attributes
final Locale selectedLocale = Session.get().getLocale();
add(new StaticImage("image_test",new Model("http://1-ps.googleusercontent.com/h/www.bizreport.com/2011/02/03/200x200xandroid-logo-200x200.jpg.pagespeed.ic.SONOBLzFc5.jpg")));
Form<?> form = new Form<Void>("form") {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void onSubmit() {
JPEGDim dims = new JPEGDim();
final FileUpload uploadedFile = fileUpload.getFileUpload();
if (uploadedFile != null) {
// write to a new file
File newFile = new File(UPLOAD_FOLDER
+ uploadedFile.getClientFileName());
try {
final Dimension d = dims.getJPEGDimension(newFile);
if (d.getWidth()==1024 || d.getHeight()==768 ) {
try {
if (newFile.exists()) {
newFile.delete();
}
newFile.createNewFile();
uploadedFile.writeTo(newFile);
info("saved file: " + uploadedFile.getClientFileName());
info("Imagen cumple con dimensiones " + d.getHeight() + " x " + d.getWidth());
} catch (Exception e) {
throw new IllegalStateException("Error "+e.toString());
}
} else {
error("Archivo no valido... " + + d.getHeight() + " x " + d.getWidth());
}
} catch (IOException e1) {
// TODO Auto-generated catch block
error(e1.toString());
}
}
}
};
// Enable multipart mode (need for uploads file)
form.setMultiPart(true);
// max upload size, 10k
form.setMaxSize(Bytes.megabytes(10));
form.add(fileUpload = new FileUploadField("fileUpload"));
add(form);
}
class JPEGDim {
public Dimension getJPEGDimension(File f) throws IOException {
FileInputStream fis = new FileInputStream(f);
// check for SOI marker
if (fis.read() != 255 || fis.read() != 216)
throw new RuntimeException("SOI (Start Of Image) marker 0xff 0xd8 missing");
Dimension d = null;
while (fis.read() == 255) {
int marker = fis.read();
int len = fis.read() << 8 | fis.read();
if (marker == 192) {
fis.skip(1);
int height = fis.read() << 8 | fis.read();
int width = fis.read() << 8 | fis.read();
d = new Dimension(width, height);
break;
}
fis.skip(len - 2);
}
fis.close();
return d;
}
}
}

Java Serializable Saving

Well I have this class for a game I'm making, and I'm trying to save the ArrayList notes. When I logout, it properly print the size, for example if I have 5 notes, when I log out notes.getSize() would be 5, but when I log in, it gets reset back to nothing. Why isn't notes saving?
public class Notes implements Serializable {
private static final long serialVersionUID = -4947870743226160329L;
private ArrayList<Note> notes = new ArrayList<Note>(30);
public class Note implements Serializable {
private static final long serialVersionUID = -4589885080580317958L;
private int color = 0;
private String text = "";
public Note(int color, String text) {
this.setColor(color);
this.setText(text);
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setColor(int color) {
this.color = color;
}
public int getColor() {
return color;
}
}
private transient Player player;
public Notes(Player p) {
this.player = p;
}
public void addNote(String text) {
System.out.println("Note Text: "+text);
if (text.length() > 50) {
player.getPackets().sendGameMessage("You can only enter notes up to 50 characters!");
return;
}
if (notes.size() < 30) {
notes.add(new Note(0, text));
} else {
player.getPackets().sendGameMessage("You cannot add more then 30 notes!");
return;
}
int NoteId = notes.size() - 1;
player.getPackets().sendConfig(1439, NoteId);
player.getTemporaryAttributtes().put("selectedNote", NoteId);
refreshNotes(false);
}
public void addNote(String text, int color) {
notes.add(new Note(color, text));
}
public void loadNotes() {
player.getPackets().sendIComponentSettings(34, 9, 0, 30, 2621470);
player.getPackets().sendHideIComponent(34, 3, false);
player.getPackets().sendHideIComponent(34, 44, false);
player.getPackets().sendIComponentText(34, 13, "Loading notes<br>Please wait...");
player.getPackets().sendConfig(1439, -1);
refreshNotes(true);
}
public void refreshNotes(boolean sendStartConfigs) {
for (int i = 0; i < 30; i++) {
player.getPackets().sendGlobalString(149 + i, i < notes.size() ? notes.get(i).getText() : "");
}
if (sendStartConfigs) {
for (int i = 1430; i < 1450; i++)
player.getPackets().sendConfig(i, i);
}
player.getPackets().sendConfig(1440, getFirstTotalColorValue());
player.getPackets().sendConfig(1441, getSecondTotalColorValue());
}
public int intColorValue(int color, int noteId) {
return (int) (Math.pow(4, noteId) * color);
}
public int getFirstTotalColorValue() {
int Color = 0;
for (int i = 0; i < 15; i++) {
if (notes.size() > i)
Color += intColorValue(notes.get(i).getColor(), i);
}
return Color;
}
public int getSecondTotalColorValue() {
int color = 0;
for (int i = 0; i < 15; i++) {
if (notes.size() > (i + 16))
color += intColorValue(notes.get(i + 16).getColor(), i);
}
return color;
}
public void deleteSelectedNote() {
if ((int)player.getTemporaryAttributtes().get("selectedNote") > -1) {
int slot = (int) player.getTemporaryAttributtes().get("selectedNote");
notes.remove(slot);
player.getTemporaryAttributtes().put("selectedNote", -1);
player.getPackets().sendConfig(1439, -1);
refreshNotes(false);
}
}
public void clear() {
notes.clear();
refreshNotes(false);
}
public void editNote(String string, int index) {
notes.get(index).setText(string);
refreshNotes(false);
}
public void setColor(int color, int index) {
notes.get(index).setColor(color);
refreshNotes(false);
}
public void deleteNote(int slot) {
notes.remove(slot);
refreshNotes(false);
}
public void setNotes(ArrayList<Note> setNotes) {
notes = setNotes;
refreshNotes(false);
}
}
And here is the class I manage saving/loading in
public class SerializableFilesManager {
private static final String PATH = "data/characters/";
private static final String BACKUP_PATH = "data/charactersBackup/";
public synchronized static final boolean containsPlayer(String username) {
return new File(PATH + username + ".p").exists();
}
public synchronized static Player loadPlayer(String username) {
try {
return (Player) loadSerializedFile(new File(PATH + username + ".p"));
} catch (Throwable e) {
Logger.handle(e);
}
try {
Logger.log("SerializableFilesManager", "Recovering account: "
+ username);
return (Player) loadSerializedFile(new File(BACKUP_PATH + username
+ ".p"));
} catch (Throwable e) {
Logger.handle(e);
}
return null;
}
public static boolean createBackup(String username) {
try {
Utils.copyFile(new File(PATH + username + ".p"), new File(
BACKUP_PATH + username + ".p"));
return true;
} catch (Throwable e) {
Logger.handle(e);
return false;
}
}
public synchronized static void savePlayer(Player player) {
try {
storeSerializableClass(player, new File(PATH + player.getUsername()
+ ".p"));
} catch (ConcurrentModificationException e) {
//happens because saving and logging out same time
} catch (Throwable e) {
Logger.handle(e);
}
}
public static final Object loadSerializedFile(File f) throws IOException,
ClassNotFoundException {
if (!f.exists())
return null;
ObjectInputStream in = new ObjectInputStream(new FileInputStream(f));
Object object = in.readObject();
in.close();
return object;
}
public static final void storeSerializableClass(Serializable o, File f)
throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(o);
out.close();
}
private SerializableFilesManager() {
}
}
Do NOT mark Player as transient, cause you are saving it, transient will prevent if from
getting saved, and will bring player to the default value of null, when deserialized.
Have you made the player class serializable ?
Its the Entire object graph that gets serialized or none... the purpose of transient is to make a particular member to be left off during serialization so that, the process of serialization goes smoothly.
For example, Suppose in a game we want to keep the progress of the player and hours of play for that session, but not the starting and ending times. So the starting and ending time can be made transient.
you should save your ArrayList with:
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream("filename",false);
out = new ObjectOutputStream(fos);
out.writeObject(notes);
out.close();
System.out.println("Object Persisted");
} catch (IOException ex) {
ex.printStackTrace();
}
and when you open your project, import you Arraylist with:
FileInputStream fos;
try {
fos = new FileInputStream("filename");
ObjectInputStream oos = new ObjectInputStream(fos);
notes=(ArrayList) oos.readObject();
fos.close();
{
catch {
}
Thats because your Player is transient...I've tried to demonstrate your logic on other example...when Player was set to private, serialization has been successful and all data has been loaded back. Otherwise, when transient, Player reference was null, it loads only other serialized fields like int. When theres only a transient Player as field in class, the NullPointerException occurs, but ArrayList has size > 0.

Java:Download Restart

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

Categories