I am trying to upload jar file using zk(5.0.5). While uploading i have checked its format (extension) for that I have used getFormat() API of the Media (org.zkoss.util.media.Media).
code:
browsebtn.addEventListener("onUpload",new EventListener() {
public void onEvent(Event event) throws Exception {
private Media uploadedMedia;
uploadEvent=(UploadEvent) event;
uploadedMedia=uploadEvent.getMedia();
if(uploadedMedia!=null){
String fileName=uploadedMedia.getName();
fileFormat=uploadedMedia.getFormat();
System.out.println("File Format Name"+fileFormat);
}
}
});
Problem is that for internet explorer i get format as zip , for chrome and Firefox i get its format as octet-stream . Why there is such mismatching for different browsers . How to solve this problem ?(I dont want to any hard coding such as browser check)
You can try with;
LobData data = ZkUtils.media2LobData(uploadedMedia);
Then use that data:
data.getFormat();
I think the best way is to check the mime type to get the type, format, extension... of your file and to prevent some security attacks, for example you can use this :
File f = new File("test.pdf");
System.out.println("Mime Type of " + f.getName() + " is " +
new MimetypesFileTypeMap().getContentType(f));
// "Mime Type of test.pdf is application/pdf"
You can find here the list of the most popular mime types.
Hope this helps.
Related
I need to write a Java program to extract all attachments from messages saved by Outlook 2016 in the native msg format. The program should skip inline images. Also some of the mails have multipart/alternative parts where the program should retrieve the "best" content-type, e.g. text/html over text/plain.
In order to do that, I need to find out the content-type and content-disposition of all parts and attachments of the message.
I tried the following:
public static void main(String[] args) throws IOException {
String mfile = "test/test2.msg";
MAPIMessage msg = new MAPIMessage(mfile);
AttachmentChunks[] attachments = msg.getAttachmentFiles();
if (attachments.length > 0) {
for (AttachmentChunks attachment : attachments) {
System.out.println("long file name = " + attachment.getAttachLongFileName());
System.out.println("content id = " + attachment.getAttachContentId());
System.out.println("mime tag = " + attachment.getAttachMimeTag());
System.out.println("embedded = " + attachment.isEmbeddedMessage());
}
}
msg.close();
}
The problem is, that the "mime tag" (i.e. the content-type) is returned only for some attachments and returns null for all others. The content-disposition seems to be totally missing.
For example, I get the following output on a mail saved by OL2016 (the mail contains a PDF attachment and an inline logo image):
long file name = Vertretungsvollmacht Übersiedlung.pdf
content id = null
mime tag = null
embedded = false
long file name = image001.jpg
content id = image001.jpg#01D2E697.12EC9370
mime tag = image/jpeg
embedded = false
Is there a way to get these attributes out of the msg files or is there a more complete & convenient way to achieve what I want in Java with some other library than Apache POI-HSMF?
In order to get the content-disposition (inline or attachment), I did the following:
String disposition = "attachment";
if (contentId != "")
if (body.contains(contentId.toString()))
disposition = "inline";
To obtain the content-type, I have derived it from the file extension of the attachment, e.g.:
String ext = fileNameOri.substring(fileNameOri.lastIndexOf(".") + 1);
switch (ext.toLowerCase()) {
case "xlsx":
ct = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
break;
}
A list of mime types can be obtained from e.g. https://wiki.selfhtml.org/wiki/MIME-Type/%C3%9Cbersicht
Of course, this should only be done in case AttachmentChunks.getAttachMimeTag() returns an empty string.
The fact that an attachment has a content-id tag does not mean it is an embedded image - Lotus Notes adds content-id to all attachments. The only valid check is to load the HTML body and figure out what the <img> tags refer to.
Currently I am making a program (in Java) that grabs all the streamers on twitch (Videogame streaming site) from a given URL e.g. and lists them into a text file using Jsoup.
However, no matter what I try, it seems like I can't get the streamer's names. After a while I discovered that the page source for some reason does not contain the streamer's names which I think could be the problem?
Here is my code currently.
public static void main(String[] args) throws IOException {
int i = 0;
PrintWriter streamerwriter = new PrintWriter("streamer.txt", "UTF-8");
Document doc = Jsoup.connect(https://www.twitch.tv/directory/game/Hearthstone%3A%20Heroes%20of%20Warcraft).get();
Elements streamers = doc.getElementsByClass("js-profile-link");
for (Element streamer : streamers) {
i++;
System.out.println(i + "." + streamer.text());
streamerwriter.println(i + "." + streamer.text());
}
streamerwriter.close();
}
Any help would be greatly appreciated.
you don't need to parse webpage.Because twitch has an api to select streamers.
https://streams.twitch.tv/kraken/streams?limit=20&offset=0&game=Hearthstone%3A+Heroes+of+Warcraft&broadcaster_language=&on_site=1
so you should parse json data
if you want to know why you don't see streamers in jsoup because of lazy loading.because that part you want to parse is loaded lazily.You should know that lazy request and parse that url by jsoup which i found and wrote up.(twitch api)
Please check this question out:
how to use Jsoup in site that has lazyload scrollLoader.js
I am doing a conversion from docx to pdf format. I successfully did the variable replacement and have a WordprocessingMLPackage template.
I have tried both approches. The old deprcated version of converting to pdf and the newer method. Both fails giving this exception error
Don't know how to handle "application/pdf" as an output format.
Neither an FOEventHandler, nor a Renderer could be found for this
output format. Error: UnsupportedOpertaionException
I have tried everything I can. This thing works on my local machine but now at my workplace. I think I have all the necessary jars. Can u please instruct what course of action should I take.
Code :
Method 1:
Docx4J.toPDF(template, new FileOutputStream("newPdf.pdf"));
Method 2:
public static void createPDF(WordprocessingMLPackage template, String outputPath) {
try {
// 2) Prepare Pdf settings
PdfSettings pdfSettings = new PdfSettings();
// 3) Convert WordprocessingMLPackage to Pdf
OutputStream out = new FileOutputStream(new File(
outputPath));
PdfConversion converter = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(
template);
converter.output(out, pdfSettings);
} catch (Throwable e) {
e.printStackTrace();
}
}
Both are giving the same error. Any help is appreciated!
My issue is resolved. The problem was that the required fop-1.1.jar was there on my eclipse classpath but it was not there on the local server classpath. I added them there and it worked like a charm.
I am hoping that someone can help me here. I am using the yCad library to read a number of dxf files and output a composite model, to dxf format.
The initial process of reading the file is complete. However, when I save the file it is saved without the model.
Here is an example of the code used to save the dxf file
public static boolean SaveDxf(String outputPath, String fileName, Yxxf model)
{
try
{
model.iohandler = new YutilIOHandler();
model.ioname = new YutilIOHandlerName(fileName);
model.ioname.dstfile = outputPath + "\\" + fileName + ".dxf";
YdxfPutHandler handler = new YdxfPutHandler();
handler.commandPutMainStart(model.iohandler, model);
return true;
}
catch(Exception ex)
{
System.out.println("failed to save dxf file: " + ex.getMessage());
return false;
}
}
When the file is viewed from an editor an error is reported stating the model is empty.
The error occurs even when a dxf file is read and then saved with no manipulation.
I have resolved this issue.
The resolution required a modification to the version of the YCad library that I was using due the following selection.
if (ent instanceof YxxfEntLine)
{
YdxfPutEntLine.put(putbfr, (YxxfEntLine)ent);
}
NOTE: This may have been due to an out of date version of the library.
The method was modified to include all required types.
else if(ent instanceof YxxfEntPolyline)
{
YdxfPutPolyline.put(putbfr, (YxxfEntPolyline)ent);
}
A number of new classes were added to the solution.
When I get time I will see if I can submit these modification to the source library, if they are required.
Is there a built in way to get all of the media files (movies , music) on a computer in java?
No, not build in. But, you could create a crawler that scans your entire hard drive for files with certain extensions ( or even better, MIME types ).
Check out this answer for an easy way to iterate through directories: https://stackoverflow.com/a/3154523/691606
See also Get the Mime Type from a File. Based on 1st 2 (of 3) techniques shown therein, is this:
import javax.activation.MimetypesFileTypeMap;
import java.io.File;
class MimeForMedia {
public static void main(String[] args) {
String[] types = {
"png", "jpg", "gif", "tif", "bmp", // image
"snd", "wav", "mp3", "ogg", "au", // sound
"mov", "avi", "mpg", "flv" // video
};
MimetypesFileTypeMap typeMap = new MimetypesFileTypeMap();
for (String type : types) {
String name = "a." + type;
String bestType = typeMap.getContentType(name);
if (bestType.equals("application/octet-stream")) {
System.out.print( "Using URLConnection: " );
try {
bestType = (new File(name)).toURI().toURL()
.openConnection().getContentType();
} catch(Exception e) {
System.out.println( e.getMessage() );
}
}
System.out.println (type + " " + bestType);
}
}
}
Here are the results on a Windows 7 PC.
Using URLConnection: png image/png
jpg image/jpeg
gif image/gif
tif image/tiff
Using URLConnection: bmp content/unknown
Using URLConnection: snd audio/basic
wav audio/x-wav
Using URLConnection: mp3 content/unknown
Using URLConnection: ogg content/unknown
au audio/basic
mov video/quicktime
avi video/x-msvideo
mpg video/mpeg
Using URLConnection: flv content/unknown
Press any key to continue . . .
Iterate on all the folders of your file system and look for files with the extensions you need (if you have time).