How to parse multi-part form data in wicket - java

When my page gets hit from a third party page, I get the below data in request payload:
Content-type: multipart/form-data, boundary----------14048
Content-Length = 590
----------14048
Content-disposition: form-data; name ="xyz"
{"abc":"lmn","def":"ghi"}
----------14048
I need to read the JSON string from this parameter in my Java class. How can I do that?
My current code looks like this:
IRequestParameters requestParameters = getRequest().getPostParameters();
if (requestParameters != null && requestParameters.getParameterNames().contains( "abc" )&&requestParameters.getParameterValue( "abc" ) != null){
  value = requestParameters.getParameterValue( "abc" ).toString();
}
Thanks in advance.

First, you need to parse multipart form data in Wicket:
MultipartServletWebRequest multiPartRequest =
webRequest.newMultipartWebRequest(getMaxSize(), "ignored");
// multiPartRequest.parseFileParts(); // this is needed after Wicket 6.19.0+
IRequestParameters params = multiPartRequest.getRequestParameters();
Then you need to parse the JSON fragment, one way to do that is by using org.json.
import org.json.*;
JSONObject jsondict = new JSONObject(params.getParameter("xyz");
Then you need to get the JSON parameter you are interested in:
string payload = jsondict.getString("abc");

The below code works fine for me.
HttpSevletRequest request = (HttpSevletRequest )getRequest.getContainerRequest();
try{
InputStreamReader inputReader = new InputStreamReader(request.getInputStream());
BufferedReader reader = new BufferedReader(inputReader );
for(String line;(line = reader.readLine())!=null;){
if(line.contains("abc")){
//perform task....
}
}
}catch(IOException e){
//logs
}

Related

German/Special character support in form data rest web service

I am currently developing small project in Angular JS + Java, where user is registering his information with his profile picture using rest webservice. Everything is working fine, except in case of special character(Ä Ö Ü ä ö).
Java :
#POST
#Path("add_employee")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.APPLICATION_JSON)
public Response addEmployee(MultipartFormDataInput input) {
try {
Map<String, List<InputPart>> formDataMap = input.getFormDataMap();
if (formDataMap != null && !formDataMap.isEmpty()) {
InputPart inputPart = formDataMap.get("EmployeeProxy").get(0);
ObjectMapper mapper = new ObjectMapper();
//receiving wrong json below=>
EmployeeProxy admbo = mapper.readValue(inputPart.getBodyAsString(), EmployeeProxy.class);
List<InputPart> profilePic = formDataMap.get("profilePic");
.
.
.
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (Exception ex) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
Angular JS :
var fd = new FormData();
fd.append('EmployeeProxy', angular.copy(JSON.stringify($scope.empInfo)));
fd.append('profilePic', $scope.myFile);
$http.post(Server.url + 'add_employee', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function (response) {
});
Sending Json : {"empName": "Ä Ö Ü ä ö","empSurname": "XYZ","emailId":
"abc#gmail.com"}
Receiving Json : {"empName": "�� �� �� �� �� ��","empSurname":
"XYZ","emailId": "abc#gmail.com"}
Please find below image for request header information :
This is working fine, if I am using APPLICATION_JSON without MULTIPART_FORM_DATA.
If your Content-Type header is undefined, RestEasy cannot identify the charset to use and will fallback to a default (us-ascii).
See also:Overwriting the default fallback content type for multipart messages
Edit after reading up on this: It should be the multipart body which specifies the Content-Type in order for RestEasy to parse the individual strings.
In the documentation of FormData it can be done in the following way:
Angular JS :
fd.append('EmployeeProxy', new Blob([angular.copy(JSON.stringify($scope.empInfo))], { type: "text/plain; charset=iso-8859-1"}));
Java :
String json = IOUtils.toString(inputPart.getBody(InputStream.class, null), StandardCharsets.UTF_8);
EmployeeProxy admbo = mapper.readValue(json, EmployeeProxy.class);

Generate ImapMessage from Response Object

I've created a custom command to retrieve multiple objects in the same request (in order to solve some performance issues), instead of using the folder method .getMessage(..) which in my case retrieved an ImapMessage object:
Argument args = new Argument();
args.writeString(Integer.toString(start) + ":" + Integer.toString(end));
args.writeString("BODY[]");
FetchResponse fetch;
BODY body;
MimeMessage mm;
ByteArrayInputStream is = null;
Response[] r = protocol.command("FETCH", args);
Response status = r[r.length-1];
if(status.isOK()) {
for (int i = 0; i < r.length - 1; i++) {
...
}
}
Currently I'm validating if the object is a ImapResponse like this:
if (r[i] instanceof IMAPResponse) {
IMAPResponse imr = (IMAPResponse)r[i];
My question is, how can I turn this response into an ImapMessage?
Thank you.
Are you trying to download the entire message content for multiple messages at once? Have you tried using IMAPFolder.FetchProfileItem.MESSAGE? That will cause Folder.fetch to download the entire message content, which you can then access using the Message objects.
I haven't succeeded yet to convert it into a IMAPMessage but I'm now able transform it into a MIME Message. It isn't perfect but I guess it will have to work for now:
FetchResponse fetch = (FetchResponse) r[i];
BODY body = (BODY) fetch.getItem(0);
ByteArrayInputStream is = body.getByteArrayInputStream();
MimeMessage mm = new MimeMessage(session, is);
Then, it can be used to get information like this:
String contentType = mm.getContentType();
Object contentObject = mm.getContent();
There are also other methods to get information like the sender, date, etc.

Http response through service sends content (mime) type in text/html but not application/json

My application using Oauth for basecam api. I am trying to get Httpresponse into json format but it revert into plain html (text/html) content-type. so there is no method to parse HTML content and get the token from basecamp. This is not homework but a small R&D to quick start Oauth protocol. as am new to oauth.
//HERE -> final String JSON_CONTENT = "application/json"
String contentType = OAuthConstants.JSON_CONTENT;
if (response.getEntity().getContentType() != null) {
contentType = response.getEntity().getContentType().getValue();
//BELOW -> getting contentType is in "text/html; utf-8
System.out.println(response.getEntity().getContentType().getValue()); //text/html; charset=utf-8
}
if (contentType.contains(OAuthConstants.JSON_CONTENT)) {
return handleJsonResponse(response);
} else
if (contentType.contains(OAuthConstants.URL_ENCODED_CONTENT)) {
return handleURLEncodedResponse(response);
} else
if (contentType.contains(OAuthConstants.XML_CONTENT)) {
return handleXMLResponse(response);
}
else {
// Unsupported Content type
throw new RuntimeException(
"Cannot handle "
+ contentType
+ " content type. Supported content types include JSON, XML and URLEncoded");
}
So above lines explain very well that control won't come is json, xml or url_encoded if-else. Si either i need to parse text/html into json or xml response or i have to create another method name handleHtmlResponse(). what way it would be continent to get contentType.
After the response is set with all the data(header, body ...), commit it by calling ServletResponse#flushBuffer.

JSON: Create a web page with JSON data

Firstly, I am extremely new to JSON. I have been reading as much as I can on it. While I get the concept, implementing it is a different deal altogether for me.
So, I have an app which reads and displays data from JSON web pages. For instance, I can extract the time that is being shown in this website: http://date.jsontest.com/
Using the HTML from this website, I added the JSON Object to my HTML page in the following manner:
<html>
<body>
<pre>
{
"score": "30-20"
}
</pre>
</body>
</html>
However, the app now throws a JSON exception everytime I try to retreive the score.
My question is, 'Is adding a JSON Object to the pre tag in an HTML page the correct way of creating a JSON Object on a web page?'
If not, what is the correct way to do it?
EDIT: This is is the code I am using in java to retrieve the JSON data:
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if(status==200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
//JSONArray timeline = new JSONArray(0);
JSONObject last = new JSONObject(data);
return last;
}
else{
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
return null;
}
The try statement:
try {
json = lastTweet();
return json.getString("time");
//return "Oh Well";
}
Thanks.
Your application should send the Content-type: application/json header and should only output the string representation of the data itself, so that your entire page is just:
{
"score": "30-20"
}
and nothing more. The example that you gave follows the same procedure if you check the response headers and view the source code of that page.
The reason your parser is failing is because the page starts with <, when the first non-whitespace character should be {.
Use something like this:
response.setContentType("application/json");
PrintWriter out = response.getWriter();
String json = "{\"data\": \"test\"}";
out.print(json);
out.flush();
on your dataserver

Attachment Id of emails in java

I am currently working with java mail api . I need to list the attachment details also wants remove the attachment from some emails and forward it to others. So i'm trying to find out the Attachment ID. How can i do it? Any suggestion will be appreciate!!!
Does this help?
private void getAttachments(Part p, File inputFolder, List<String> fileNames) throws Exception{
String disp = p.getDisposition();
if (!p.isMimeType("multipart/*") ) {
if (disp == null || (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE)))) {
String fileName = p.getFileName();
File opFile = new File(inputFolder, fileName);
((MimeBodyPart) p).saveFile(opFile);
fileNames.add(fileName);
}
}
}else{
Multipart mp = (Multipart) p.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++){
getAttachments(mp.getBodyPart(i),inputFolder, fileNames);
}
}
}
There ain't anything as an attachment ID. What your mail client displays as a message with attached contents, is really a MIME Multipart and looks like this (sample source):
From: John Doe <example#example.com>
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="XXXXboundary text"
This is a multipart message in MIME format.
--XXXXboundary text
Content-Type: text/plain
this is the body text
--XXXXboundary text
Content-Type: text/plain;
Content-Disposition: attachment; filename="test.txt"
this is the attachment text
--XXXXboundary text--
Important things to note:
Every part in a multipart has a Content-Type
Optionally, there can be a Content-Disposition header
Single parts can be themselves multipart
Note that there is indeed a Content-ID header, but I don't think it's what you are looking for: for example, it is used in multipart/related messages to embed image/*s and text from a text/html in the same email message. You have to understand how it works and if it's used in your input.
I think your best option is to examine the Content-Disposition and the Content-Type header. The rest is guesswork, and without actual requirement one can't help with the code.
Try using the Apache Commons Email package which has a MimeMessageParser class. With the parser you can get the content id (which could be used to identify the attachment) and attachments from the email message like so:
Session session = Session.getInstance(new Properties());
ByteArrayInputStream is = new ByteArrayInputStream(rawEmail.getBytes());
MimeMessage message = new MimeMessage(session, is);
MimeMessageParser parser = new MimeMessageParser(message);
// Once you have the parser, get the content ids and attachments:
List<DataSource> attachments = parser.getContentIds.stream
.map(id -> parser.findAttachmentByCid(id))
.filter(att -> att != null)
.collect(Collectors.toList());
I have created a list here for the sake of brevity, but instead, you could create a map with the contentId as the key and the DataSource as the value.
Take a look at some more examples for using the parser in java here, or some code I wrote for a scala project here.

Categories