How to parse AEM DAM JSON InputStream and create JSON Object - aem

I have a requirement where-in I have to read the JSON file which exists in AEM DAM. So, I have created a query to read the JSON file in inputStream. With the below line of code, i could get the JSON file in Input Stream. Now, I need to know If there is any standard library to read the input stream and create the JSON Object?
InputStream is = asset.getOriginal().getStream();

There are many libraries for serializing/deserializing JSON in java, the most notable is Google’s Gson: https://github.com/google/gson
I’ve used gson in all my AEM projects that require JSON manipulation. That does not mean you can’t use another library.

As mentioned above there are many libraries like Google’s Gson, Jackson an etc. I think the below code snippet can help you,
public JSONObject getJsonFromFile(ResourceResolver resolver,String filePath){
JSONObject jsonObj=new JSONObject();
Resource resource= resolver.getResource(filePath);
try {
Node jcnode = resource.adaptTo(Node.class).getNode("jcr:content");
InputStream content=jcnode.getProperty("jcr:data").getBinary().getStream();
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new
InputStreamReader(content,StandardCharsets.UTF_8));
while ((line = br.readLine()) != null) {
sb.append(line);
}
jsonObj = new JSONObject(sb.toString());
}catch (RepositoryException | JSONException | IOException e) {
LOGGER.error(e.getMessage(),e);
}
return jsonObj;
}

Related

What is the relevant code for getInputStream() in Swift 5?

In Android Studio, I use this code to get data from server
url = new URL(url);
HttpURLConnection connection = null;
try
{
HttpURLConnection.setFollowRedirects(false);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
connection.setInstanceFollowRedirects(false);
InputStream inputStream = connection.getInputStream();
this.header = connection.getHeaderFields();
this.status = connection.getResponseCode();
}
In Swift 5, I'm able to perform similar task by using URLSession.shared.dataTask(), but I couldn't find anything to replace InputStream inputStream = connection.getInputStream().
After I did some research on Swift 5 inputStream and outputStream, I'm getting more confused, can anyone provide some sample on how to replace this?
Use uploadTask(withStreamedRequest in order to work with streams https://developer.apple.com/documentation/foundation/urlsession/1410934-uploadtask

send email with multiple attachment in scala

I have used the java mail API to send emails within our group. I am aware of the DataHandler objects that in turn uses FileDataSource to grab the files and attach as a multipart file. However, I am not able to use it in scala. Can anyone help me on this?
Heres my code:
def createMessage: Message = {
val properties = new Properties()
properties.put("mail.smtp.host", smtpHost)
properties.put("mail.smtp.port",smtpPort)
val session = Session.getDefaultInstance(properties, null)
return new MimeMessage(session)
}
var message: Message = null
message = createMessage
message.setFrom(new InternetAddress(from))
message.setSentDate(new Date())
message.setSubject(subject)
message.setText(content)
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to))
def sendMessage {
Transport.send(message)
}
I can use message.sefileName to set file name of the attachment, but how can I attach the actual files. For example in Java, we can achieve similar results like the following:
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageText);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
FileDataSource fdatasource = new FileDataSource(file);
messageBodyPart2.setDataHandler(new DataHandler(fdatasource));
messageBodyPart2.setFileName(fdatasource.getName)
Multipart mpart = new MimeMultipart();
mpart.addBodyPart(messageBodyPart1);
mpart.addBodyPart(messageBodyPart2);
message.setContent(mpart);
I don't know this mail API, but you should be able to use a Java API the same way in Scala that you would use it in Java. If you see something like this in Java:
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageText);
You usually want to translate it to something like this in Scala:
val messageBodyPart1: MimeBodyPart = new MimeBodyPart()
messageBodyPart1.setText(messageText)
Just translate the Java code you have posted to Scala this way and it should work as well (or not well) as it worked in Java.

Escape Sequence in Camel restlet / rest dsl

Camel Route -
rest("/servicenow").post("/{operation}").consumes("application/json").type(Model.class).produces(MediaType.APPLICATION_JSON).to("direct:servicenow");
from("direct:servicenow")
.setHeader("operationSelector", simple("${header.operation}"))
.process(new PreProcessor())
.recipientList().simple("servicenow://${header.instance}?userName=${header.name}&password=${header.password}&apiUrl=${header.apiUrl}")
.process(new PostProcessor());
and PostProcessor Class -
Object msg = exchange.getIn().getBody();
GsonBuilder builder = new GsonBuilder();
builder.setLenient();
Gson gson = builder.create();
JsonElement element = gson.toJsonTree(msg);
JsonObject result = new JsonObject();
if (element.isJsonArray()) {
JsonArray array = (JsonArray) element;
result.add("result", array);
System.out.println(result.toString());
exchange.getOut().setBody(result.toString());
} else {
result.add("result", element);
System.out.println(result.toString());
exchange.getOut().setBody(result.toString());
}
Example result contains escape sequences in the JSON Array/Object while returning to the Client
"{\"result\":[{\"parent\":\"\",\"made_sla\":\"true\",\"caused_by\":\"\"
Please do help to modify in the restlet configuration if required so I get response without escape sequence in JSON response.
Instead of using this line :
JsonObject result = new JsonObject();
Use this prefered answer :
Map<DataType,DataType> result = new HashMap<DataType,DataType>();
result.put("result", array);
exchange.getOut().setBody(result);
The restlet will bind the map object to a jsonObject.

