I'm currently using the library JSON-io. I created a desktop application which when a person want to log in in the system send an JSONObject with his username and password. Then the server send back the response if the person is allowed or not (also a JSONObject). Until here everything works fine.
Now i want to make an Android app. I take the same code than before for login but the application crashes.
The code for login is launch from an AsyncTask and i put the permission to access to Internet to the Manifest.
I perform some testing and it occurs that the method write of JSONWriter "delete" my JSON because on the server side he receives this : {}. I tried to hardcode the JSONObject on the server side (the server's code works fine because we can use the desktop app) but this time the readObject on the android App receives also {}.
We tried to send jsonObject.toString() and this time it worked (except that the server isn't configured to handle a string).
Do anyone knows why on android the two methods write and readObject are deleting the JSON ?
Thank you.
EDIT:
Here the code i wrote:
On the android App
protected Boolean doInBackground(Void... params) {
// 3 : create a JSON object and send it to server for verification
JSONObject loginJS = new JSONObject();
try {
loginJS.put("type", Type.LOGIN); // Type is an enum
loginJS.put("username", userName);
loginJS.put("hash", mPassword);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
User user = new User();
System.out
.println("User created and ready to connect to the spu for login");
user.connexionToSPU(); // This method works
System.out.println("LoginJS = "+loginJS.toString()); At this point the print of the JSON is fine we have {"type":"Login", ....}
user.sendToSPU(loginJS); //This is where there's a problem
// 4 : wait response
JSONObject loginResponseJS = user.receiveFromSPU(); // And when i hard code the JSON on the server side receiveFromSPU get a empty JSON
Method connexionToSPU:
public void connexionToSPU() {
jswSPU = null;
jsrSPU = null;
Socket socket = null;
try {
socket = new Socket(prop.readPropertiesXML("IP_adress_server"),
Integer.parseInt(prop.readPropertiesXML("port_server")));
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
jswSPU = new JsonWriter(socket.getOutputStream());
jsrSPU = new JsonReader(new BufferedInputStream(socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sendToSPU method
public void sendToSPU(JSONObject json) {
try {
jswSPU.write(json);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ReceiveFromSPU method
public JSONObject receiveFromSPU() {
JSONObject json = null;
try {
json = (JSONObject) jsrSPU.readObject();
System.out.println("JSON FROM THE SERVER : "+json.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
Hope it will be sufficiently clear.
Thank you
Related
Hello Im writing an app in which client sends name of room to server, server creates it and then sends back whole list of rooms. I have problem with receiving this object from server also whats interesting when I close clients' app and open again I have list of rooms just like it should be. I refresh room list in client app but its always empty only reopening helps that's pretty weird and I don't know an issue of this.
On client side:
getIs() method is returning is object
getOs() method returning os object
this.os = new ObjectOutputStream(clientSocket.getOutputStream());
this.is = new ObjectInputStream(clientSocket.getInputStream());
private void createRoom(ActionEvent event) {
String roomName = "CreateRoom ";
roomName += setRoomName();
String response = null;
try {
client.getOs().writeObject(roomName);
response = (String) client.getIs().readObject();
System.out.println(response);
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void refreshRooms() {
String response = null;
try {
client.getOs().writeObject("RefreshRooms");
response = (String) client.getIs().readObject();
System.out.println(response);
rooms = (Rooms) client.getIs().readObject();
System.out.println("Print in client: ");
rooms.printAllRooms();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Server:
this.os = new ObjectOutputStream(connection.getOutputStream());
this.is = new ObjectInputStream(connection.getInputStream());
public void run() {
String inputRequest = null;
try {
while((inputRequest = (String) ois.readObject()) != null) {
System.out.println(inputRequest);
handleRequest(inputRequest);
}
} catch (IOException | ClassNotFoundException e) {
System.out.println("Client has disconnected.");
e.printStackTrace();
}
}
private void handleRequest(String request) {
String response = null;
String[] msg = request.split(" ");
if(msg[0].equals("CreateRoom")) {
try {
oos.writeObject("You want create a room.");
Room newRoom = new Room(msg[1]);
rooms.addRoom(newRoom);
System.out.println("Created room: " + newRoom.getName());
System.out.println("\n Print after creation: ");
rooms.printAllRooms();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if (msg[0].equals("RefreshRooms")) {
try {
oos.writeObject("You want list of rooms.");
System.out.println("Print before send.");
rooms.printAllRooms();
oos.writeObject(rooms);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
///EDIT:
So I removed PrintWriter and BufferedReader objects and now Im using only Object Streams. What doesn't work now is:
I create some rooms one after another and then refresh rooms list on clients app - in that case I get all rooms
But when I create one room refresh then create another and refresh I get only 1 room after 2nd refresh, so basically when I refresh server sends me always the same object from 1st send and I don't know how to change it.
Also Im printing these rooms on server side and always get all rooms so room creation is OK.
You could try to flush the buffered streams:
os.flush()
This will force the stream to actually send the bytes of the serialized object. Without that, the BufferedOutputStream might just wait around and buffer data, as the name says. This is done so that the size of the sent packets does not become too small, which would result in a lot of overhead if you want to send multiple objects.
If you are done, you should close the stream anyway.
I have this spring boot java controller having code that utilizes the OpenKM document management API to search the document management system for documents and display results using Ajax, HTML, CSS and Jquery datatables on the front-end.
Due to the way the API was written, I cannot get a document object with its metadata in one call but will need to use an output of the first API operation's call as a filter for another API operation method in two nested for loops.
Additionally, I had to iterate the toString method of an API return object to retrieve the metadata information, as they were not accessible through the return object's properties.
The problem is the performance of this code. I would like to see if there is a way to optimize this code.
// Read the property or metadata to use in constituting the StoredDocument object
for (QueryResult queryResult : resultSet.getResults()) {
// Create a locally-scoped List<String>
List<String> listOfStoredDocumentProperties = new ArrayList<String>();
Document document = queryResult.getDocument();
String nodeId = document.getPath();
// Populate storedDocument object
storedDocument = new StoredDocument();
storedDocument.setAuthor(document.getAuthor());
storedDocument.setCreated(document.getCreated());
storedDocument.setLastModified(document.getLastModified());
storedDocument.setPath(document.getPath());
storedDocument.setPermissions(document.getPermissions());
storedDocument.setSize(document.getActualVersion().getSize());
storedDocument.setUuid(document.getUuid());
storedDocument.setVersionNumber(document.getActualVersion().getName());
// System.out.println(nodeId);
try {
listOfFormElement = okm.getPropertyGroupProperties(nodeId, documentVo.getGroupId());
int counterForTrackingDocDirectionPos = 0;
for (FormElement formElement : listOfFormElement) {
++counterForTrackingDocDirectionPos;
if (counterForTrackingDocDirectionPos == 4) {
String formElementString = formElement.toString();
// System.out.println("formElementString: " + formElementString);
System.out.println("name: " + formElement.getName());
System.out.println("formElement: " + formElement);
String transformedFormElementString = StringUtils.EMPTY;
try {
transformedFormElementString = formElementString.substring(0, formElementString.indexOf(", selected=true"));
// Read the string from a position that is 3 steps before the last position in the string.
transformedFormElementString = transformedFormElementString
.substring(transformedFormElementString.length() - 3, transformedFormElementString.length()).trim();
transformedFormElementString = transformedFormElementString.startsWith("=")
? transformedFormElementString.substring(1, transformedFormElementString.length()) : transformedFormElementString;
} catch (Exception ex) {
// To catch scenario where formElementString.indexOf(", selected=true") does not find the
// specified string. This happens when document direction is not set and therefore is
// selected=false for both the options IN and OUT.
transformedFormElementString = "NOT SET";
}
listOfStoredDocumentProperties.add(transformedFormElementString);
System.out.println("transformedFormElementString: " + transformedFormElementString);
} else {
String formElementString = formElement.toString();
String transformedFormElementString = formElementString.substring(formElementString.indexOf("value="),
formElementString.indexOf("data="));
// Remove the preceding 'value=' and the last 2 character-constituted string ", "
transformedFormElementString = transformedFormElementString.substring(6, transformedFormElementString.length() - 2).trim();
listOfStoredDocumentProperties.add(transformedFormElementString);
}
}
storedDocument.setCompanyName(listOfStoredDocumentProperties.get(0));
storedDocument.setProductLine(listOfStoredDocumentProperties.get(1));
storedDocument.setSubjectHeading(listOfStoredDocumentProperties.get(2));
storedDocument.setDocumentDirection(listOfStoredDocumentProperties.get(3));
storedDocument.setDocumentType(listOfStoredDocumentProperties.get(4));
storedDocument.setReferenceNumber(listOfStoredDocumentProperties.get(5));
storedDocument.setDate(ISO8601.parseBasic(listOfStoredDocumentProperties.get(6)).getTime().toString());
// Add the storedDocument object to the return list
listOfstoredDocuments.add(storedDocument);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchGroupException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PathNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RepositoryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DatabaseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknowException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WebserviceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The solution for it is extending the REST API. In the professional edition, the REST API is extensible with plugins architecture https://docs.openkm.com/kcenter/view/okm-6.4/creating-your-own-rest-plugin-(-extending-rest-api-).html, in the community this option still is not present. The idea is to build a method from server side what provide the exact data what really you need, creating high-level methods.
I'm have created a java app that reads files from a FTP server.I have tested this app locally(with success) and now i have deployed this app to heroku.
This is a piece a my code :
public void CSVListing() {
String[] fnames = {"1","2","3","4"};
try {
try {
client.connect(host);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
//----------------------------------------
boolean login = false;
try {
login = client.login(user, pass);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
if (login) {
System.out.println("Login success...");
//boolean logout = false;
System.out.println("ready to work");
}
else {
System.out.println("Login fail...");
}
//----------------------------------------
System.out.println(client.printWorkingDirectory());
fnames = client.listNames();
System.out.println("FNAMES ARE" + fnames);
for(String s: fnames){
System.out.println(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
......................................................
I have locally executed this code and it gives me a list of the files, but when I execute this on my heroku app online >>fnames = client.listNames();<< returns null according to my logs. I'm accessing the same FTP host in both executions (locally and online).
Can somebody help me and tell me where i'm wrong?
Did you check your permissions? Awhile ago I pass through something similar, the problem was that the user connecting to the FTP server didn't have permission to download files.
I am new to websocket, and trying out with few examples. The application I created works fine for sometime say 10 - 15 mins, and from then on, it throws the timeout exception when sendText method is called on websocket session. I changed the value for "org.apache.tomcat.websocket.BLOCKING_SEND_TIMEOUT" to -1 and now it hangs.
could you please help me to resolve this issue.
The code I have written to send the data to websocket is as below:
public void update() {
Dashboard dashboardData = tunnelDataService.getDashboardData();
ObjectWriter ow = new ObjectMapper().writer();
String json = null;
try {
json = ow.writeValueAsString(dashboardData);
} catch (JsonGenerationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JsonMappingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
synchronized (lock) {
if (session.isOpen()) {
session.getBasicRemote().sendText(json);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am deploying this application on JBoss EAP 6.3.
I have a following piece of code, basically copy-pasted from examples as I am new to Java and Android (not to programming):
URL vurl = new URL(voteurl); //vuteurl is a string containing a proper URL
HttpURLConnection hc;
hc=null;
hc = (HttpURLConnection)vurl.openConnection();
hc.setRequestMethod("GET");
hc.setDoOutput(true);
hc.setReadTimeout(10000);
hc.connect();
On the line "hc.connect();" the application crashes and Android informs me that it had been stopped.
Adding android.permission.INTERNET to the permisions used by the app did not help.
OK, turns out Android doesn't like network operations in the main thread.
Doing a request in a separate thread does the trick. Thanks guys for Your help!
URL vurl = null;
try {
vurl = new URL(voteurl);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} //vuteurl is a string containing a proper URL
HttpURLConnection hc;
hc=null;
try {
hc = (HttpURLConnection)vurl.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
hc.setRequestMethod("GET");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hc.setDoOutput(true);
hc.setReadTimeout(10000);
try {
hc.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}