How come I can't writeUTF to RMS? - java

I am developing an app using J2ME.
The project is to store integer and string data into RMS.
The error shows that out.writeUTF(i.getNumberPlate()); is not working.
So any solution to solve this problem? The compiler cant even compile the project.
public class CarparkReservationParser {
public static byte[] parseObj(CarparkReservation i) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out;
try {
out = new DataOutputStream(baos);
// write into string
out.writeInt(i.getCarpark());
out.writeUTF(i.getNumberPlate());
out.writeUTF(i.getStudentID());
out.writeUTF(i.getName());
out.writeInt(i.getYear());
out.writeInt(i.getMonth());
// baos.toByteArray();
} catch (IOException e) {
}
// convert to byte array
return baos.toByteArray();
}
}

#jack's comment is right. writeUTF receives a String as parameter. If getNumberPlate() does not return a String you must change your code. For example:
out.writeUTF(i.getNumberPlate().toString());

Related

How to convert a Java string into a ByteString without re-escaping the string

I'm trying to convert an already java encoded string into a ByteString, without re-encoding the string.
My method looks like this:
import com.google.api.HttpBody;
import com.google.protobuf.ByteString;
protected HttpBody getHttpBody(String contentType, String data) {
System.out.println("=======d==:" + data);
HttpBody.Builder bodyBuilder = HttpBody.newBuilder();
bodyBuilder.setContentType(contentType);
try {
bodyBuilder.setData(ByteString.copyFrom(data.getBytes()));
} catch (Exception e) {}
HttpBody body = bodyBuilder.build();
System.out.println("=======d2==:" + body);
return body;
}
The input "data" looks like this:
=======d==:------WebKitFormBoundaryeyaPdl6AduTufZV4\r\nContent-Disposition: form-data; name=\"content\"; filename=\"473892_CRUST_grammars.zip\"\r\nContent-Type: application/x-zip-compressed\r\n\r\nPK\003\004\024\000\000\000\b\000\342:nT\222{\260q;\001\000\000\022\002\000\000\021\000\000\000en-US/CRUST.grxmleQOO\2030\024?\217OQ\353\201\023+h4s\026\226\005\227x\232\211l1\272L\322\2617\326\004ZR\212\250\237\336\256\262\211YO\257\357\375\376\275\226N>\313\002}\200\252\271\024\241\033\f}\027\201\310\344\226\213<ty\362\344\215F7w^\340N\"\207\346\212\225%S\310P\306\0053\000\f\302[&\370\304\307\206\217\221\222R\2078~^&\v|\300\212:\304{\255\2531!m\333\016\333\353\241T9\271\362\375\200\370\267\244\023\305\221\203\272CK\320\f\tVB\210\353\226+\310R!U\311\n\376\r\251\226i\245\344\206mx\3015\207\032\243L\n\r\3028\006\230D\2163\240\252)\000\361\355)B\235\311\312HU\315\246\340\231\361\031\f\250\024\340\311\335\237%2=\256\241\214,Y\301\0165\212\207\3702\333\003\324_F\227j\226G\364b\025?L\027\323\225\0256\372\217\263Y\362j/\357\261E\242X5\265\036\317\337\322\376l>{A\3759\276_\257#J\254$\261\266\207L\344\030\312\224\207\024\377w\351\222\364\"\233\207:[\303v\255\"\372%\240\243A\037p\356D\217\337\0209?PK\001\002\024\000\024\000\000\000\b\000\342:nT\222{\260q;\001\000\000\022\002\000\000\021\000\000\000\000\000\000\000\001\000 \000\000\000\000\000\000\000en-US/CRUST.grxmlPK\005\006\000\000\000\000\001\000\001\000?\000\000\000j\001\000\000\000\000\r\n------WebKitFormBoundaryeyaPdl6AduTufZV4--\r\n
While the data after being converted to ByteString looks like this:
=======d2==:content_type: "multipart/form-data; boundary=----WebKitFormBoundaryeyaPdl6AduTufZV4"
data: "------WebKitFormBoundaryeyaPdl6AduTufZV4\\r\\nContent-Disposition: form-data; name=\\\"content\\\"; filename=\\\"473892_CRUST_grammars.zip\\\"\\r\\nContent-Type: application/x-zip-compressed\\r\\n\\r\\nPK\\003\\004\\024\\000\\000\\000\\b\\000\\342:nT\\222{\\260q;\\001\\000\\000\\022\\002\\000\\000\\021\\000\\000\\000en-US/CRUST.grxmleQOO\\2030\\024?\\217OQ\\353\\201\\023+h4s\\026\\226\\005\\227x\\232\\211l1\\272L\\322\\2617\\326\\004ZR\\212\\250\\237\\336\\256\\262\\211YO\\257\\357\\375\\376\\275\\226N>\\313\\002}\\200\\252\\271\\024\\241\\033\\f}\\027\\201\\310\\344\\226\\213<ty\\362\\344\\215F7w^\\340N\\\"\\207\\346\\212\\225%S\\310P\\306\\0053\\000\\f\\302[&\\370\\304\\307\\206\\217\\221\\222R\\2078~^&\\v|\\300\\212:\\304{\\255\\2531!m\\333\\016\\333\\353\\241T9\\271\\362\\375\\200\\370\\267\\244\\023\\305\\221\\203\\272CK\\320\\f\\tVB\\210\\353\\226+\\310R!U\\311\\n\\376\\r\\251\\226i\\245\\344\\206mx\\3015\\207\\032\\243L\\n\\r\\3028\\006\\230D\\2163\\240\\252)\\000\\361\\355)B\\235\\311\\312HU\\315\\246\\340\\231\\361\\031\\f\\250\\024\\340\\311\\335\\237%2=\\256\\241\\214,Y\\301\\0165\\212\\207\\3702\\333\\003\\324_F\\227j\\226G\\364b\\025?L\\027\\323\\225\\0256\\372\\217\\263Y\\362j/\\357\\261E\\242X5\\265\\036\\317\\337\\322\\376l>{A\\3759\\276_\\257#J\\254$\\261\\266\\207L\\344\\030\\312\\224\\207\\024\\377w\\351\\222\\364\\\"\\233\\207:[\\303v\\255\\\"\\372%\\240\\243A\\037p\\356D\\217\\337\\0209?PK\\001\\002\\024\\000\\024\\000\\000\\000\\b\\000\\342:nT\\222{\\260q;\\001\\000\\000\\022\\002\\000\\000\\021\\000\\000\\000\\000\\000\\000\\000\\001\\000 \\000\\000\\000\\000\\000\\000\\000en-US/CRUST.grxmlPK\\005\\006\\000\\000\\000\\000\\001\\000\\001\\000?\\000\\000\\000j\\001\\000\\000\\000\\000\\r\\n------WebKitFormBoundaryeyaPdl6AduTufZV4--\\r\\n"
What I want is for the 2 data fields to look the same. As you can see after the conversion to ByteString, the data content gets escaped again (which I don't want).
I've tried a couple of copyFrom /copyFromUtf8 approaches, providing encoding, even tried to unescape the input using StringEscapeUtils functionality, before passing it into copyFrom, but messes up the message structure.
This message is a multipart form data payload which contains a zip file with a text file in it.
I need this in order to mock a request for some integration tests.
Any idea how I can achieve this ?
Thanks
OK for whoever will be interested, I've took a different approach to solve my problem. Basically I've serialized the whole HttpBody object and dumped it into a text file and then in my tests I've desterilized the content of the file.
That worked.
protected HttpBody deserializeHttpBody(String file) {
try {
InputStream in = this.getClass().getClassLoader().getResourceAsStream("data/" + file);
ObjectInputStream objectInputStream = new ObjectInputStream(in);
HttpBody obj = (HttpBody) objectInputStream.readObject();
objectInputStream.close();
return obj;
} catch (Exception e) {
System.out.println("==============Error==" + e);
}
return null;
}
private void serialize (com.google.api.HttpBody body) {
try {
FileOutputStream fileOutputStream
= new FileOutputStream("/tmp/upload"+System.currentTimeMillis()+".txt");
ObjectOutputStream objectOutputStream
= new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(body);
objectOutputStream.flush();
objectOutputStream.close();
System.out.println("==============Saved==");
} catch (Exception e) {
System.out.println("==============Error==" + e);
}
}

How can I convert an ImageIcon to a String for storage in a JSON

Hello and thank you for your help in advance.
I'm working on an rpg character builder. Each character is stored as a JSON file and I would like to include the character image. This was stored as an ImageIcon, but it can't be stored in a JSON.
How can I convert the ImageIcon to a String and back again?
This is what I have so far:
public ImageIcon getImageIcon() {
byte b[];
ByteArrayInputStream bi;
ObjectInputStream si;
ImageIcon image = null;
try {
b = this.imageIcon.getBytes();
bi = new ByteArrayInputStream(b);
si = new ObjectInputStream(bi);
image = (ImageIcon) si.readObject();
} catch (IOException | ClassNotFoundException ex) {
System.out.println(ex);
}
return image;
}
public void setImageIcon(ImageIcon imageIconIn) {
ByteArrayOutputStream bo;
ObjectOutputStream so;
try{
bo = new ByteArrayOutputStream();
so = new ObjectOutputStream(bo);
so.writeObject(imageIconIn);
so.flush();
this.imageIcon = bo.toString();
} catch (IOException ex){
System.out.println(ex);
}
}
The problem is I get the following error when converting the String back to an ImageIcon:
java.io.StreamCorruptedException: invalid stream header: EFBFBDEF
I think the setImageIcon() method is fine, but I'm not sure how to fix the getImageIcon() method.
I'm using Java 1.8 and GSON 2.8.0
Thanks again for your help.
Your icon should be either stored:
inline in your JSON file as a String using Base64 encoding.
see this thread
in a separate file, and the filename stored as a String in the JSON.
{ "iconFile": "./characters/dwarf.png" }

Serialize - failing after package renaming

Appended are my little utility functions for serialising objects. I just encountered following problem:
I renamed a package and suddenly I get a java.lang.ClassCastException when opening my app and trying to read serialised data...
Can I somehow solve that? I would like my serialisations to be working after a renaming, can I do something to implement this? Via some versioning for example?
Here are my two simple functions I use currently:
public static String serialize(Object object)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try
{
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object);
oos.flush();
oos.close();
} catch (IOException e)
{
L.e(StringUtil.class, e);
}
return Base64.encodeToString(baos.toByteArray(), 0);
}
public static <T> T deserialize(String serializedObject, Class<T> clazz)
{
if (serializedObject == null)
return (T)null;
byte [] data = Base64.decode(serializedObject, 0);
Object o = null;
try
{
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
o = ois.readObject();
ois.close();
}
catch (IOException e)
{
L.e(StringUtil.class, e);
}
catch (ClassNotFoundException e) {
L.e(StringUtil.class, e);
}
return (T)o;
}
I can suggest next options:
add support to your deserialize method to deal with old package names
convert byte [] data to String
replace old package name with new in deserialized data (with regexp)
continue to deserialize with ObjectInputStream