Spring RestTemplate POST file with UTF-8 filename

I'm using Spring RestTemplate to perform POST request sending a PDF file. The filename contains some UTF-8 characters (e.g. é, è, à, ê, ë).
The problem is that after sending the request, on the other side where the request is received, the filename doesn't have the expected UTF-8 characters, and I have something like ?popi?.pdf instead.
I've tried to explicitly set UTF-8 charset in RestTemplate, but it still doesn't work.
Here is my code,
public SomeThing storeFile(InputStream content, String fileName) {
Charset utf8 = Charset.forName("UTF-8");
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headersFile = new HttpHeaders();
headersFile.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headersFile.setContentDispositionFormData("file", fileName);
List<Charset> listCharSet = new ArrayList<Charset>();
listCharSet.add(utf8);
headersFile.setAcceptCharset(listCharSet);
InputStreamResource inputStreamResource = new InputStreamResource(content);
HttpEntity<InputStreamResource> requestEntityFile = new HttpEntity<>(inputStreamResource, headersFile);
MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
multipartRequest.add("file", requestEntityFile);
RestTemplate newRestTemplate = new RestTemplate();
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
HttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
newRestTemplate.getMessageConverters().add(0, stringHttpMessageConverter);
newRestTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
FormHttpMessageConverter convForm = new FormHttpMessageConverter();
convForm.setCharset(utf8);
newRestTemplate.getMessageConverters().add(convForm);
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(multipartRequest, header);
ResponseEntity<String> result = newRestTemplate.postForEntity(env.getProperty("core.endpoint") + "/documents", requestEntity, String.class);
}
according to rfc7578 when you POST a file with multipart/form-data you should use "percent-encoding" instead of filename*
NOTE: The encoding method described in [RFC5987], which would add a
"filename*" parameter to the Content-Disposition header field, MUST NOT be used.
it could be easyly realesed:
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(0, new FormHttpMessageConverter() {
#Override
protected String getFilename(Object part) {
if (part instanceof Resource) {
Resource resource = (Resource) part;
try {
return URLEncoder.encode(resource.getFilename(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
});
Most likely the file encoding's system property of the used JVM hasn't been explicitly set, meanwhile the operating system where JVM runs is not using UTF-8 as the default charset. For instance, if JVM runs on Windows, and we don't specify the charset, the default value will be Windows-1252 instead.
Could you double check the JVM arguments of both applications that send and receive the file? Please ensure that it has -Dfile.encoding=UTF-8 argument before specifying the main class name.
Please also ensure that the application/service which receives the file has been configured to accept UTF-8 charset.
Feel free to also check the other possible related answers, if adding the file.encoding argument on JVMs doesn't help solving the problem,
How to get UTF-8 working in Java webapps?
Spring MVC UTF-8
Encoding

java api to get a file content for enterprise github

I tried so hard for a simple line of code that read a file content from enterprise github with oauth token, but could not find a example of such.
I tried https://github.com/jcabi/jcabi-github, but it does not support enterprise github?(maybe I am wrong)
Now i am trying egit:
GitHubClient client = new GitHubClient("enterprise url");
GitHubRequest request = new GitHubRequest();
request.setUri("/readme");
GitHubResponse response = client.get(request);
Then what? I only saw a getBody, maybe I need to parse it with some kinda json library? It has to be simpler..I am expecting something like: repo.get(url).getContent()
Finally figure out by reading source code..
GitHubClient client = new GitHubClient(YOURENTERPRICEURL);
client.setOAuth2Token(token);
// first use token service
RepositoryService repoService = new RepositoryService(client);
try {
Repository repo = repoService.getRepository(USER, REPONAME);
// now contents service
ContentsService contentService = new ContentsService(client);
List<RepositoryContents> test = contentService.getContents(repo, YOURFILENAME);
List<RepositoryContents> contentList = contentService.getContents(repo);
for(RepositoryContents content : test){
String fileConent = content.getContent();
String valueDecoded= new String(Base64.decodeBase64(fileConent.getBytes() ));
System.out.println(valueDecoded);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}