I have a byte[] array. Suppose-
byte[] b = new byte[] {'11', '22', '33', '44'};
I want to store this array in Elasticsearch and get this byte array from elasticsearch by java. How can I do it? Please someone show me an example.
For example I want to see something like this-
SearchHit hit = searchResponse.getHits().getHits();
byte[] b = (byte[]) hit.getSource().get("byte_array");
But I am getting this error. Please someone help me
java.lang.ClassCastException: java.util.ArrayList cannot be cast to [B
Related
I have below situation. It needs to be implemented in Java.
Take input from a text file, convert the content into a byte array.
Use the above byte array as a part of a JSON object , create a .json file
For point1, i have done something like this.
InputStream is = new ClassPathresource("file.txt").getInputStream();
byte[] ip = IOUtils.toByteArray(is);
For point2, my Json file (containing json object), should look like below.
{
"name": "xyz",
"address: "address here",
"ipdata": ""
}
The ipdata should contain the byte array created in step 1.
How can i create a json object with the byte array created in step 1 as a part of it ? And then write the entire content to a separate .json file ?
Also is the byte array conversion done in step1 an optimum way, or do we need to use any other API(may be to take care of encoding)?Please suggest.
Any help is appreciated. Thanks in advance.
You can simply convert the byte array ip using ip.toString()
Or if you know the encoding you can use ipString = new String(ip, "UTF8")
And then take that string to add to your json object.
Since you are reading a JSON string from file and want to write it back to a new json file you dont need the JSON Object conversion in-between. Just convert the byte[] to String as
String ips = new String(ip);
Now create a JSON Object with the data you want to write to the new file. And then you can write the data to file using FileWriter. PFB the code-
JSONObject obj = new JSONObject();
obj.put("name", "xyz");
obj.put("address", "address here");
obj.put("ipdata", ips);
try(FileWriter fileWriter =
new FileWriter("newFileName.json") ){
fileWriter.write(obj.toString());
}
In my Oracle table I am using a BLOB field to save the byte array which is originally a JSON string from user input on page.
For example, this is what the client passes to the server:
"{'AD_ID_NBR':'440111111111177777'}"
On the server side, it will be converted to a byte array and stored into BLOB.
byte[] bytes = input.getUserInput();//userInput is byte[]
ps.setBlob(2, new ByteArrayInputStream(bytes));
When returning the user input to the client side, I need to do the reverse.
input.setUserInput(rs.getBlob("USER_INPUT").getBytes(1l, (int)rs.getBlob("USER_INPUT").length()));
Then on the client side I will get :
"userInput": "eydBRF9JRF9OQlInOic0NDAxMTExMTExMTExMjIyMjInfQ=="
Obviously it is not what I need. Some conversion should be done here.
My question is how to convert this string into the json string that I had saved before. Thanks.
Blob blob = rs.getBlob("USER_INPUT");
byte[] bdata = blob.getBytes(1, (int) blob.length());
String s = new String(bdata);
I m trying to get/convert the value of Arraylist in byte[]
below is my code
final ArrayList<Object> imglists = new ArrayList<Object>();
this is my arraylist of Objects in this arraylist m storing the values of images in form of bytes
for (int i=0; i<mPlaylistVideos.size();i++) {
holder.mThumbnailImage.buildDrawingCache();
Bitmap bitmap= holder.mThumbnailImage.getDrawingCache();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bs);
byte[] rough = bs.toByteArray();
imglists.add(i,rough);
}
I m trying to get the specific value from arraylist and store that in byte[]
this is what I was trying to do
byte[] value=imglists.get(2);
I could not find any complete answer to convert Arraylist of Object into byte[]
I know Arraylist doesn't support primitive datatype (i-e byte)
What you are looking for is a List of byte[], something like that:
List<byte[]> imglists = new ArrayList<>();
Then you can simply add your byte array to your List using the add(E) method as next:
imglists.add(bs.toByteArray());
You will then be able to access to a given byte array from its index in the List using the method get(int) as you try to achieve:
// Get the 3th element of my list
byte[] value = imglists.get(2);
You want to convert ArrayList to byte[] ? or Object to byte[]?
I wrote in this way, just simply convert the element in ArrayList into byte[] ,it works!
List<Object> objects = new ArrayList<Object>();
objects.add("HelloWorld".getBytes());
byte[] bytes = (byte[]) objects.get(0);
System.out.println(new String(bytes)); // HelloWorld
I tried to get my byte[] value from JSONObject using following code but I am not getting original byte[] value.
JSONArray jSONArray = jSONObject.getJSONArray(JSONConstant.BYTE_ARRAY_LIST);
int len = jSONArray.length();
for (int i = 0; i < len; i++) {
byte[] b = jSONArray.get(i).toString().getBytes();
//Following line creates pdf file of this byte arry "b"
FileCreator.createPDF(b, "test PDF From Web Resource.pdf");
}
}
Above code creates pdf file but file can not open i.e corrupted file. But, when I use same class and method to create file:
FileCreator.createPDF(b, "test PDF From Web Resource.pdf");
before adding into JSONObject like follwoing:
JSONObject jSONObject = new JSONObject();
jSONObject.put(JSONConstant.BYTE_ARRAY_LIST, bList);
it creates file i.e I can open pdf file and read its content.
What I did wrong to get byte[] from JSONObject so that it is creating corrupted file? Please kindly guide me. And I always welcome to comments. Thank You.
Finally I solved my issue with the help of apache commons library. First I added the following dependency.
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.6</version>
<type>jar</type>
</dependency>
The technique that I was using previously was wrong for me (Not sure for other). Following is the solution how I solved my problem.
Solution:
I added byte array value previously on JSONObject and stored as String. When I tried to get from JSONObject to my byte array it returned String not my original byte array. And did not get the original byte array even I use following:
byte[] bArray=jSONObject.getString(key).toString().getBytes();
Now,
First I encoded my byte array into string and kept on JSONObject. See below:
byte[] bArray=(myByteArray);
//Following is the code that encoded my byte array and kept on String
String encodedString = org.apache.commons.codec.binary.Base64.encodeBase64String(bArray);
jSONObject.put(JSONConstant.BYTE_ARRAY_LIST , encodedString);
And the code from which I get back my original byte array:
String getBackEncodedString = jSONObject.getString(JSONConstant.BYTE_ARRAY_LIST);
//Following code decodes to encodedString and returns original byte array
byte[] backByte = org.apache.commons.codec.binary.Base64.decodeBase64(getBackEncodedString);
//Creating pdf file of this backByte
FileCreator.createPDF(backByte, "fileAfterJSONObject.pdf");
That's it.
This might be of help for those using Java 8. Make use of java.util.Base64.
Encoding byte array to String :
String encodedString = java.util.Base64.getEncoder().encodeToString(byteArray);
JSONObject.put("encodedString",encodedString);
Decode byte array from String :
String encodedString = (String) JSONObject.get("encodedString");
byte[] byteArray = java.util.Base64.getDecoder().decode(encodedString);
For tests example(com.fasterxml.jackson used):
byte[] bytes = "pdf_report".getBytes("UTF-8");
Mockito.when(reportService.createPackageInvoice(Mockito.any(String.class))).thenReturn(bytes);
String jStr = new ObjectMapper().writeValueAsString(bytes).replaceAll("\\\"", ""); // return string with a '\"' escape...
mockMvc.perform(get("/api/getReport").param("someparam", "222"))
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
...
.andExpect(jsonPath("$.content", is(jStr)))
;
When inserting a byte array into a JSONObject the toString() method is invoked.
public static void main(String... args) throws JSONException{
JSONObject o = new JSONObject();
byte[] b = "hello".getBytes();
o.put("A", b);
System.out.println(o.get("A"));
}
Example output:
[B#1bd8c6e
so you have to store it in a way that you can parse the String into the original datatype.
I am developing a Web application in Java. In that application, I have created webservices in Java. In that webservice, I have created one webmethod which returns the image list in base64 format. The return type of the method is Vector. In webservice tester I can see the SOAP response as xsi:type="xs:base64Binary". Then I called this webmethod in my application. I used the following code:
SBTSWebService webService = null;
List imageArray = null;
List imageList = null;
webService = new SBTSWebService();
imageArray = webService.getSBTSWebPort().getAddvertisementImage();
Iterator itr = imageArray.iterator();
while(itr.hasNext())
{
String img = (String)itr.next();
byte[] bytearray = Base64.decode(img);
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
imageList.add(imag);
}
In this code I am receiving the error:
java.lang.ClassCastException: [B
cannot be cast to java.lang.String" on
line String img = (String)itr.next();
Is there any mistake in my code? Or is there any other way to bring the image in actual format? Can you provide me the code or link through which I can resolve the above issue?
Note:- I already droped this question and I got the suggetion to try the following code
Object next = iter.next();
System.out.println(next.getClass())
I tried this code and got the output as byte[] from webservice. but I am not able to convert this byte array to actual image.
is there any other way to bring the image in actual format? Can you provide me the code or link through which I can resolve the above issue?
You can check this link which provides information about converting image to Byte[] and Byte[] back to image. Hope this helps you.
http://www.programcreek.com/2009/02/java-convert-image-to-byte-array-convert-byte-array-to-image/
To convert use Base64.decode;
String base64String = (String)itr.next();
byte[] bytearray = Base64.decode(base64String);
BufferedImage imag=ImageIO.read(bytearray);
I'm not familiar with what you're trying to do, but I can say this: String does have a constructor that takes a byte[].
If I understood you correctly, you tried to do String s = (String) byteArray;, which of course doesn't work. You can try String s = new String(byteArray);.
Looking at the actual error message:
java.lang.ClassCastException: [B cannot be cast to java.lang.String
on line String img = (String)itr.next();
I'm saying that perhaps you meant to do:
String img = new String(itr.next());