I am working on a project where i have to convert XML file in the server and then send them into a JSON form in the client side
The problem is when I have a large XML document since parsing will surpass the limit size of the string.
I even tried changing string into Byte[] but the problem my angular client side accept only JSON form
#RequestMapping(value = "/{var1}/{var2}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getGraph(#PathVariable("var1") String var1, #PathVariable("var2") String var2) {
byte[] result = loadUnloadWorkflow.loadWorkflow("AMAZONTEST", "FR");
return new ResponseEntity<byte[]>(result, HttpStatus.OK);
}
is there a way to parse any XML file whatever it's size into string ?
You could try to convert the XML to an object and then, convert the object to json. What about that?
Related
I have a BDD automation framework setup with Selenium WebDriver and Cucumber with Java. I have configured Rest Assured and I am currently using one JSON payload which is stored in an external JSON file. I am directly reading this JSON file into byte array and then converting the same to String and sending the payload to a post request.
Till now, everything was static and hence, this was working without any issue. However, now the requirement is to send a couple of attributes with dynamic values everytime I make a post call. I know how to send a complete dynamic payload using POJOs but I am looking for a different solution where I can read the payload from the same JSON file and can send dynamic values for few required attributes. Please let me know if this is possible.
Attaching the code for reference.
File which reads the JSON file and sends the payload to post request
public class AddOrderAPIActions {
ConfigReader configReader = new ConfigReader();
Properties prop;
public AddOrderAPIActions() {
prop = configReader.init_prop();
}
//Setting up the API URI
public void setURI() {
String URI = prop.getProperty("apiURI");
RestAssured.baseURI = URI;
}
//Sending the request payload via POST method
public String sendRequestPayload() throws IOException {
//read data from local JSON file then store in byte array
byte[] b = Files.readAllBytes(Paths.get("./src/test/resources/data/addOrder.json"));
//convert byte array to string
String bdy = new String(b);
//input details with header and body
Response response = given().header("Content-type", "application/json").queryParam("api_key", prop.getProperty("apiKey")).body(bdy)
//adding post method
.when().post().then().log().all().extract().response();
JsonPath jp = response.jsonPath();
String shipmentNumber = jp.get("data.shipmentDetails[0].shipmentNumber");
System.out.println("Shipment Number is "+ shipmentNumber);
return shipmentNumber;
}
}
The JSON file with payload
[
{
"originDetails": {
"originCode": "Dynamic_Value",
"originStartTime": "",
"originEndTime": "",
"senderName": "Origin Name",
"senderContactNumber": "9999999999",
"senderAddress": "Bali, Indonesia",
"senderPincode": "201001",
"senderCity": "Delhi",
"senderCountry": "India"
},
]
Here, I want to send a dynamic value for "originCode" attribute and rest of the attributes should be sent as read from the JSON file.
Thanks in advance.
i want to save protocol-buffers object via string, in JAVA
but when i use ByteString with encode UTF_8 ,parse result not correct
public static void test2() throws InvalidProtocolBufferException {
CrcCertInfoRequest data = CrcCertInfoRequest.newBuilder().setCompanyType(222).build();
Charset charset = StandardCharsets.UTF_8;
String proStr = data.toByteString().toString(charset);
ByteString bs2 = ByteString.copyFrom(proStr, charset);
String json = ObjectMapperUtils.toJSON(data);
System.out.println("proStr=" + proStr.length() + "json=" + json.length());
System.out.println(ObjectMapperUtils.toJSON(CrcCertInfoRequest.parseFrom(bs2)));
System.out.println(ObjectMapperUtils.toJSON(ObjectMapperUtils.fromJSON(json, CrcCertInfoRequest.class)));
}
code output:
proStr=3json=119
{"appId":0,"createSource":0,"certType":0,"accountType":0,"companyType":3104751,"industryCategory1":0,"industryCategory2":0}
{"appId":0,"createSource":0,"certType":0,"accountType":0,"companyType":222,"industryCategory1":0,"industryCategory2":0}
the integer field companyType parse result is incorrect.supposed to be 222 but is 3104751
i tried other charset ,use ISO_8859_1 is ok ,but i'm not sure it's always ok.
protobuf version is protobuf-java-3.16.1.jar
java version is jdk1.8.0_171.jdk
how can i save and parse protobuf data using string in java?
ByteString is an immutable sequence of bytes and is not an actual String. Interpreting the bytes as UTF-8 does not work because it's not UTF-8 data. It's also not ISO_8859_1 or any other String encoding even if the parsing is lenient enough to not throw an error.
how can I save and parse protobuf data using string in java?
Convert the raw bytes to Base64.
Is it possible with spring boot and for example apache poi to get POST request json format with excel file inside?
for example :
POST api/testrequest/
Content-Type: application/json //(maybe another type?)
{
"searchKey": "test1",
"searchValue": file.excel
}
And fetch it to Object?
Now I did something like this :
Controller method :
#PostMapping(
value = "excelentity",
consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_JSON_VALUE})
public String getExcelAndParseItToEntity(#RequestBody ExcelTemplate file) {
String fileName = file.getFile().getOriginalFilename();
log.info(fileName);
return "test case";
}
And Java Object :
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class ExcelTemplate {
private MultipartFile file;
private String name;
}
But it doesn't work
You can't include it directly but you can encode it as string.
The client sending that json request to your spring boot application can encode the file to base64 and include the resulting string in the json as text.
Something like that:
byte[] fileContent = readExcelFile(file); // Use InputStreams to read all bytes of the excel
String encodedFile = Base64.getEncoder().encodeToString(fileContent);
doRequest(encodedFile); // Do request, set 'encodedFile' as value of 'searchValue' in json
Your json would then look something like that:
{
"searchKey": "test1",
"searchValue": "SGVsbG8gU3RhY2tPdmVyZmxvdyE=..."
}
In your spring boot application simply decode it to bytes again and save it as file or use it directly with a ByteArrayInputStream.
var searchValue = getFromJson(json); // get the value from your json / dto
byte[] decodedBytes = Base64.getDecoder().decode(searchValue);
// Save to a file then use it
saveToFile(decodedBytes);
// Or
// Use it directly as InputStream without saving it to file
var inputStream = new ByteArrayInputStream(decodedBytes);
See this baeldung tutorial for more information on how to use Base64: https://www.baeldung.com/java-base64-encode-and-decode
And this one for the ByteArrayInputStream: https://www.baeldung.com/convert-byte-array-to-input-stream
When we get input from any other Service/API in our own microservice, how our spring-boot application will know that the input type is either XML type or JSON type payload internally. And. After it is getting the actual kind of payload as input if I want to convert from XML to JSON or vice-versa, how it will work, will it have the same native method as below;
public static String xml= "<?xml version=\"1.0\" ?><root><test attribute=\"text1\">XML DATA</test><test attribute=\"text2\">DATA DATA</test></root>";
JSONObject json = XML.toJSONObject(xml);
String jsonString = json.toString(4);
System.out.println(jsonString);
//Convert from XML to JSON
and while converting from XML to JSON,
JSONObject jsonObject = new JSONObject(jsonString);
String xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-15\"?>\n<"+root+">" + XML.toString(jsonObject) + "</"+root+">";
Or is there any other way to convert?
Simply my query is like, how to know what is the input type and how our application will recognize this?
You can read the content type request header as an argument in your controller's class mapping method:
public class APIController {
#GetMapping(
public String getMethod(#RequestBody String body, #RequestHeader("Content-type") String contentType) {
}
}
String json="{"FROM_JID":"6bc24cac4eaf304ce1731bd5aebe9b0419052701","TO_JID":"dfc8d53f402373a1d3622dde50e180b388b36bc1","TYPE_ID":"1","PLATFORM":"IOS","CONTENT":"{\"FROM_JID\":\"6bc24cac4eaf304ce1731bd5aebe9b0419052701\",\"FROM_HOST\":\"ssdevim.mtouche-mobile.com\",\"FROM_JNAME\":\"test1\",\"TO_JID\":\"dfc8d53f402373a1d3622dde50e180b388b36bc1\",\"TO_HOST\":\"ssdevim.mtouche-mobile.com\",\"MESSAGE_ID\":\"LiYaU-39\",\"MESSAGE_TYPE\":\"enc\",\"MESSAGE\":\"test1 has sent you an encrypted message.\",\"STAMP\":\"2015-11-12 12:04:54.252241\",\"BADGE\":3,\"CONTENT-AVAILABLE\":1,\"SOUND\":\"dafault\"}","DEVICE_ID":"AC53D4F0-DAAA-475E-9668-5E9E7485797C","PUSH_ID":"c9544c8db2117f02f3edc8af9058b3d54c15500302bf6f47c487193876f6dc23","CREATE_DATE":"2015-11-12","CREATE_TIME":"04:04:54"}";
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
but it showing error
First, this won't compile:
String json="{"FROM_JID":"6bc24cac4eaf304ce1731bd5aebe9b0419052701","TO_JID":"dfc8d53f402373a1d3622dde50e180b388b36bc1","TYPE_ID":"1","PLATFORM":"IOS","CONTENT":"{\"FROM_JID\":\"6bc24cac4eaf304ce1731bd5aebe9b0419052701\",\"FROM_HOST\":\"ssdevim.mtouche-mobile.com\",\"FROM_JNAME\":\"test1\",\"TO_JID\":\"dfc8d53f402373a1d3622dde50e180b388b36bc1\",\"TO_HOST\":\"ssdevim.mtouche-mobile.com\",\"MESSAGE_ID\":\"LiYaU-39\",\"MESSAGE_TYPE\":\"enc\",\"MESSAGE\":\"test1 has sent you an encrypted message.\",\"STAMP\":\"2015-11-12 12:04:54.252241\",\"BADGE\":3,\"CONTENT-AVAILABLE\":1,\"SOUND\":\"dafault\"}","DEVICE_ID":"AC53D4F0-DAAA-475E-9668-5E9E7485797C","PUSH_ID":"c9544c8db2117f02f3edc8af9058b3d54c15500302bf6f47c487193876f6dc23","CREATE_DATE":"2015-11-12","CREATE_TIME":"04:04:54"}";
You even can notice that its syntax is not highlighted properly.
You need to escape your quotes in order to make Java recognize it as a part of a string, but not your code:
String json="{\"FROM_JID\":\"6bc24cac4eaf304ce1731bd5aebe9b0419052701\",\"TO_JID\":\"dfc8d53f402373a1d3622dde50e180b388b36bc1\",\"TYPE_ID\":\"1\",\"PLATFORM\":\"IOS\",\"CONTENT\":\"{\\\"FROM_JID\\\":\\\"6bc24cac4eaf304ce1731bd5aebe9b0419052701\\\",\\\"FROM_HOST\\\":\\\"ssdevim.mtouche-mobile.com\\\",\\\"FROM_JNAME\\\":\\\"test1\\\",\\\"TO_JID\\\":\\\"dfc8d53f402373a1d3622dde50e180b388b36bc1\\\",\\\"TO_HOST\\\":\\\"ssdevim.mtouche-mobile.com\\\",\\\"MESSAGE_ID\\\":\\\"LiYaU-39\\\",\\\"MESSAGE_TYPE\\\":\\\"enc\\\",\\\"MESSAGE\\\":\\\"test1 has sent you an encrypted message.\\\",\\\"STAMP\\\":\\\"2015-11-12 12:04:54.252241\\\",\\\"BADGE\\\":3,\\\"CONTENT-AVAILABLE\\\":1,\\\"SOUND\\\":\\\"dafault\\\"}\",\"DEVICE_ID\":\"AC53D4F0-DAAA-475E-9668-5E9E7485797C\",\"PUSH_ID\":\"c9544c8db2117f02f3edc8af9058b3d54c15500302bf6f47c487193876f6dc23\",\"CREATE_DATE\":\"2015-11-12\",\"CREATE_TIME\":\"04:04:54\"}";
Second, if you already have a String and you want to convert it to byte[], why do you deserialize it? Just convert it to byte array:
byte[] bytes = json.getBytes();