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.
Related
Screenshot of program running (top left: server, the rest are clients):
In the bottom-right window, I am trying to press Control D (mac) (for windows it's control Z) in order to exit the bottom right window/client alone without exiting the entire application/program but it doesn't seem to be working because I can still type "it didn't work" and it outputs the message.
My question is: What changes can I make to the following code so that when a client presses Control D it will close just one window/client and not exit the whole application?
Part of code that should close the window (currently empty):
//This is the code that prints messages to all clients
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (!line.equals(null) && !line.equals("null") && !line.equals(null) && !line.equals("F") && !line.equals("m") && !line.equals("M") && threads[i] != null && threads[i].clientName != null && !threads[i].clientName.equals("m") && !threads[i].clientName.equals("M"))
{
if(!line.equals("") == true && line.isEmpty()== false)
{
threads[i].os.println(name + ": " + line);
}
}
//After Control D/Z is pressed, this code will execute
else if(line.equals(null) || line.equals("null") || line.contains("null"))
{
try
{
//This code location exits the program, system.exit(0) and system.exit(-1) didn't work
//how do i close only one client window here without exiting the whole program?
}
catch (NullPointerException ignored)
{
}
finally
{
}
// threads[i].os.close();
// System.exit(0);
}
}
}
NOTE: SKIP THE REST and scroll down if you already know the answer
Full code of ClientThreads.java:
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.nio.*;
import java.nio.channels.FileChannel;
class ClientThreads extends Thread
{
public String path = "";
public String name1 = "";
private String clientName = null;
private DataInputStream is = null;
private PrintStream os = null;
private Socket clientSocket = null;
private final ClientThreads[] threads;
private int maxClientsCount;
public int position = 0;
public static List<String> listName = Collections.synchronizedList(new ArrayList<String>());
List<String> l = Collections.synchronizedList(new ArrayList<String>());
public String[] namesList = new String[10];
public ClientThreads(Socket clientSocket, ClientThreads[] threads,
String name, String[] namesList, List<String> listName)
{
this.clientSocket = clientSocket;
this.threads = threads;
maxClientsCount = threads.length;
this.name1 = name;
this.namesList = namesList;
}
#SuppressWarnings("deprecation")
public void run()
{
int maxClientsCount = this.maxClientsCount;
ClientThreads[] threads = this.threads;
synchronized (listName)
{
//Iterator i = listName.iterator(); // Must be in synchronized block
ListIterator<String> i = listName.listIterator();
}
try
{
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
String name;
String name3;
while (true)
{
//os.println("What is your name?");
name = is.readLine().trim();
name3 = name;
break;
}
synchronized(listName)
{
if(!listName.contains(name))
{
if(!listName.contains(name) && name != null && !name.isEmpty())
{
listName.add(name);
Path currentRelativePath = Paths.get("");
path = currentRelativePath.toAbsolutePath().toString();
}
}
}
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] != null && threads[i] == this)
{
clientName = "#" + name;
break;
}
}
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] != null)
{
}
}
}
while (true)
{
synchronized(listName)
{
}
String line = is.readLine();
if (line.contains("3582938758912781739713asfaiwef;owjouruuzlxjcjnbbiewruwoerpqKFDJiuxo9"))
{
break;
}
else
{
}
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (!line.equals(null) && !line.equals("null") && !line.equals(null) && !line.equals("F") && !line.equals("m") && !line.equals("M") && threads[i] != null && threads[i].clientName != null && !threads[i].clientName.equals("m") && !threads[i].clientName.equals("M"))
{
if(!line.equals("") == true && line.isEmpty()== false)
{
threads[i].os.println(name + ": " + line);
}
}
else if(line.equals(null) || line.equals("null") || line.contains("null"))
{
try
{
//This code location exits the program, system.exit(0) and system.exit(-1) didn't work
//how do i close only one client window here without exiting the whole program?
}
catch (NullPointerException ignored)
{
}
finally
{
}
// threads[i].os.close();
// System.exit(0);
}
}
}
// }
}
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] != null && threads[i] != this && threads[i].clientName != null)
{
// threads[i].os.println(name + "has disconnected.");
threads[i].listName.remove(name);
listName.remove(name);
// threads[i].os.println("The list now contains: " + listName);
// System.out.println("A user disconnected. The list now contains: " +listName);
}
}
}
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] == this)
{
//threads[i] = null;
}
}
}
// is.close();
// os.close();
//clientSocket.close();
}
catch (IOException e)
{
}
}
}
Full code of ChatClient.java:
import java.io.*;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ChatClient implements Runnable
{
public static String path = "";
private static Socket clientSocket = null;
private static PrintStream os = null;
private static DataInputStream is = null;
private static BufferedReader inputLine = null;
private static boolean closed = false;
public static String[] namesList = new String[10];
public int iteration = 0;
public static String[] responses = new String[50];
public int responseCount = 0;
public static final int maxClientsCount = 10;
public static final ClientThreads[] threads = new ClientThreads[maxClientsCount];
public static List<String> listName = Collections.synchronizedList(new ArrayList<String>());
List<String> l = Collections.synchronizedList(new ArrayList<String>());
public ChatClient()
{
}
public static void main(String[] args)
{
for(int i = 0; i < namesList.length; i++)
{
namesList[i] = "";
}
for(int j = 0; j < responses.length; j++)
{
responses[j] = "";
}
// System.out.println("args[0] is: " + args[0]);
int portNumber = Integer.valueOf(args[0]);
String host = "localhost";
//int filePort = Integer.valueOf(args[0]);
try
{
synchronized(listName)
{
clientSocket = new Socket(host, portNumber);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
}
}
catch (UnknownHostException e)
{
//System.err.println("Don't know about host " + host);
} catch (IOException e)
{
// System.err.println("Couldn't get I/O for the connection to the host "
// + host);
}
if (clientSocket != null && os != null && is != null)
{
try
{
new Thread(new ChatClient()).start();
while (!closed)
{
os.println(inputLine.readLine() );
}
// os.close();
//is.close();
//clientSocket.close();
}
catch (IOException e)
{
// System.err.println("IOException: " + e);
}
}
}
#SuppressWarnings("deprecation")
public void run()
{
String responseLine = "";
try
{
while ((responseLine = is.readLine()) != null)
{
if(responseLine!=null && !responseLine.equals(null) && responseLine!="null" && !responseLine.equals("null") && !responseLine.contains("null"))
{
System.out.println(responseLine);
}
else if(responseLine.contains("null") || responseLine.equals("null") || responseLine==null || responseLine.equals(null))
{
//This is another location which will be executed if Control D/Control Z is pressed
//os.close();
// is.close();
//System.exit(0);
}
}
//closed = true;
}
catch (IOException e)
{
// System.err.println("IOException: " + e);
}
}
}
Full code of ChatServer.java:
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer
{
public static List<String> listName = Collections.synchronizedList(new ArrayList<String>());
List<String> l = Collections.synchronizedList(new ArrayList<String>());
public static ServerSocket serverSocket = null;
public static Socket clientSocket = null;
public static final int maxClientsCount = 10;
public static final ClientThreads[] threads = new ClientThreads[maxClientsCount];
public static String[] namesList = new String[10];
// public ChatClient arrayOfNames = new ChatClient;
public static void main(String args[])
{
synchronized (listName)
{
//Iterator i = listName.iterator(); // Must be in synchronized block
Iterator<String> i = listName.listIterator();
}
int once = 0;
if(once == 0)
{
// System.out.println("args[0] is: " + args[0]);
int portNumber = Integer.valueOf(args[0]);
// System.out.println("waiting for connections on port " + portNumber + " ...\n ");
once = 3;
}
once = 3;
try
{
int portNumber1 = Integer.valueOf(args[0]);
serverSocket = new ServerSocket(portNumber1);
}
catch (IOException e)
{
System.out.println(e);
}
while (true)
{
try
{
clientSocket = serverSocket.accept();
int i = 0;
for (i = 0; i < maxClientsCount; i++)
{
if (threads[i] == null)
{
String name = "";
(threads[i] = new ClientThreads(clientSocket, threads, name, namesList, listName)).start();
break;
}
}
if (i == maxClientsCount)
{
//PrintStream os = new PrintStream(clientSocket.getOutputStream());
// os.println("Server too busy. Try later.");
// os.close();
// clientSocket.close();
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}
}
EDIT: it might also be possible to change threads[i] to threads[i+1] in order to keep track of different clients in certain parts of the code
What you need instead of this:
while (!closed)
{
os.println(inputLine.readLine() );
}
is this:
String line;
while ((line = inputLine.readLine()) != null)
{
os.println(line);
}
This will fall-through when ctrl/d or ctrl/z is pressed, as appropriate, and main() will then exit. Provided you have also made your threads daemons, the JVM will then exit.
NB this:
// After Control D/Z is pressed, this code will execute
isn't true, and this:
else if(line.equals(null) || line.equals("null") || line.contains("null"))
is drivel. line.equals(null) can never be true, by definition, otherwise a NullPointerException would have been thrown instead of calling .equals(): and why you should be interested in whether the user has typed "null", or something containing "null", is a mystery.
And why you are using synchronized(listName) in the main() method of an application which up to this point is single-threaded is another mystery.
Screenshot of program running (top is server, bottom right is first client, bottom left is second client):
Screenshot of program running
The problem with the screenshot above is that the message that appears on the bottom left window User name: something has been added to position 0 in the namesList array should instead be User name: something has been added to position 1 in the namesList array The reason the position needs to be 1 instead of 0 is because the first name should be stored in the first position, and the second name should be stored in the second position (to make the list of names actually store all of the names)
The issue is making the namesList array and position sync.
EDIT: it seems that threads[i] has global accessibility, is it possible that I should make an arraylist of file names with objects to somehow store the names of the connected clients instead of a regular string array to store them?
What changes can I make to the following code that would make the array sync and accessible to all clients?
ChatThreads.java code:
import java.io.*;
import java.net.*;
import java.util.*;
class ClientThreads extends Thread
{
public String name1 = "";
private String clientName = null;
private DataInputStream is = null;
private PrintStream os = null;
private Socket clientSocket = null;
private final ClientThreads[] threads;
private int maxClientsCount;
public static String[] namesList = new String[4];
public int iteration = 0;
public static String[] responses = new String[50];
public int responseCount = 0;
public ClientThreads(Socket clientSocket, ClientThreads[] threads, String name)
{
this.clientSocket = clientSocket;
this.threads = threads;
maxClientsCount = threads.length;
this.name1 = name;
}
#SuppressWarnings("deprecation")
public void run()
{
int maxClientsCount = this.maxClientsCount;
ClientThreads[] threads = this.threads;
for(int i = 0; i < namesList.length; i++)
{
namesList[i] = "";
}
for(int j = 0; j < responses.length; j++)
{
responses[j] = "";
}
try
{
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
String name;
String firstName;
while (true)
{
os.println("What is your name?");
name = is.readLine().trim();
break;
}
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] != null && threads[i] == this)
{
clientName = "#" + name;
break;
}
}
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] != null)
{
threads[i].os.println(name + " has connected.");
os.println("Enter an option: 'm' = message, 'f' = file request, 'x' = exit\n");
}
}
}
while (true)
{
String line = is.readLine();
if (line.startsWith("/quit"))
{
break;
}
else
{
//os.println("Enter an option: 'm' = message, 'f' = file request, 'x' = exit\n");
}
if(line.equals("x") || line.equals("X"))
{
os.println("x");
System.exit(0);
}
if(line.equals("m") || line.equals("M"))
{
os.println("Enter your message: ");
}
if(line.equals("f") || line.equals("F"))
{
os.println("Who owns the file?");
boolean keep = true;
while (keep == true)
{
String fileOwner = is.readLine();
if(fileOwner !=null && !fileOwner.isEmpty())
{
responses[responseCount] = fileOwner + "`owns a file";
responseCount++;
os.println(fileOwner);
namesList[iteration] = fileOwner;
System.out.println("User named: " + fileOwner + " has been added to position " + iteration + " in the namesList array.");
iteration++;
keep = false;
os.println("Which file do you want?");
boolean keep2 = true;
while(keep2==true)
{
String filename = is.readLine();
if(filename !=null && !filename.isEmpty())
{
// os.println(filename);
keep2 = false;
os.println("Enter an option: 'm' = message, 'f' = file request, 'x' = exit\n");
}
}
}
}
}
else
{
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (!line.equals("x") && !line.equals("X") && !line.equals("f") && !line.equals("F") && !line.equals("m") && !line.equals("M") && threads[i] != null && threads[i].clientName != null && !threads[i].clientName.equals("m") && !threads[i].clientName.equals("M"))
{
threads[i].os.println(name + ": " + line + "\n");
this.os.println("Enter an option: 'm' = message, 'f' = file request, 'x' = exit\n");
}
}
}
}
}
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] != null && threads[i] != this && threads[i].clientName != null)
{
threads[i].os.println(name + "has disconnected.");
}
}
}
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] == this)
{
threads[i] = null;
}
}
}
is.close();
os.close();
clientSocket.close();
}
catch (IOException e)
{
}
}
}
ChatClient.java code:
import java.io.*;
import java.net.*;
public class ChatClient implements Runnable
{
private static Socket clientSocket = null;
private static PrintStream os = null;
private static DataInputStream is = null;
private static BufferedReader inputLine = null;
private static boolean closed = false;
public static String[] namesList = new String[4];
public int iteration = 0;
public static String[] responses = new String[50];
public int responseCount = 0;
public static void main(String[] args)
{
for(int i = 0; i < namesList.length; i++)
{
namesList[i] = "";
}
for(int j = 0; j < responses.length; j++)
{
responses[j] = "";
}
int portNumber = Integer.valueOf(args[3]);
String host = "localhost";
int filePort = Integer.valueOf(args[1]);
try
{
clientSocket = new Socket(host, portNumber);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
}
catch (UnknownHostException e)
{
System.err.println("Don't know about host " + host);
} catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to the host "
+ host);
}
if (clientSocket != null && os != null && is != null)
{
try
{
new Thread(new ChatClient()).start();
while (!closed)
{
os.println(inputLine.readLine() );
}
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
#SuppressWarnings("deprecation")
public void run()
{
String responseLine = "";
try
{
while ((responseLine = is.readLine()) != null)
{
if(responseLine.equals("x") || responseLine.equals("X"))
{
System.exit(0);
}
if(responseLine.equals("Who owns the file?") && !responseLine.isEmpty() && responseLine != null)
{
responseCount++;
System.out.println(responseLine);
responses[responseCount] = "234782375920192831";
}
if(responseLine.equals("Which file do you want?"))
{
responseCount++;
System.out.println(responseLine);
responses[responseCount] = responseLine;
}
if(responseLine.equals("What is your name?"))
{
responseCount++;
System.out.println(responseLine);
responses[responseCount] = responseLine;
}
if(responseLine.equals("m") || responseLine.equals("M"))
{
responseCount++;
System.out.println("Enter your message: ");
responses[responseCount] = responseLine;
}
if(responseLine.equals("Enter an option: 'm' = message, 'f' = file request, 'x' = exit\n"))
{
responseCount++;
System.out.println(responseLine);
responses[responseCount] = responseLine;
}
if(responseLine != null && !responseLine.isEmpty() && !responseLine.equals("What is your name?") && !responseLine.equals("Enter an option: 'm' = message, 'f' = file request, 'x' = exit\n") && !responseLine.equals("Who owns the file?") && !responseLine.equals("Which file do you want?"))
{
responseCount++;
if(responses[responseCount-1].equals("234782375920192831"))
{
namesList[iteration] = responseLine;
System.out.println("User named: " + responseLine + " has been added to position " + iteration + " in the namesList array." );
iteration++;
}
else
{
System.out.println(responseLine);
responses[responseCount] = responseLine;
}
}
}
closed = true;
}
catch (IOException e)
{
System.err.println("IOException: " + e);
}
}
}
ChatServer.java code
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer
{
public static ServerSocket serverSocket = null;
public static Socket clientSocket = null;
public static final int maxClientsCount = 10;
public static final ClientThreads[] threads = new ClientThreads[maxClientsCount];
public static void main(String args[])
{
if(args.length <3)
{
int portNumber = Integer.valueOf(args[1]).intValue();
System.out.println("waiting for connections on port " + portNumber + " ...\n ");
}
try
{
int portNumber1 = Integer.valueOf(args[1]).intValue();
serverSocket = new ServerSocket(portNumber1);
}
catch (IOException e)
{
System.out.println(e);
}
while (true)
{
try
{
clientSocket = serverSocket.accept();
int i = 0;
for (i = 0; i < maxClientsCount; i++)
{
if (threads[i] == null)
{
String name = "";
(threads[i] = new ClientThreads(clientSocket, threads, name)).start();
break;
}
}
if (i == maxClientsCount)
{
PrintStream os = new PrintStream(clientSocket.getOutputStream());
os.println("Server too busy. Try later.");
os.close();
clientSocket.close();
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}
}
ServerThread.java code:
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;
public class ServerThread
{
private static ServerSocket serverSocket = null;
private static Socket clientSocket = null;
private static final int maxClientsCount = 10;
private static final ClientThreads[] threads = new ClientThreads[maxClientsCount];
public static void main(String args[])
{
int portNumber = Integer.valueOf(args[1]).intValue();
if(args.length <3)
{
System.out.println("waiting for conennections on port" + portNumber + " ...\n ");
}
try
{
serverSocket = new ServerSocket(portNumber);
}
catch (IOException e)
{
System.out.println(e);
}
while (true)
{
try
{
clientSocket = serverSocket.accept();
int i = 0;
for (i = 0; i < maxClientsCount; i++)
{
if (threads[i] == null)
{
String name = "";
(threads[i] = new ClientThreads(clientSocket, threads, name)).start();
break;
}
}
if (i == maxClientsCount)
{
PrintStream os = new PrintStream(clientSocket.getOutputStream());
os.println("Server too busy. Try later.");
os.close();
clientSocket.close();
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}
}
My question is: How would I make the namesList array the same across multiple clients with the position?
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());
}
});
}
}
}