Convert encoded base64 image to File object in Android

I am trying to use the AndroidImageSlider library and populate it with images that I have downloaded as a base64 string.
The library only accepts URLs, R.drawable values, and the File object as parameters.
I am trying to convert the image string to a File object in order to be passed to the library function. I have been able to decode from base_64 and convert to a byte[] so far.
String imageData;
byte[] imgBytesData = android.util.Base64.decode(imageData, android.util.Base64.DEFAULT);
You'll need to save the File object to disk for that to work. This method will save the imageData string to disk and return the associated File object.
public static File saveImage(final Context context, final String imageData) {
final byte[] imgBytesData = android.util.Base64.decode(imageData,
android.util.Base64.DEFAULT);
final File file = File.createTempFile("image", null, context.getCacheDir());
final FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
fileOutputStream);
try {
bufferedOutputStream.write(imgBytesData);
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
It creates a temporary file in your applications 'cache' directory. However, you are still responsible for deleting the file once you no longer need it.

java.io.InvalidClassException: serialization from string to object fail java

I have an Object called Doodle, I serialize it into a String and it's ok.
The problem arrises when I try to deserialize the object, the error is this:
java.io.InvalidClassException: java.util.ArrayList; local class incompatible: stream classdesc serialVersionUID = 8664875232659988799, local class serialVersionUID = 8683452581122892189
The methods to serialize and deserialize are the following:
public static String serDoodle(Doodle dood){
String serializzato = null;
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(dood);
so.flush();
serializzato = bo.toString();
so.close();
bo.close();
} catch (Exception e) {
System.out.println(e);
}
return serializzato;
}
public static Doodle deserDoodle(String deserializza){
Doodle dod = new Doodle();
try {
byte[] b = deserializza.getBytes();
ByteArrayInputStream bi = new ByteArrayInputStream(b);
ObjectInputStream si = new ObjectInputStream(bi);
dod=(Doodle) si.readObject();
si.readObject().getClass();
si.close();
bi.close();
} catch (Exception e) {
System.out.println("deserDoodle "+e);
}
return dod;
}
I use the same method(but with different variable) to serialize another type of object and with that one it works greatly.
I don't understand where is the trouble!
I serialize it into a String and it's ok
No, it isn't OK. String is not a container for binary data. The round-trip between byte-array and String isn't guaranteed to be losses. Don't do this. Use byte[], or at least Base64-encode it.

Categories