I'm populating a dropdown listbox in jsp with strings with characters like \u00e8. I will use the selected value of the dropdown to filter the display in a table with values retrieved from DB. However, when I send them back to servlet via request.getAttribute, its value changed. I used org.apache.commons.lang.StringEscapeUtils.escapeJava() and found that its value changed from \u00e8 to \u00C3\u00A8. The content type of the webpage is UTF-8. How can I have consistent characters for HTML and Java?
Sorry if I cannot put comments, accept answer, vote for comments as javascript in my workstation is disabled (which really sucks). I'll do them once I get home. Thanks.
This is what I did on my Multi-part file upload.
List formItems = upload.parseRequest(request);
Iterator iter = formItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
String field = "";
String value = "";
if (item.isFormField()) {
try{
field=item.getFieldName();
value=item.getString("UTF-16");
}
catch(Exception e){
}
}
Related
I have an html form to submit like this:
<form enctype="multipart/form-data" id="formToSubmit" action="/create_components" method="POST">
<input type="file" name="component_1" id="component_1">
Other inputs here...
On the server side, I wanna get all the inputs (both files and text inputs)... and the form is dynamically created so I don't know in advance the name of the IDs.
On the server I need both content and IDs.
On the server I first tried to loop on the parameters, but this skip the inputs that are of type file and return only the text ones:
Enumeration<?> enums = request.getParameterNames();
while (enums.hasMoreElements()) {
Object inputName = enums.nextElement();
// Here I get all the input that are not files
}
Then I tried in that way:
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Set set = multipartRequest.getFileMap().entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
String fileName = (String)me.getKey();
MultipartFile multipartFile = (MultipartFile)me.getValue();
byte[] bytes = multipartFile.getBytes();
}
In this way I actually get the files, but I don't know how to get their IDs.
I need both: the file content and the ID (in this example "component_1"). How can I do that? Is there a way I can change the last code in order to get also the ID?
You have the name of file by calling to:
String valueOfNameAttribute = ((MultipartFile)me.getValue()).getName()
Isn't that what you need?
I am trying to get the font size of acroField of a pdf version 1.7.
I am using this code to get font size of AcroField of PDF.
But pdf Dictionary does not contains the key (PdfName.DA).
When I am accesing pdfObject from PdfDictionary for PdfName.DA, I am getting null.
My code is
final AcroFields.Item item = acroFields.getFieldItem(fieldName);
ArrayList list =null;
list = item.merged;
if (list != null)
{
for (final Iterator it1 = list.iterator(); it1.hasNext();)
{
final PdfDictionary itemDict = (PdfDictionary) it1.next();
final PdfObject da = itemDict.get(PdfName.DA);
System.out.println(da); //da coming null.
}
}
I am using jar "itext-2.1.7.jar"
Above code works fine for PDF With version 1.6.But it is not working well for version 1.7 of PDF.
The link for the PDF is "http://www.mediafire.com/view/riuajytszavbq77/JanWebinar013014.pdf"
Why do you think the "DA" key should be there? The PDF specification clearly states that the DA key is in the "Additional entries common to all fields containing variable text". The fields in your PDF file doen't appear to have variable text (text entered by the user for example).
As such the "DA" key is optional and you should be prepared to accept it isn't there.
I have a multipart/form-data form that contains a file upload section and other fields such as checkboxes. I would like to create a string based on the information from checkboxes, delimitered with ";" in order to send it to the database.
My UploadServlet looks like this:
try {
// parses the request's content to extract file data
List formItems = upload.parseRequest(request);
Iterator iter = formItems.iterator();
// iterates over form's fields
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// processes only fields that are not form fields
if (!item.isFormField()) {
//doSomething
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
}
else
{
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
// Do anotherThing
// Can I create a string from the checkbox inputs here?
}
Thanks!
You need to collect multiple fields with the same name yourself. Assuming that the input field name of those checkboxes is checkboxName, here's a kickoff example:
List<String> checkboxValues = new ArrayList<String>();
// ... while looping over all items.
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
if ("checkboxName".equals(fieldname)) {
checkboxValues.add(fieldvalue);
}
// ... after looping over all items.
StringBuilder builder = new StringBuilder();
for (String checkboxValue : checkboxValues) {
if (builder.length() > 0) builder.append(";");
builder.append(checkboxValue);
}
String semicolonSeparatedCheckboxValues = builder.toString();
// Save in DB. By the way, why not just using a separate table with a FK?
// Storing multiple values delimited in a single DB column is a bad practice.
For Apache Commons FileUpload, there will always be one item for every HTML element in the multipart form that you submitted.
So if you have multiple checkboxes with the same name, you will get multiple items with the same field names. In other words, for many checkboxes, you will find many items with the same field name, but with different value.
I have a 'small' problem. In a database documents contain a richtextfield. The richtextfield contains a profile picture of a certain contact. The problem is that this content is not saved as mime and therefore I can not calculate the url of the image.
I'm using a pojo to retrieve data from the person profile and use this in my xpage control to display its contents. I need to build a convert agent which takes the content of the richtextitem and converts it to mime to be able to calculate the url something like
http://host/database.nsf/($users)/D40FE4181F2B86CCC12579AB0047BD22/Photo/M2?OpenElement
Could someone help me with converting the contents of the richtextitem to mime? When I check for embedded objects in the rt field there are none. When I get the content of the field as stream and save it to a new richtext field using the following code. But the new field is not created somehow.
System.out.println("check if document contains a field with name "+fieldName);
if(!doc.hasItem(fieldName)){
throw new PictureConvertException("Could not locate richtextitem with name"+fieldName);
}
RichTextItem pictureField = (RichTextItem) doc.getFirstItem(fieldName);
System.out.println("Its a richtextfield..");
System.out.println("Copy field to backup field");
if(doc.hasItem("old_"+fieldName)){
doc.removeItem("old_"+fieldName);
}
pictureField.copyItemToDocument(doc, "old_"+fieldName);
// Vector embeddedPictures = pictureField.getEmbeddedObjects();
// System.out.println(doc.hasEmbedded());
// System.out.println("Retrieved embedded objects");
// if(embeddedPictures.isEmpty()){
// throw new PictureConvertException("No embedded objects could be found.");
// }
//
// EmbeddedObject photo = (EmbeddedObject) embeddedPictures.get(0);
System.out.println("Create inputstream");
//s.setConvertMime(false);
InputStream iStream = pictureField.getInputStream();
System.out.println("Create notesstream");
Stream nStream = s.createStream();
nStream.setContents(iStream);
System.out.println("Create mime entity");
MIMEEntity mEntity = doc.createMIMEEntity("PictureTest");
MIMEHeader cdheader = mEntity.createHeader("Content-Disposition");
System.out.println("Set header withfilename picture.gif");
cdheader.setHeaderVal("attachment;filename=picture.gif");
System.out.println("Setcontent type header");
MIMEHeader cidheader = mEntity.createHeader("Content-ID");
cidheader.setHeaderVal("picture.gif");
System.out.println("Set content from stream");
mEntity.setContentFromBytes(nStream, "application/gif", mEntity.ENC_IDENTITY_BINARY);
System.out.println("Save document..");
doc.save();
//s.setConvertMime(true);
System.out.println("Done");
// Clean up if we are done..
//doc.removeItem(fieldName);
Its been a little while now and I didn't go down the route of converting existing data to mime. I could not get it to work and after some more research it seemed to be unnecessary. Because the issue is about displaying images bound to a richtextbox I did some research on how to compute the url for an image and I came up with the following lines of code:
function getImageURL(doc:NotesDocument, strRTItem,strFileType){
if(doc!=null && !"".equals(strRTItem)){
var rtItem = doc.getFirstItem(strRTItem);
if(rtItem!=null){
var personelDB = doc.getParentDatabase();
var dbURL = getDBUrl(personelDB);
var imageURL:java.lang.StringBuffer = new java.lang.StringBuffer(dbURL);
if("file".equals(strFileType)){
var embeddedObjects:java.util.Vector = rtItem.getEmbeddedObjects();
if(!embeddedObjects.isEmpty()){
var file:NotesEmbeddedObject = embeddedObjects.get(0);
imageURL.append("(lookupView)\\");
imageURL.append(doc.getUniversalID());
imageURL.append("\\$File\\");
imageURL.append(file.getName());
imageURL.append("?Open");
}
}else{
imageURL.append(doc.getUniversalID());
imageURL.append("/"+strRTItem+"/");
if(rtItem instanceof lotus.domino.local.RichTextItem){
imageURL.append("0.C4?OpenElement");
}else{
imageURL.append("M2?OpenElement");
}
}
return imageURL.toString()
}
}
}
It will check if a given RT field is present. If this is the case it assumes a few things:
If there are files in the rtfield the first file is the picture to display
else it will create a specified url if the item is of type Rt otherwhise it will assume it is a mime entity and will generate another url.
Not sure if this is an answer but I can't seem to add comments yet. Have you verified that there is something in your stream?
if (stream.getBytes() != 0) {
The issue cannot be resolved "ideally" in Java.
1) if you convert to MIME, you screw up the original Notes rich text. MIME allows only for sad approximation of original content; this might or might not matter.
If it matters, it's possible to convert a copy of the original field to MIME used only for display purposes, or scrape it out using DXL and storing separately - however this approach again means an issue of synchronization every time somebody changes the image in the original RT item.
2) computing URL as per OP code in the accepted self-answer is not possible in general as the constant 0.C4 in this example relates to the offset of the image in binary data of the RT item. Meaning any other design of rich text field, manually entered images, created by different version of Notes - all influence the offset.
3) the url can be computed correctly only by using C API that allows to investigate binary data in rich text item. This cannot be done from Java. IMO (without building JNI bridges etc)
I'm using Java. This is the pure data that gets inserted in the datastore:
<p>Something</p>\n<p>That</p>\n<p> </p>\n<p>Should.</p>\n<p> </p>\n
<p>I have an interesting question.</p>\n<p>Why are you like this?</p>\n
<p> </p>\n<p>Aren't you fine?</p>
This is how it gets stored:
<p>Something</p> <p>That</p> <p>�</p> <p>Should.</p> <p>�</p>
<p>I have an interesting question.</p> <p>Why are you like this?</p>
<p>�</p> <p>Aren't you fine?</p>
What's up with the weird symbols? This happens only live, not on my local dev_appserver.
EDIT
Here's the code that inserts the data:
String content = ""; // this is where the data is stored
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
while(iter.hasNext()) {
FileItemStream item = iter.next();
InputStream stream = item.openStream();
if(item.isFormField()) {
String fieldName = item.getFieldName();
String fieldValue = new String(IOUtils.toByteArray(stream), "utf-8");
LOG.info("Got a form field: " +fieldName+" with value: "+fieldValue);
// assigning the value
if(fieldName.equals("content")) content = fieldValue;
} else {
...
}
}
} catch (FileUploadException e){
}
...
// insert it in datastore
Recipe recipe = new Recipe(user.getKey(), title, new Text(content), new Text(ingredients), tagsAsStrings);
pm.makePersistent(recipe);
It's a multipart/form-data form so I have to do that little item.isFormField() magic to get the actual content, and construct a String. Maybe that's causing the weird encoding issue? Not sure.
To retrieve the data I simply do:
<%=recipe.getContent().getValue()%>
Since content is of type Text (app engine type) I use the .getValue() to get the actual result. I don't think it's an issue with retrieving the data, since I can see the weird characters directly in the online app-engine datastore viewer.
Are you using eclipse ? if yes check under File > Properties > Text File encoding that your file is UTF-8 encoding.
I would guess not.
So, change it to UTF-8 and your issue should get fixed.
regards
didier
Followed this page to create a Servlet Filter so that all my pages were being encoded in utf8:
How to get UTF-8 working in Java webapps?
After creating the filter, everything works!