ReadObject returns OptionalDataException - java

We are trying to send an object from an android Bluetooth client to a desktop Bluetooth server. We are trying to do this through the ObjectInputStream and ObjectOutput Stream. We are also very new to Bluetooth development, and have tried looking online for different examples and solutions.
Here is our code,
Android Code:
private static 1.5.0/docs/api/java/util/UUID.html">UUID generalUuid = 1.5.0/docs/api/java/util/UUID.html">UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static BluetoothSocket socket;
private static BluetoothSocket getBluetoothSocket(){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.cancelDiscovery();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
if(device.getName().equalsIgnoreCase(("mint-0"))){
try {
return device.createRfcommSocketToServiceRecord(generalUuid);
} catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
return null;
}
}
}
}
return null;
}
public static boolean sendData(1.5.0/docs/api/java/lang/String.html">String first, 1.5.0/docs/api/java/lang/String.html">String last, int age){
socket = getBluetoothSocket();
try {
socket.connect();
} catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
// TODO Auto-generated catch block
socket = null;
}
if(socket != null){
try {
1.5.0/docs/api/java/io/ObjectOutputStream.html">ObjectOutputStream oos = new 1.5.0/docs/api/java/io/ObjectOutputStream.html">ObjectOutputStream(socket.getOutputStream());
oos.writeChars("X");
//send serializable object
personTest person = new personTest(first, last, age);
oos.writeObject(person);
oos.flush();
oos.close();
socket.close();
return true;
} catch (1.5.0/docs/api/java/io/IOException.html">IOException e) {
socket = null;
return false;
}
}else{
return false;
}
}
PC Code:
public class DataServer {
static final String serverUUID = "11111111111111111111111111111123";
public static void main(String[] args) throws IOException {
LocalDevice localDevice = LocalDevice.getLocalDevice();
localDevice.setDiscoverable(DiscoveryAgent.GIAC); // Advertising the service
System.out.println("Setting Discoverable");
String url = "btspp://localhost:" + serverUUID + ";name=BlueToothServer";
StreamConnectionNotifier server = (StreamConnectionNotifier) Connector.open(url);
System.out.println("Server: " + url);
StreamConnection connection = server.acceptAndOpen(); // Wait until client connects
System.out.println("Client Connected");
//=== At this point, two devices should be connected ===//
ObjectInputStream ois = new ObjectInputStream(connection.openInputStream());
personTest obj = null;
System.out.println("Waiting for Object");
//while(true){
try{
obj = (personTest) ois.readObject();
if(obj.getName() != "Gregg Miller"){
System.err.println("Name " + obj.getName() + " incorrect");
}
} catch(ClassNotFoundException cnfe){
System.err.println("cnfe "+cnfe.getMessage());
}
catch(InvalidClassException ice){
System.err.println("ice "+ice.getMessage());
}
catch(StreamCorruptedException sce){
System.err.println("sce "+sce.getMessage());
}
catch(IOException ioe){
System.err.println("ioe "+ioe.getMessage());
System.err.println(ioe.toString());
System.err.println("ODE Length: " +((OptionalDataException)ioe).length);
System.err.println("ODE EOF: " +((OptionalDataException)ioe).eof);
}
//}
System.out.println("Recieved, closing connection");
connection.close();
}
}
The output of the program after running both the android app and the desktop program are as followed:
ioe null
java.io.OptionalDataException
ODE Length: 2
ODE EOF: false
As requested, here is the PersonTest code:
package edit.rit.ce.whud;
import java.io.Serializable;
public class personTest extends Object implements Serializable {
private String firstName;
private String lastName;
private int age;
public personTest(String first, String last, int age){
this.firstName = first;
this.lastName = last;
this.age = age;
}
public String getName(){
return firstName +" "+ lastName;
}
public int getAge(){
return age;
}
}

Remove this:
oos.writeChars("X");
You're confusing the readObject() method at the other end. Or else read those chars at the other end.

Related

Socket Server via Singleton with parameters from properties file

