I have created a PDF from a word document using POI4XPages api.
here is the code:
var template = poiBean.buildResourceTemplateSource(null,"purchaseorder.docx");
var result = poiBean.processDocument2Stream(template, lst);
var is:java.io.InputStream = new java.io.ByteArrayInputStream(result.toByteArray());
var os:java.io.OutputStream = poiBean.buildPDFFromDocX(is)
As you can see the result of my code is an OutputStream, The next step for me is to convert the stream to an attachment and attach it to a notesdocument but don't know how to do that. It doesn't really matter if I first need to attach it to disc or if it written to a body field immediately.
The poiBean is described here
https://github.com/OpenNTF/POI4Xpages/blob/master/biz.webgate.dominoext.poi/src/biz/webgate/dominoext/poi/beans/PoiBean.java
I am using SSJS here but I guess a java solution would work as well.
thanks
Thomas
Some copying and pasting but this is how you stream it into an richtext field but you need to convert os to an inputstream and assign this to a variable called is2
var stream:NotesStream = session.createStream();
session.setConvertMIME(false);
var doc:NotesDocument = database.createDocument();
var body:NotesMIMEEntity = doc.createMIMEEntity();
stream.setContents(is2); // is an inputstream
body.setContentFromBytes(stream, "application/octet-stream",NotesMIMEEntity.ENC_IDENTITY_BINARY);
stream.close();
doc.save(true, true);
session.setConvertMIME(true);
This is what I based the example on
https://openntf.org/XSnippets.nsf/snippet.xsp?id=create-html-mails-in-ssjs-using-mime
Related
what's the equivalent fileoutputstream of java in dart?
Java code
file = new FileOutputStream(logFile, true);
byte[] input = "String".getBytes();
file.write(input);
java file output
String
Ive tried this in dart
Dart code
var file = File(logFile!.path).openWrite();
List input = "String".codeUnits;
file.write(input);
[String]
and every time I open the file again to append "String2" and "String3" to it, the output will be
[String][String2][String3]
as oppose to java's output
StringString3String3
to sum it up, is there a way to fix/workaround this?
why each array bytes written in dart will be a new array instead of append into an existing one?
You can achieve that by using File.writeAsString() and using FileMode.append.
Picking up your example, this would be:
var file = File(logFile!.path);
file.writeAsString("String", mode: FileMode.append);
did you try writeAsString() ?
import 'dart:io';
void main() async {
final filename = 'file.txt';
var file = await File(filename).writeAsString('some content');
// Do something with the file.
}
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!
Can any one tell me how to decode a base64 encoded image in classic ASP? The image is encoded by Java org.apache base64 class. The Java uses RFC 2045 for base64 decoding.
<%
Set objXML = Server.CreateObject("MSXml2.DOMDocument")
Set objDocElem = objXML.createElement("Base64Data")
objDocElem.DataType = "bin.base64"
objDocElem.text = "/9j/4AAQSkZJRgABAQEBLAEsAAD/2wBDAAUD" 'encodedString
'Save to disk
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Type = 1
objStream.Open
objStream.Write objDocElem.NodeTypedValue
objStream.SaveToFile "abc.jpg", 2
set objStream = Nothing
'Or send to browser
Response.ContentType = "image/jpeg"
Response.AddHeader "Content-Disposition", "attachment; filename=abc.jpg";
Response.BinaryWrite objDocElem.NodeTypedValue
Set objXML = Nothing
Set objDocElem = Nothing
%>
You can use the Capicom COM object. I've been using it to to the reverse (base64 encoding).
This is what I would do (if you've got a big loop, you'd better have the CreateObject done outside the loop, but in simple cases this should do it):
Function Base64Decode(encodedString)
Dim caputil : Set caputil = CreateObject("CAPICOM.Utilities")
If len(encodedString) > 0 Then
Base64Decode = caputil.Base64Decode(encodedString)
Else
Base64Decode = ""
End If
Set caputil = Nothing
End Property
Reference : http://msdn.microsoft.com/en-us/library/aa388176(v=vs.85).aspx
By the way, capicom.dll can be downloaded from MS site : http://www.microsoft.com/downloads/en/details.aspx?FamilyID=860ee43a-a843-462f-abb5-ff88ea5896f6
I'm starting to design an application, that will, in part, run through a directory of files and compare their extensions to their file headers.
Does anyone have any advice as to the best way to approach this? I know I could simply have a lookup table that will contain the file's header signature. e.g., JPEG: \xFF\xD8\xFF\xE0
I was hoping there might be a simper way.
Thanks in advance for your help.
I'm afraid it'll have to be more complicated than that. Not every file type has a header at all, and some (such as RAR) have their characteristic data structures at the end rather than at the beginning.
You may want to take a look at the Unix file command, which does the same job:
http://linux.die.net/man/1/file
http://linux.die.net/man/5/magic
If you don't need to do dirty work on these values (and you don't have linux) you could simply use an external program, like TrID, that is able to do this thing for you.
Maybe you can just work on its output without caring to doing it by yourself.. in anycase if you have just around 20 kinds of files that you will have to manage having a simple lookup table (eg. HashMap<String,byte[]>) is not that bad. Of cours this will work only if desidered file format has a magic number, otherwise you are on your own (or with an external program).
Because of the problem with the missing significant header for some file types (thanks #Michael) I would create a map of extension to a kind of type checker with a simple API like
public interface TypeCheck throws IOException {
public boolean isValid(InputStream data);
}
Now you can code something like
File toBeTested = ...;
Map<String,TypeCheck> typeCheckByExtension = ...;
TypeCheck check = typeCheckByExtension.get(getExtension(toBeTested.getName()));
if (check != null) {
InputStream in = new FileInputStream(toBeTested);
if (check.isValid(in)) {
// process valid file
} else {
// process invalid file
}
in.close();
} else {
// process unknown file
}
The Header check for JPEG for example may look like
public class JpegTypeCheck implements TypeCheck {
private static final byte[] HEADER = new byte[] {0xFF, 0xD8, 0xFF, 0xE0};
public boolean isValid(InputStream data) throws IOException {
byte[] header = new byte[4];
return data.read(header) == 4 && Arrays.equals(header, HEADER);
}
}
For other types with no significant header you can implement completly other type checks.
You can extract the mime type for each file and compare this to a map of mimetype/extension (Map<String, List<String>>, the first String is the mime type, the second is a list of valid extensions).
Resources :
Get the Mime Type from a File
JMimeMagic
On the same topic :
Java - HowTo extract MimeType from a byte[]
Getting A File's Mime Type In Java
You can know the file type of file reading the header using apache tika. Following code need apache tika jar.
InputStream is = MainApp.class.getResourceAsStream("/NetFx20SP1_x64.txt");
BufferedInputStream bis = new BufferedInputStream(is);
AutoDetectParser parser = new AutoDetectParser();
Detector detector = parser.getDetector();
Metadata md = new Metadata();
md.add(Metadata.RESOURCE_NAME_KEY,MainApp.class.getResource("/NetFx20SP1_x64.txt").getPath());
MediaType mediaType = detector.detect(bis, md);
System.out.println("MIMe Type of File : " + mediaType.toString());