parsing XML to base64 and json - java

I am trying to encode an XML to Base64 and then, write this Base64 to a JSON file.
When i do it, the Base64 is complete, but the JSON is incomplete, there is no trailing } at the end of string and it is incomplete, I do not know what could be do.
Here is my code:
This is the Xml to Base64 encoder
public static String fileEncoderBase64() throws IOException {
File file = new File("/root/EntradaN1.xml");
BufferedReader bufferedReader = null;
String linea;
String lineas = null;
try {
bufferedReader = new BufferedReader(new FileReader(file));
while ((linea = bufferedReader.readLine()) != null) {
lineas += linea;
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
bufferedReader.close();
}
return encodeBase64(lineas);
}
public static String encodeBase64(String mensaje) throws UnsupportedEncodingException {
byte[] bytes = mensaje.getBytes("UTF-8");
return Base64.getEncoder().encodeToString(bytes);
}
And this is the JSON parser:
public static void jsonCreator(JsonModelAgent jsonModelAgent) throws IOException {
Gson gson = new Gson();
gson.toJson(jsonModelAgent, new BufferedWriter(new FileWriter("/root/datos.json")));
}
And this is de diferences between mongo's Base64 length and json's length.
JSON: ==============>65176
MONGO: =============>76592
Thanks for help.

just adding close to jsonCreator's fileWriter works

Related

Trying to validate a json against Json Schema in java but getting java.lang.NoSuchMethodError

I want to validate a JSON object with JSON schema.
This is my method:
public static void jsonSchemValidator(String json, String defination) throws ValidationException, JSONException, IOException )
{
JSONObject jsonSchemaori = new JSONObject(new JSONTokener(readFromResources(defination)));
JSONObject jsonSubject = new JSONObject(new JSONTokener(readFromResources(json)));
Schema schema = SchemaLoader.load(jsonSchemaori);
schema.validate(jsonSubject);
}
String defination="src/test/resources/json/pick_event_schema.json";
String json="src/test/resources/json/pickevent1.json";
Utils.jsonSchemValidator(json,schema);
I generated the Schema file from the following site: https://www.liquid-technologies.com/online-json-to-schema-converter
This is my readFromResources:
public static String readFromResources(String fileName) throws IOException {
File file = new File(fileName);
String filePath = file.getAbsolutePath();
StringBuilder sb = new StringBuilder();
FileReader fr = new FileReader(filePath);
try( BufferedReader br = new BufferedReader(fr) ) {
String contentLine = br.readLine();
while (contentLine != null) {
sb.append(contentLine);
contentLine = br.readLine();
}
} catch (IOException e) {
throw e;
}
return sb.toString();
}
I am getting an exception:
java.lang.NoSuchMethodError: org.json.JSONObject.getNames(Lorg/json/JSONObject;)[Ljava/lang/String;
Please let me where I am going wrong. Thank you.

Read json file from resources and convert it into json string in JAVA [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have this JSON string hardcoded in my code.
String json = "{\n" +
" \"id\": 1,\n" +
" \"name\": \"Headphones\",\n" +
" \"price\": 1250.0,\n" +
" \"tags\": [\"home\", \"green\"]\n" +
"}\n"
;
I want to move this to resources folder and read it from there,
How can I do that in JAVA?
This - in my experience - is the most reliable pattern to read files from class path.[1]
Thread.currentThread().getContextClassLoader().getResourceAsStream("YourJsonFile")
It gives you an InputStream [2] which can be passed to most JSON Libraries.[3]
try(InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("YourJsonFile")){
//pass InputStream to JSON-Library, e.g. using Jackson
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readValue(in, JsonNode.class);
String jsonString = mapper.writeValueAsString(jsonNode);
System.out.println(jsonString);
}
catch(Exception e){
throw new RuntimeException(e);
}
[1] Different ways of loading a file as an InputStream
[2] Try With Resources vs Try-Catch
[3] https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
Move json to a file someName.json in resources folder.
{
id: 1,
name: "Headphones",
price: 1250.0,
tags: [
"home",
"green"
]
}
Read the json file like
File file = new File(
this.getClass().getClassLoader().getResource("someName.json").getFile()
);
Further you can use file object however you want to use. you can convert to a json object using your favourite json library.
For eg. using Jackson you can do
ObjectMapper mapper = new ObjectMapper();
SomeClass someClassObj = mapper.readValue(file, SomeClass.class);
There are many possible ways of doing this:
Read the file completely (only suitable for smaller files)
public static String readFileFromResources(String filename) throws URISyntaxException, IOException {
URL resource = YourClass.class.getClassLoader().getResource(filename);
byte[] bytes = Files.readAllBytes(Paths.get(resource.toURI()));
return new String(bytes);
}
Read in the file line by line (also suitable for larger files)
private static String readFileFromResources(String fileName) throws IOException {
URL resource = YourClass.class.getClassLoader().getResource(fileName);
if (resource == null)
throw new IllegalArgumentException("file is not found!");
StringBuilder fileContent = new StringBuilder();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(new File(resource.getFile())));
String line;
while ((line = bufferedReader.readLine()) != null) {
fileContent.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return fileContent.toString();
}
The most comfortable way is to use apache-commons.io
private static String readFileFromResources(String fileName) throws IOException {
return IOUtils.resourceToString(fileName, StandardCharsets.UTF_8);
}
Pass your file-path with from resources:
Example: If your resources -> folder_1 -> filename.json Then pass in
String json = getResource("folder_1/filename.json");
public String getResource(String resource) {
StringBuilder json = new StringBuilder();
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(resource)),
StandardCharsets.UTF_8));
String str;
while ((str = in.readLine()) != null)
json.append(str);
in.close();
} catch (IOException e) {
throw new RuntimeException("Caught exception reading resource " + resource, e);
}
return json.toString();
}
There is JSON.simple is lightweight JSON processing library which can be used to read JSON or write JSON file.Try below code
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try (Reader reader = new FileReader("test.json")) {
JSONObject jsonObject = (JSONObject) parser.parse(reader);
System.out.println(jsonObject);
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
try(InputStream inputStream =Thread.currentThread().getContextClassLoader().getResourceAsStream(Constants.MessageInput)){
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readValue(inputStream ,
JsonNode.class);
json = mapper.writeValueAsString(jsonNode);
}
catch(Exception e){
throw new RuntimeException(e);
}

How to Read Arabic text from .txt file in Android [duplicate]

This question already has answers here:
Why is Java BufferedReader() not reading Arabic and Chinese characters correctly?
(3 answers)
Closed 6 years ago.
i m trying to read a file having having arabic text and then i need to place read text in a text view..
following is the code i tried:
public static String readRawFile(Context ctx, int resId) throws UnsupportedEncodingException {
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(isr);
String line;
StringBuilder text = new StringBuilder();
try {
while ((line = reader.readLine()) != null) {
text.append(line);
Log.e("Line Read", line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
but what i the file read is following
��(P3�EP ��qDDGP ��qD1QN-�EN#pFP ��qD1QN-PJEP ���
how should i read file such that the text read is in arabic
trying using only Bufferreader, with it i can read both arabic and english words at the same time. And you dont need the UT-8 encoding.
I hope this helps you:
public static void readArabic(String path) throws FileNotFoundException {
try(BufferedReader red = new BufferedReader(new FileReader(path));) {
String out;
while ((out = red.readLine()) != null){
System.out.println(out);
}
} catch (IOException e) {
e.printStackTrace();
}
}
This is the main method:
public static void main(String[] args) throws FileNotFoundException {
String path1 = "/Users/addodennis/Desktop/Projects/HotelReservation/src/Data/testAra";
readArabic(path1);
}
And this is the output:
I just copied some arabic text from the wikipedia page.
الأَبْجَدِيَّة العَرّة‎‎ al-abjadīyah al-ʻarabīyah or الحُرُوف العَرَبِيَّة
’ī (هِجَائِي) or alifbā’ī (أَلِفْبَائِي)
يواجه مستخدمو الانترنت السوريون منذ بعض الوقت صعوبة في الدخول إلى موقع (ويكيبيديا
الولوج إلى صفحات موقع الموسوعة الحرة (ويكيبيديا)، وهو واحد من أشهر المواقع العالمية على الشبكة الدولية.
And if you still want to use StringBuilder then you can do this also:
public static String readArabic(String path) throws FileNotFoundException {
StringBuilder add = new StringBuilder();
try(BufferedReader red = new BufferedReader(new FileReader(path));) {
String out;
while ((out = red.readLine()) != null){
//System.out.println(out);
add.append(out);
}
} catch (IOException e) {
e.printStackTrace();
}
return String.valueOf(add);
}

Cant get String out of Base64 encoded ByteArrayDataSource

I have a String converted with org.apache.axis2.databinding.utils.ConverterUtil to a Base64Binary (ByteArrayDataSource inside a DataHandler).
When I try to convert it back to the string, it doestn work. I cant figure out why. What am I missing?
Here`s the code:
#Test
public void testBase64() {
DataHandler test = ConverterUtil.convertToBase64Binary("TEST");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(test.getDataSource().getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
String result = new String(Base64.decode(sb.toString()));
} catch (IOException e) {
e.printStackTrace();
}
As you can see.. result string is empty..
I hope someone can help me with this.
Thanks

Read utf-8 url to string java

Good day. Have just switched from objective-c to java and trying to read url contents normally to string. Read tons of posts and still it gives garbage.
public class TableMain {
/**
* #param args
*/
#SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
URL url = null;
URLConnection urlConn = null;
try {
url = new URL("http://svo.aero/timetable/today/");
} catch (MalformedURLException err) {
err.printStackTrace();
}
try {
urlConn = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader input = new BufferedReader(new InputStreamReader(
urlConn.getInputStream(), "UTF-8"));
StringBuilder strB = new StringBuilder();
String str;
while (null != (str = input.readLine())) {
strB.append(str).append("\r\n");
System.out.println(str);
}
input.close();
} catch (IOException err) {
err.printStackTrace();
}
}
}
What's wrong? I get something like this
??y??'??)j1???-?q?E?|V??,??< 9??d?Bw(?э?n?v?)i?x?????Z????q?MM3~??????G??љ??l?U3"Y?]????zxxDx????t^???5???j?‌​?k??u?q?j6?^t???????W??????????~?????????o6/?|?8??{???O????0?M>Z{srs??K???XV??4Z‌​??'??n/??^??4????w+?????e???????[?{/??,??WO???????????.?.?x???????^?rax??]?xb??‌​& ??8;?????}???h????H5????v?e?0?????-?????g?vN
Here is a method using HttpClient:
public HttpResponse getResponse(String url) throws IOException {
httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
return httpClient.execute(new HttpGet(url));
}
public String getSource(String url) throws IOException {
StringBuilder sb = new StringBuilder();
HttpResponse response = getResponse(url);
if (response.getEntity() == null) {
throw new IOException("Response entity not set");
}
BufferedReader contentReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = contentReader.readLine();
while ( line != null ){
sb.append(line)
.append(NEW_LINE);
line = contentReader.readLine();
}
return sb.toString();
}
Edit: I edited the response to ensure it uses utf-8.
This is a result of:
You are fetching data that is UTF-8 encoded
You are didn't specify, but I surmise you are printing it to the console on a Windows system
The data is being received and stored correctly, but when you print it the destination is incapable of rendering the Russian text. You will not be able to just "print" the text to stdout unless the ultimate display handler is capable of rendering the characters involved.

Categories