I am going to run Socket Server via Singleton Pattern because I have multiple threads, and every time I call it, I want to use the same socket server. This is SocketSingleton.java class :
public class SocketSingleton {
private static ServerSocket serverSocket = null;
private SocketSingleton() {}
public static synchronized ServerSocket getServerSocket() throws IOException {
PropertiesKey prop = new PropertiesKey();
if (serverSocket == null) {
serverSocket = new ServerSocket(prop.getSocketPort());
}
return serverSocket;
}
}
But I've noticed that I should get my few values from configuration.properties like SOCKET_PORT=2203
I can get the values from configuration with the code bellow
public class PropertiesAlgorithmImpl implements PropertiesAlgorithm {
private static Properties defaultProps = new Properties();
static {
try {
String propertiesDirectory = "src/main/resources/configuration.properties";
FileInputStream in = new FileInputStream(propertiesDirectory);
if (in == null) {
System.out.println("Sorry, unable to find " + propertiesDirectory);
}
defaultProps.load(in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getValuesFromProperties(String key) {
if (defaultProps.getProperty(key) != null) {
return defaultProps.getProperty(key);
}
return "Sorry, unable to find " + key ;
}
}
This is an enum of Socket Port.
public enum CONFIG { SOCKET_PORT}
public class PropertiesKey {
private PropertiesAlgorithm propertiesAlgorithm;
public int getSocketPort(){
propertiesAlgorithm = new PropertiesAlgorithmImpl();
return Integer.parseInt(propertiesAlgorithm.getValuesFromProperties(CONFIG.SOCKET_PORT.name()));
}
In the SocketSingleton class, I am calling socket port like this:
serverSocket = new ServerSocket(prop.getSocketPort());
What is the possible reason that I can't get the socket port parameters from configuration.properties?
I fixed the class bellow with input stream and it worked:
public class PropertiesAlgorithmImpl implements PropertiesAlgorithm {
private static final Logger logger = LoggerFactory.getLogger(PropertiesAlgorithmImpl.class);
private static Properties defaultProps = new Properties();
static {
String propertiesDirectory = "config.properties";
try (InputStream input = PropertiesAlgorithmImpl.class.getClassLoader().getResourceAsStream(propertiesDirectory)) {
if (input == null) {
logger.info("Sorry, unable to find " + propertiesDirectory);
}
defaultProps.load(input);
input.close();
} catch (Exception e) { logger.info(String.valueOf(e.getStackTrace())); }
}
public String getValuesFromProperties(String key) {
if (defaultProps.getProperty(key) != null) {
return defaultProps.getProperty(key);
}
logger.info("Sorry, unable to find " + key);
return "Sorry, unable to find " + key ;
}

FileZilla won't react on commands from my java FTP server

I write my own Java FTP server. Until recently I used PUttY to debug my control telnet connection and everything seemed fine - I had successful two-way communication. Now I try to debug my server with FileZilla, but it does not seem to read my text, nor to send some to server, so it just hangs and wait for something.
Control connection class
public class ControlConnection extends Thread {
private enum OperationMode {
ACTIVE, PASSIVE
}
private final Map<String, Supplier<String>> COMMANDS;
private String[] userTokens;
private User user;
private String userLogin;
private boolean authenticated;
private boolean dataConnected;
private boolean userExists;
private final Socket socket;
private DataInputStream inputStream;
private DataOutputStream outputStream;
private DataConnection ftpSession;
private OperationMode operationMode;
private String errorMessage;
public ControlConnection(Socket socket) {
super(ControlConnection.class.toString());
this.socket = socket;
// constants initialization
authenticated = false;
dataConnected = false;
// commands initialization
COMMANDS = new HashMap<>();
// commands init
}
#Override
public void run() {
try {
inputStream = new DataInputStream(socket.getInputStream());
outputStream = new DataOutputStream(socket.getOutputStream());
sendGreetings();
IOProcessing.writeBytes(outputStream, pasvCommand());;
boolean running = true;
while (running) {
sendGreetings();
String input = IOProcessing.readBytes(inputStream);
if (!(input.equals("")))
System.out.println(input);
if (!checkInput(input))
continue;
userTokens = input.split(" ");
String command = userTokens[0].toUpperCase();
String answer = COMMANDS.get(command).get();
outputStream.writeBytes(answer);
}
}
catch (IOException e) {
System.err.println(e);
System.exit(-1);
}
}
private boolean commonCheck() {
// some checks
return true;
}
private String getErrorMessage() {
return errorMessage;
}
public void sendGreetings() {
String greetings = String.format("220 Control connection established: %s", getConnectionInfo());
IOProcessing.writeBytes(outputStream, greetings);
}
public String getConnectionInfo() {
String info = String.format("%s: %d %s",
socket.getInetAddress().toString(), socket.getPort(), user != null ? user.getUsername(): "");
return info;
}
// input/output proccessing functions
public boolean checkInput(String input) {
// checks
return true;
}
// commands functions
private String pasvCommand() {
if (operationMode == OperationMode.PASSIVE) {
errorMessage = "Already in passive mode.%n";
return errorMessage;
}
String answer;
new ListenToSocket().start();
answer = String.format("227 Entering Passive Mode (%s, %d)",
"127.0.0.1", DataConnection.PORT);
operationMode = OperationMode.PASSIVE;
return answer;
}
private class ListenToSocket extends Thread {
public ListenToSocket() {
}
#Override
public void run() {
try {
ServerSocket ftpSocket =
new ServerSocket(DataConnection.PORT);
ftpSession =
DataConnection.getDataConnection(ftpSocket.accept());
if (ftpSession != null) {
ftpSession.start();
dataConnected = true;
String greetings = "Data connection established: " + ftpSession.getConnectionInfo();
IOProcessing.writeBytes(outputStream, greetings);
} else {
dataConnected = false;
}
} catch (IOException e) {
System.out.print(e);
}
}
}
also, server does not get user credentials, entered in FileZilla - input from server is always empty
IOProcessing class
public class IOProcessing {
private static final Charset UTF8_CHARSET;
static {
UTF8_CHARSET = Charset.forName("UTF-8");
}
public static String readBytes(DataInputStream inputStream) {
String result = "";
try {
int len = inputStream.available();
if (len == 0) {
return result;
}
byte[] byteInput = new byte[len];
inputStream.readFully(byteInput, 0, len);
result = new String(byteInput, "UTF-8").trim();
} catch (IOException e) {
System.err.println(e);
}
return result;
}
output FileZlla log
Status: Resolving address of localhost
Status: Connecting to [::1]:21...
Status: Connection established, waiting for welcome message.
You didn't show us the writeBytes. So I can only guess that you are not sending \r\n after the messages sent to the client. Particularly after the welcome message. So FileZilla keeps waiting forever for it, as any FTP client would do.

Having trouble sending one password attempt at a time (Java)

I am trying to do an extra credit assignment for my Java class where we are attempting to hack into a server. The problem I am having right now is only sending one password at a time:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client
{
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private static int passwordLength;
private static String attempt;
private static int counter = 0;
private static String acceptable = "ABCDEFGHIJKLMNOPQRSTUVWXYXZabcdefghijklmnopqrstuvwxyz0123456789";
public Client()
{
try
{
System.out.println("Connecting to server...");
socket = new Socket("localhost", 58999);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (Exception e)
{
System.out.println("Run the server first.");
}
}
public void close()
{
try
{
socket.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
public String sendPassword(String pass)
{
if (!HUSH) System.out.print("Sending: " + pass);
out.println(pass);
String result = null;
try
{
result = in.readLine();
if (!HUSH)
{
if (result.equals("no"))
System.out.println(" (wrong password)");
else if (result.equals("yes"))
System.out.println(" (CORRECT!)");
}
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
return result;
}
public static boolean HUSH = false;
public static void main(String[] args)
{
Client me = new Client();
//BEGIN YOUR WORK
int length;
HUSH = false; //change this to false for testing
System.out.println("Input character length");
Scanner ui = new Scanner(System.in);
length = ui.nextInt();
Client(length);//set the max length of the password
generate();//pull into the first generate method
me.sendPassword("1234");
me.sendPassword(attempt); //the first password i am trying to break
me.sendPassword("letmein");
me.sendPassword("willthiswork");
// END YOUR WORK
me.close();
}
public static void Client(int max)
{
passwordLength = max;
}
public static void generate()
{
generate(""); //enters generate(String password)
}
static void generate(String password)
{
//base case
if(password.length() == passwordLength)//if password is long enough
System.out.println(++counter + " " + password);
else
for(int x = 0; x < acceptable.length(); x++)
generate(attempt = password + acceptable.charAt(x));
}
}
When I run the code (using the server that is supplied), it runs every possible password combination, but returns 9 (passwordLength number of times) instead of sending say..... A (wrong password) B (wrong password) so on and so forth. I know I need to add something onto my for loop to call it back to main, but I'm not sure how to.

ClassNotFoundException on the server when reading from ObjectInputStream

Based on this tutorial and another tutorial that unfortunately I can't get my hands on right now, I've created my Client-Server application but instead of sending string messages, the client asks for data(using Object Input/Output Streams) from the server using a custom class "Message".
First I created, the basic concept of it, using simple Java and tested both the server and the client on my computer, and displayed the data my client received in the console output. Everything worked out great, so I started to make the transition to Android(for the client). Trying to use the AsycTask, as show in the linked tutorial, I've managed so far to establish the connection between the client and the server. But I'm having a problem getting my server to read my "Message" object. Here are my classes:
Server:
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class T_Server extends Thread {
private static int port = 4444;
private ServerSocket srvSock = null;
private Socket clntSock = null;
private boolean running = false;
private ObjectInputStream in;
private ObjectOutputStream out;
private OnMessageReceived msgListener;
private Message msgIn;
private Object objSend;
public static void main(String[] args) {
OnMessageReceived _msgListener=new OnMessageReceived();
T_Server server=new T_Server(_msgListener);
server.start();
}
public T_Server(OnMessageReceived _msgListener) {
this.msgListener = _msgListener;
}
public void send(Object _msg) {
if (out != null) {
try {
out.writeObject(_msg);
out.flush();
} catch (IOException ex) {
Logger.getLogger(T_Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#Override
public void run() {
running = true;
try {
srvSock = new ServerSocket(port);
System.out.println("Server startet. IP : " + InetAddress.getLocalHost() + ", Port : " + srvSock.getLocalPort());
System.out.println("\nWaiting for a client ...");
clntSock = srvSock.accept();
System.out.println("\nClient accepted: " + clntSock);
try {
out = new ObjectOutputStream(clntSock.getOutputStream());
in = new ObjectInputStream(clntSock.getInputStream());
while (running) {
msgIn = (Message) in.readObject();
System.out.println(msgIn.toString());
objSend = msgListener.messageReceived(msgIn);
send(objSend);
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} finally {
clntSock.close();
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
}
}
}
I use the same Message class both on the Server and on the Client
Message Class:
import java.io.Serializable;
public class Message implements Serializable{
private static final long serialVersionUID = 1L;
public String sender, content, type;
public Message(String sender, String type, String content){
this.sender = sender; this.type=type; this.content = content;
}
#Override
public String toString(){
return "{type='"+type+"', sender='"+sender+"', content='"+content+"'}";
}
}
I have also created a class to handle the Messages, on the server side, called OnMessageReceived.
P.S. In this class there are fields and some options that have to do with my backend database.
OnMessageReceived:
import java.sql.SQLException;
import java.util.regex.Pattern;
public class OnMessageReceived {
public Object messageReceived(Message message) throws SQLException {
Message _msg = message;
Database db = new Database();
Object objReturn;
String strResult;
boolean addResult;
final Pattern pattern = Pattern.compile("\\[.*?&");
final String[] result;
if (_msg.type.equals("getUsers")) {
objReturn = db.getUsers();
return objReturn;
} else if (_msg.type.equals("getFriends")) {
objReturn = db.getFriends(_msg.sender);
return objReturn;
} else if (_msg.type.equals("addFriend")) {
String _UserName, _UserNameFriend;
_UserName = _msg.sender;
_UserNameFriend = _msg.content;
addResult = db.addFriend(_UserName, _UserNameFriend);
if (addResult) {
strResult = "Add was successfull";
return strResult;
} else if (!addResult) {
strResult = "Add failed";
return strResult;
}
System.out.println(addResult);
} else if (_msg.type.equals("addUser")) {
String _UserName, _Password, _Phone;
result = pattern.split(_msg.content);
_UserName = _msg.sender;
_Password = result[0];
_Phone = result[1];
addResult = db.addUser(_UserName, _Password, _Phone);
if (addResult) {
strResult = "Add was successfull";
return strResult;
} else if (!addResult) {
strResult = "Add failed";
return strResult;
}
System.out.println(addResult);
} else if (_msg.type.equals("Login")) {
boolean isUser;
String _UserName;
_UserName = _msg.sender;
isUser = db.isUser(_UserName);
if (isUser) {
strResult = "Login Successfull";
return strResult;
} else if (!isUser) {
strResult = "Login failed";
return strResult;
}
}
return null;
}
}
For the client side(on the Android) it's very simillar to the one in the linked tutorial.
The difference is that I only have 2 buttons, one to connect to the server and one to send my message, which is an instance of my Message class.
Client:
import java.io.*;
import java.net.*;
import android.util.Log;
public class T_Client {
private static final String TAG = "MyActivity";
private static String serverIP = "192.168.1.11";
private static int port = 4444;
private InetAddress serverAddr = null;
private Socket sock = null;
private boolean running = false;
private ObjectInputStream in;
private ObjectOutputStream out;
private OnMessageReceived msgListener;
Object objIn, objReceived;
public T_Client(OnMessageReceived _msgListener){
this.msgListener=_msgListener;
}
public void send(Message _msg) {
if (out != null) {
try {
out.writeObject(_msg);
out.flush();
Log.i(TAG,"Outgoing : " + _msg.toString());
} catch (IOException ex) {
Log.e(TAG,ex.toString());
}
}
}
public void stopClient(){
running = false;
}
public void run(){
running = true;
try {
//here you must put your computer's IP address.
serverAddr = InetAddress.getByName(serverIP);
Log.i("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
sock = new Socket(serverAddr, port);
try {
//send the message to the server
out =new ObjectOutputStream(sock.getOutputStream());
//receive the message which the server sends back
in =new ObjectInputStream(sock.getInputStream());
Log.i("TCP Client", "C: Connected.");
//in this while the client listens for the messages sent by the server
while (running) {
objIn = in.readObject();
if (objIn != null && msgListener != null) {
//call the method messageReceived from MyActivity class
msgListener.messageReceived(objIn);
}
objIn = null;
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + objIn + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
sock.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
public interface OnMessageReceived {
public void messageReceived(Object objReceived);
}
}
Main Activity:
import java.io.IOException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity {
private static final String TAG = "MyActivity";
private T_Client client;
private Message msgSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void connect(View v) throws IOException {
new connectTask().execute("");
}
public void btnSend(View v) throws IOException {
msgSend=new Message("Setlios", "getUsers", "");
if(client!=null){
client.send(msgSend);
}
}
public class connectTask extends AsyncTask<Object,Object,T_Client> {
#Override
protected T_Client doInBackground(Object... objIn) {
//we create a TCPClient object and
client = new T_Client(new T_Client.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(Object objIn) {
//this method calls the onProgressUpdate
publishProgress(objIn);
}
});
client.run();
return null;
}
#Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
Log.i(TAG,values.getClass().getName().toString());
}
}
}
When I hit the "Send" button I get this error on the server console which points me to the point where I read the object read from the ObjectInputStream and pass it an instance of the Message class but I can't understand what the problem is. I also noticed that it shows this "in.neverhide.connect" which is the package name of the project for my android client
java.lang.ClassNotFoundException: in.neverhide.connect.Message
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:622)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1593)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1514)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1750)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at Objects_WORKING.T_Server.run(T_Server.java:61)
Ok after searching around I found this post and the answer from Akinsola 'mys Tunmise. I've made the Message class into a jar and used it as an external reference in both the client and the server.

How do I get my map to load in j2me?

My midlet
public void commandAction(Command command, Displayable displayable) {
// write pre-action user code here
if (displayable == form) {
if (command == exitCommand) {
// write pre-action user code here
exitMIDlet();
// write post-action user code here
} else if (command == okCommand) {
try {
// write pre-action user code here
connection = startConnection(5000, myip);
sendMessage("Query,map,$,start,211,Arsenal,!");
String unformattedurl= receiveMessage();
stringItem.setText(stringItem.getText()+" "+unformattedurl);
String url=getURL(unformattedurl,200,200);
Imageloader imageloader=new Imageloader(stringItem,item,url);
Thread thread=new Thread(imageloader);
thread.start();
}
catch(Exception e){
stringItem.setText(stringItem.getText()+" "+e.getMessage());
}
}
}
// write post-action user code here
}
private void sendMessage(String message) throws IOException{
stringItem.setText(stringItem.getText()+2);
DataOutputStream dos = connection.openDataOutputStream();
System.out.println("Sending...."+message);
dos.writeUTF(message);
stringItem.setText(stringItem.getText()+3);
}
public SocketConnection startConnection(int port,String ip) throws IOException{
return (SocketConnection) Connector.open("socket://"+ip+":"+port);
}
public static String[] split(String str,String delim) throws Exception{
String copy=str;
int len=0;
int index = copy.indexOf(delim)+1;
if (index==0){
throw new Exception("Data format not supported");
}
else{
int prev_index=0;
Vector array=new Vector();
//System.out.println(index);
array.addElement(copy.substring(0,index-1));
while (index !=0){
len++;
copy=copy.substring(index);
index = copy.indexOf(delim)+1;
//System.out.println(copy+" "+index);
if (copy.indexOf(delim)==-1){
array.addElement(copy);
}
else{
//System.out.println(0+" "+copy.indexOf(delim));
array.addElement(copy.substring(0,copy.indexOf(delim)));
}
}
String[] array2=new String [array.size()];
for (int i=0;i<array.size();i++){
array2[i]=(String)array.elementAt(i);
//System.out.println(array2[i]);
}
return array2;
}
}
private String receiveMessage() throws IOException{
stringItem.setText(stringItem.getText()+5);
DataInputStream dis = connection.openDataInputStream();
stringItem.setText(stringItem.getText()+6);
return dis.readUTF();
}
private String getURL(String message,int width,int height) throws Exception{
item.setLabel(item.getLabel()+6);
System.out.println("TEst1");
//System.out.println("Formatted message is "+query);
//System.out.println("Getting height......"+label.getMaximumSize().height);
String[] messagearr=split(message,",");
System.out.println("TEst2");
String color,object;
String url="http://maps.google.com/maps/api/staticmap?center=Mauritius&zoom=10&size="+width+"x"+height+"&maptype=roadmap";
//&markers=color:green|label:Bus21|40.702147,-74.015794&markers=color:blue|label:User|40.711614,-74.012318&sensor=false";
String lat,longitude;
System.out.println("TEst3");
if (messagearr[0].equals("query")){
System.out.println("TEst4");
if (messagearr[1].equals("Error")){
String error=messagearr[2];
System.out.println("TEst5"+error);
item.setAltText(error);
item.setLabel("Test"+error);
}
else {
System.out.println("Wrong number");
int startindex=5;
String distance,time;
distance=messagearr[2];
time=messagearr[3];
String name=messagearr[4];
imageLabel="The bus is at :"+time+"min and "+distance +"km from user";
for (int i=startindex;i<messagearr.length;i+=2){
System.out.println("TEst8");
lat=messagearr[i];
longitude=messagearr[i+1];
if (i==startindex){
object="U";
color="Blue";
}
else{
object="B";
color="Green";
}
url=url+"&markers=color:"+color+"|label:"+object+"|"+lat+","+longitude;
item.setLabel(7+url);
System.out.println("TEst10"+" name "+name+" long "+longitude+" lat "+lat+" url "+url );
}
url+="&sensor=false";
System.out.println("Image loaded .... "+url);
return url;
}
}
item.setLabel(item.getLabel()+8);
throw new Exception("Url is wrong");
}
}
public class Imageloader implements Runnable{
StringItem stringitem=null;
ImageItem imageitem=null;
String url=null;
Imageloader(StringItem stringitem,ImageItem imageitem,String url){
this.stringitem=stringitem;
this.imageitem=imageitem;
this.url=url;
stringitem.setText(stringitem.getText()+1);
}
private void loadImage() throws IOException{
stringitem.setText(stringitem.getText()+2);
imageitem.setImage(getImage(url));
}
public Image getImage(String url) throws IOException {
stringitem.setText(stringitem.getText()+3);
HttpConnection hpc = null;
DataInputStream dis = null;
try {
hpc = (HttpConnection) Connector.open(url);
System.out.println(hpc.getResponseMessage());
//hpc.getResponseMessage()
stringitem.setText(stringitem.getText()+" ... "+hpc.getResponseMessage());
int length = (int) hpc.getLength();
System.out.println("Length is "+length);
stringitem.setText(stringitem.getText()+" ... "+length);
byte[] data = new byte[length];
dis = new DataInputStream(hpc.openInputStream());
dis.readFully(data);
return Image.createImage(data, 0, data.length);
} finally {
if (hpc != null)
hpc.close();
if (dis != null)
dis.close();
}
}
public void run() {
try {
stringitem.setText(stringitem.getText()+5);
loadImage();
} catch (IOException ex) {
imageitem.setLabel(ex.getMessage()+5);
ex.printStackTrace();
}
}
}
I am unable to load an image in my mobile phone howerver it works fine using an emulator.
The exception says "Error in HTTP connection"..
and it occurs in the loadImage() method ..
How do I sort this out?
make sure your application has access to make http connection and you have got working connection with your phone

Categories

Resources