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());
}
});
}
}
}
Related
Tried to send sms from Java application by creating three Java Class given below 1. Credentials 2. URLConnector 3. Way2Sms and running Way2Sms Class, but getting authentication failed! because of responseCode is 404 or 408 in Way2Sms java login method...any help to resolve this would be appreciated....
**Way2Sms.java**
package way2sms;
/* Code from this site
*
* http://jtechbits.blogspot.in/2011/06/sending-sms-through-way2sms-in-java.html
*
* */
import java.net.HttpURLConnection;
import java.util.Calendar;
public class Way2Sms
{
private static int responseCode = -1;
private static String userCredentials;
private static String cookie;
private static String token;
private static String site;
private static String actionStr;
private static String random1;
private static String random2;
private static String random3;
private static Credentials credentials = new Credentials();
public static void main(String[] args)
{
login("mynumber", "mypassword");
sendSMS("9663384741", "Hello");
System.out.println("Message has been sent successfully!");
}
private static void setProxy(String host, int port)
{
URLConnector.setProxy(host, port);
}
private static void login(String uid, String pwd)
{
getSite();
preHome();
String location = null;
credentials.set("username", uid);
credentials.append("password", pwd);
credentials.append("userLogin", "no");
credentials.append("button", "Login");
userCredentials = credentials.getUserCredentials();
URLConnector.connect("http://" + site + "/w2sauth.action", false, "POST", cookie, userCredentials);
**responseCode = URLConnector.getResponseCode();**
if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
{
exit("authentication failed!");
}
else
{
location = URLConnector.getLocation();
URLConnector.disconnect();
URLConnector.connect(location, false, "GET", cookie, null);
responseCode = URLConnector.getResponseCode();
if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
{
exit("redirection failed!");
URLConnector.disconnect();
}
}
}
private static void sendSMS(String receiversMobNo, String msg)
{
getActionString();
credentials.reset();
credentials.set("t_15_k_5", random1);
credentials.append("i_m", "sn2sms");
credentials.append("m_15_b", random2);
if(actionStr != null)
credentials.append("kriya", actionStr);
else
{
exit("Action string missing!");
credentials.append(random3, "");
credentials.append(random1, token);
credentials.append("catnamedis", "Birthday");
credentials.append("chkall", "on");
credentials.append("diffNo", Calendar.getInstance().getTime().toString().split(" ")[3]);
credentials.append(random2, receiversMobNo);
credentials.append("txtLen", "" + (140 - msg.length()));
credentials.append("textArea", msg);
userCredentials = credentials.getUserCredentials();
URLConnector.connect("http://" + site + "/jsp/w2ssms.action", false, "POST", cookie + "; 12489smssending34908=67547valdsvsikerexzc435457", userCredentials);
responseCode = URLConnector.getResponseCode();
if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
exit("sendSMS failed!");
URLConnector.disconnect();
}
}
private static void sendSMS(String[] receiversMobNos, String msg)
{
int noOfReceivers = receiversMobNos.length;
for(int i = 0; i < noOfReceivers; i++)
sendSMS(receiversMobNos[i], msg);
}
private static void getSite()
{
URLConnector.connect("http://www.way2sms.com/", false, "GET", null, null);
responseCode = URLConnector.getResponseCode();
if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
exit("getSite failed!");
else
{
site = URLConnector.getLocation();
if(site != null)
site = site.substring(7, site.length() - 1);
}
URLConnector.disconnect();
}
private static void preHome()
{
URLConnector.connect("http://" + site + "/content/prehome.jsp", false, "GET", null, null);
responseCode = URLConnector.getResponseCode();
if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
exit("preHome failed");
else
{
cookie = URLConnector.getCookie();
token = cookie.substring(cookie.indexOf("~") + 1);
}
URLConnector.disconnect();
}
private static void getActionString()
{
URLConnector.connect("http://" + site + "/jsp/SingleSMS.jsp?Token=" + token, false, "GET", cookie, null);
responseCode = URLConnector.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_OK)
{
String str = URLConnector.getResponse();
String aStr = "id='kriya' value='";
int index = str.indexOf(aStr);
if(index > 0)
{
index = index + aStr.length();
StringBuffer actionStringChars = new StringBuffer();
char ch = str.charAt(index);
while(ch != '\'')
{
actionStringChars.append(ch);
ch = str.charAt(++index);
}
actionStr = actionStringChars.toString();
getRandom1(str);
getRandom2(str);
getRandom3(str);
}
}
else
{
exit("getActionString failed!");
URLConnector.disconnect();
}
}
private static void getRandom1(String str)
{
String aStr = "id='t_15_k_5'";
int index = str.indexOf(aStr);
if(index > 0)
{
index = index + aStr.length();
StringBuffer random1Chars = new StringBuffer();
char ch = str.charAt(index);
if(ch == '>')
{
ch = str.charAt(++index);
while(ch != '<')
{
random1Chars.append(ch);
ch = str.charAt(++index);
}
}
else
{
index += 8;
ch = str.charAt(index);
while(ch != '\'')
{
random1Chars.append(ch);
ch = str.charAt(++index);
}
}
random1 = random1Chars.toString();
}
}
private static void getRandom2(String str)
{
String aStr = "id='m_15_b'";
int index = str.indexOf(aStr);
if(index > 0)
{
index = index + aStr.length();
StringBuffer random2Chars = new StringBuffer();
char ch = str.charAt(index);
if(ch == '>')
{
ch = str.charAt(++index);
while(ch != '<')
{
random2Chars.append(ch);
ch = str.charAt(++index);
}
}
else
{
index += 8;
ch = str.charAt(index);
while(ch != '\'')
{
random2Chars.append(ch);
ch = str.charAt(++index);
}
}
random2 = random2Chars.toString();
}
}
private static void getRandom3(String str)
{
String aStr = "dnipb";
int index = str.lastIndexOf(aStr);
if(index > 0)
{
index -= 40;
StringBuffer random3Chars = new StringBuffer();
char ch = str.charAt(index);
while(ch != '\"')
{
random3Chars.append(ch);
ch = str.charAt(--index);
}
random3 = random3Chars.reverse().toString();
}
}
private static void exit(String errorMsg)
{
System.err.println(errorMsg);
System.exit(1);
}
}
**URLConnector.java**
package way2sms;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ByteArrayOutputStream;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
public class URLConnector {
private static HttpURLConnection connection;
private static Proxy proxy;
public static void setProxy(String host, int port) {
proxy = new Proxy(Proxy.Type.HTTP, java.net.InetSocketAddress.createUnresolved(host, port));
}
public static void connect(String urlPath, boolean redirect, String method, String cookie, String credentials)
{
try
{
URL url = new URL(urlPath);
if(null != proxy)
connection = (HttpURLConnection) url.openConnection(proxy);
else
{
connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(redirect);
if(cookie != null)
connection.setRequestProperty("Cookie", cookie);
if(method != null && method.equalsIgnoreCase("POST"))
{
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.4) Gecko/20100101 Firefox/10.0.4");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
if(credentials != null)
{
DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
wr.writeBytes (credentials);
wr.flush ();
wr.close ();
}
}
}
catch(Exception exception)
{
System.out.println("Connection error");
}
}
public static String getCookie()
{
String cookie = null;
if(connection != null)
{
String headerName=null;
for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++)
{
if (headerName.equals("Set-Cookie"))
{
cookie = connection.getHeaderField(i).split(";")[0];
break;
}
}
}
return cookie;
}
public static String getLocation()
{
String location = null;
if(connection != null)
{
String headerName=null;
for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++)
{
if (headerName.equals("Location"))
{
location = connection.getHeaderField(i).split(";")[0];
break;
}
}
}
return location;
}
public static int getResponseCode()
{
int responseCode = -1;
if(connection != null)
{
try
{
responseCode = connection.getResponseCode();
}
catch(Exception exception)
{
System.err.println("Response code error");
}
}
return responseCode;
}
public static String getResponse()
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if(connection != null)
{
try
{
InputStream is = connection.getInputStream();
int next = is.read();
while (next > -1)
{
bos.write(next);
next = is.read();
}
bos.flush();
}
catch(Exception exception)
{
System.err.println("Response error");
}
}
return new String(bos.toByteArray());
}
public static String getErrorMessage()
{
StringBuilder errorMessage = new StringBuilder();
if(connection != null)
{
try
{
InputStream es = connection.getErrorStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(es));
String line;
while((line = rd.readLine()) != null)
{
errorMessage.append(line);
errorMessage.append("\r\n");
}
rd.close();
}
catch(Exception exception)
{
System.err.println("Error in getting error message");
}
}
return errorMessage.toString();
}
public static void disconnect()
{
if(connection != null)
connection.disconnect();
}
}
**Credentials.java**
package way2sms;
import java.net.URLEncoder;
import java.util.ArrayList;
public class Credentials
{
private ArrayList< String > list = new ArrayList< String >();
public void set(String name, String value) {
StringBuilder buffer = new StringBuilder();
buffer.append(name);
buffer.append("=");
buffer.append(getUTF8String(value));
add(buffer.toString());
}
public void append(String name, String value)
{
StringBuilder buffer = new StringBuilder();
buffer.append("&");
buffer.append(name);
buffer.append("=");
buffer.append(getUTF8String(value));
add(buffer.toString());
}
private void add(String item)
{
list.add(item);
}
private String getUTF8String(String value)
{
String encodedValue = null;
try
{
encodedValue = URLEncoder.encode(value, "UTF-8");
}
catch(Exception exception)
{
System.err.println("Encoding error! Please try agian...");
System.exit(1);
}
return encodedValue;
}
public boolean isEmpty()
{
return list.isEmpty();
}
public void reset()
{
list.clear();
}
public String getUserCredentials()
{
StringBuilder buffer = new StringBuilder();
int size = list.size();
for(int i = 0; i < size; i++)
{
buffer.append(list.get(i));
}
return buffer.toString();
}
}
This is due to human verification code that is Captcha. Now you can't login with previous api to send sms. You need to contact with your service provider.
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 wanted to decode video frames without using an extractor. So I just tried a small sample, where I use media extractor but I don't do extractor.readsample() to copy the bitstream data into the input buffer instead I use FFmpeg parser, inside JNI, where I memcopy the video frames into the input byte buffers and then queued the input buffer.
But when I call decoder.dequeueOutputBuffer(info, 10000):
It returns MediaCodec.INFO_TRY_AGAIN_LATER
While it works fine if I use extractor.readsample()
Java Side:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import android.app.Activity;
import android.media.MediaCodec;
import android.media.MediaCodec.BufferInfo;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class VideoBrowser extends Activity implements SurfaceHolder.Callback {
private static final String SAMPLE = Environment.getExternalStorageDirectory() + "/obama.mp4";
private PlayerThread mPlayer = null;
private static native < jintArray > int AVinitializecntxt(String strl, jintArray arr);
private native int AVREADVIDEO(byte[] array);
public int FLAG = 0;
public int jk = 0;
File f1;
FileOutputStream f;
static {
Log.i("ABCD", "BEFORE");
System.loadLibrary("ffmpeg");
System.loadLibrary("ffmpeg-test-jni");
Log.i("ABCD", "Success");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SurfaceView sv = new SurfaceView(this);
sv.getHolder().addCallback(this);
setContentView(sv);
int val;
int[] array = new int[6];
int END_OF_FILE = 0;
int aud_stream = 0;
int vid_stream = 0;
String urlString = "/mnt/sdcard/obama.mp4";
f1 = new File("/mnt/sdcard/t.h264");
try {
f = new FileOutputStream(f1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// This is where I call the function to initialize the ffmpeg inside JNI
val = AVinitializecntxt(urlString, array);
FLAG = val;
Log.i("ABCD", "FLAG : " + FLAG + val);
}
protected void onDestroy() {
super.onDestroy();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (mPlayer == null) {
mPlayer = new PlayerThread(holder.getSurface());
mPlayer.start();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mPlayer != null) {
mPlayer.interrupt();
}
}
private class PlayerThread extends Thread {
private MediaExtractor extractor;
private MediaCodec decoder;
private Surface surface;
// private VideoPlayer VideoPlayerAPIInterfaceClass = new VideoPlayer();
public PlayerThread(Surface surface) {
this.surface = surface;
}
#Override
public void run() {
if (FLAG == 1) {
extractor = new MediaExtractor();
extractor.setDataSource(SAMPLE);
for (int i = 0; i < extractor.getTrackCount(); i++) {
MediaFormat format = extractor.getTrackFormat(i);
String mime = format.getString(MediaFormat.KEY_MIME);
if (mime.startsWith("video/")) {
extractor.selectTrack(i);
decoder = MediaCodec.createDecoderByType("video/avc");
// Log.i("ABCD", "MIME : " + mime);
decoder.configure(format, surface, null, 0);
break;
}
}
if (decoder == null) {
Log.e("DecodeActivity", "Can't find video info!");
return;
}
decoder.start();
ByteBuffer[] inputBuffers = decoder.getInputBuffers();
ByteBuffer[] outputBuffers = decoder.getOutputBuffers();
BufferInfo info = new BufferInfo();
boolean isEOS = false;
long startMs = System.currentTimeMillis();
int outIndex1 = -1;
while (outIndex1 < 0) {
outIndex1 = decoder.dequeueOutputBuffer(info, 10000);
Log.i("ABCD", "etgeuieoy");
}
while (!Thread.interrupted()) {
if (!isEOS) {
int inIndex = decoder.dequeueInputBuffer(10000);
if (inIndex >= 0) {
ByteBuffer buffer = inputBuffers[inIndex];
// int sampleSize = extractor.readSampleData(buffer, 0);
byte[] bytes = new byte[buffer.capacity()];
// This is where we call JNI function to memcopy the encoded bitstream into the input buffer
int sampleSize = [b] AVREADVIDEO[/b](bytes);
buffer.clear(); buffer.put(bytes, 0, sampleSize);
if (sampleSize < 0) {
// We shouldn't stop the playback at this point, just pass the EOS
// flag to decoder, we will get it again from the
// dequeueOutputBuffer
// Log.d("DecodeActivity", "InputBuffer BUFFER_FLAG_END_OF_STREAM");
decoder.queueInputBuffer(inIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
isEOS = true;
} else {
decoder.queueInputBuffer(inIndex, 0, sampleSize, 0, 0);
extractor.advance();
}
}
}
int outIndex = decoder.dequeueOutputBuffer(info, 10000);
switch (outIndex) {
case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED:
Log.d("DecodeActivity", "INFO_OUTPUT_BUFFERS_CHANGED");
outputBuffers = decoder.getOutputBuffers();
break;
case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED:
Log.d("DecodeActivity", "New format " + decoder.getOutputFormat());
break;
case MediaCodec.INFO_TRY_AGAIN_LATER:
Log.d("DecodeActivity", "dequeueOutputBuffer timed out!");
break;
default:
ByteBuffer buffer = outputBuffers[outIndex];
Log.v("DecodeActivity", "We can't use this buffer but render it due to the API limit, " + buffer);
// We use a very simple clock to keep the video FPS, or the video
// playback will be too fast
while (info.presentationTimeUs / 1000 > System.currentTimeMillis() - startMs) {
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
// Log.i("ABCD", "RELEASING OUTPUT BUFFER");
decoder.releaseOutputBuffer(outIndex, true);
//decoder.releaseOutputBuffer(outIndex, false);
break;
}
// All decoded frames have been rendered, we can stop playing now
if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
Log.d("DecodeActivity", "OutputBuffer BUFFER_FLAG_END_OF_STREAM");
break;
}
}
decoder.stop();
decoder.release();
extractor.release();
}
}
}
}
}
JNI Side:
JNIEXPORT jint JNICALL
Java_com_alldigital_videoplayer_VideoBrowser_AVREADVIDEO(JNIEnv * pEnv,
jobject pObj, jbyteArray array) {
AV_ctxt * avctxt = & aud_vid_ctxt;
jbyte * buf = ( * pEnv) - > GetByteArrayElements(pEnv, array, NULL);
if (buf == NULL) {
LOGERR(10, "AVVIDEOREAD", "Bytes null");
}
AVPacket * packet;
packet = av_malloc(sizeof(AVPacket));
av_init_packet(packet);
int avread_res = av_read_frame(avctxt - > gFormatCtx, packet);
int size = packet - > size;
if (avread_res >= 0) {
if (packet - > stream_index == avctxt - > gVideoStreamIndex) {
// packet->size,packet->
if (NULL == memcpy(buf,(char * ) packet - > data, packet - > size))
LOGERR(10, "AV_AUDIO_DECODE", "memcpy for audio buffer failed");
}
}
( * pEnv) - > ReleaseByteArrayElements(pEnv, array, buf, 0);
av_free_packet(packet);
packet = NULL;
return size;
}
}
Even though I am copying the encoded data of each frame through FFmpeg without calling extractor, I am getting this outputbuffer timeout issue - why?
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(new File(
"ur file path"));
byte[] buf = new byte[1024];
int n;
while (-1 != (n = fis.read(buf))) {
baos.write(buf, 0, n);
}
byte[] videoBytes = baos.toByteArray();
// use this videoBytes which is low level of original video
} catch (Exception e) {
e.printStackTrace();
}
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);
}
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