I am trying to call the "dspdf.exe" inside the jar file where this smartpdf class exists. I plan to extract it to a temp location and delete when program ends. However this doesn't seem to work, any help will be appreciated.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.omg.CORBA.portable.InputStream;
public class smartpdf {
static String url="";
static String output="output.pdf";
public static void main(String[] args) throws IOException{
gui mygui = new gui();//gui will call the generate function when user selects
}
public static void generate() throws IOException{
InputStream src = (InputStream) smartpdf.class.getResource("dspdf.exe").openStream();
File exeTempFile = File.createTempFile("dspdf", ".exe");
FileOutputStream out = new FileOutputStream(exeTempFile);
byte[] temp = new byte[32768];
int rc;
while((rc = src.read(temp)) > 0)
out.write(temp, 0, rc);
src.close();
out.close();
exeTempFile.deleteOnExit();
Runtime.getRuntime().exec(exeTempFile.toString()+" "+url+" "+output );
//Runtime.getRuntime().exec("dspdf "+url+" "+output);
}
}
EDIT:
The error that I am getting:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoa
der.java:56)
Caused by: java.lang.ClassCastException: sun.net.www.protocol.jar.JarURLConnecti
on$JarURLInputStream cannot be cast to org.omg.CORBA.portable.InputStream
at smartpdf.generate(smartpdf.java:18)
at smartpdf.main(smartpdf.java:14)
... 5 more
You use the wrong InputStream. Change it to java.io.InputStream.
Why do you use org.omg.CORBA.portable.InputStream instead of a java.io.BufferedInputStream`
with as parameters the inputstream from the resource. I mean this:
BufferedInputStream inputstream = new BufferedInputStream(smartpdf.class.getResourceAsStream(...));
The same for your fileoutput stream: BufferedOutputStream
Don't use
class.getResource(...).openStream();
but use
class.getResourceAsStream(...);
Note also (once you've resolved the InputStream issue) that you should be consuming your spawned process stdout and stderr, otherwise the spawned process may block. See this answer for more details.
Related
I am using Sphinx4 for custome home automatization software and I am stuck on using my custom dict file, for some reason it cant find the file even though I am sure I am using the correct path. This is my code :
package pccomone;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.LiveSpeechRecognizer;
import edu.cmu.sphinx.api.SpeechResult;
import edu.cmu.sphinx.api.StreamSpeechRecognizer;
public class Main {
private static final String BODICPATH = "PCCom/src/resource/bodict.dict";
public static void main(String args[]) throws Exception{
Configuration configuration = new Configuration();
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
configuration.setDictionaryPath(BODICPATH);
//configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict"); use only for large commands!!!!!!!!!
configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.bin");
LiveSpeechRecognizer recognizer = new LiveSpeechRecognizer(configuration);
recognizer.startRecognition(true);
SpeechResult result;
while((result = recognizer.getResult()) != null){
String command = result.getHypothesis();
if(command.equalsIgnoreCase("stop")){
recognizer.stopRecognition();
System.exit(0);
}
System.out.println(command);
}
}
}
I didn't come far since I can't get it to use my custom dict file and the included dict file is way to large for the software to work fast and accurate.
This is the Error,
Exception in thread "main" java.lang.RuntimeException: Allocation of
search manager resources failed
at edu.cmu.sphinx.decoder.search.WordPruningBreadthFirstSearchManager.allocate(WordPruningBreadthFirstSearchManager.java:247)
at edu.cmu.sphinx.decoder.AbstractDecoder.allocate(AbstractDecoder.java:103)
at edu.cmu.sphinx.recognizer.Recognizer.allocate(Recognizer.java:164)
at edu.cmu.sphinx.api.LiveSpeechRecognizer.startRecognition(LiveSpeechRecognizer.java:47)
at pccomone.Main.main(Main.java:26)
Caused by: java.io.FileNotFoundException: PCCom\src\resource\bodict.dict (The system cannot find the path
specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at sun.net.www.protocol.file.FileURLConnection.connect(Unknown Source)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(Unknown
Source)
at java.net.URL.openStream(Unknown Source)
at edu.cmu.sphinx.linguist.dictionary.TextDictionary.allocate(TextDictionary.java:180)
at edu.cmu.sphinx.linguist.lextree.LexTreeLinguist.allocate(LexTreeLinguist.java:332)
at edu.cmu.sphinx.decoder.search.WordPruningBreadthFirstSearchManager.allocate(WordPruningBreadthFirstSearchManager.java:243)
... 4 more
Hi I want to compress and store compressed image to folder. So I have used the below code,
import java.io.*;
import java.util.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;
public class Compression {
public static void main(String[] args) throws IOException {
String dc = "C:\\Users\\admin\\Desktop\\RFI\\DC\\1_1_c.jpg";
String dr = "C:\\Users\\admin\\Desktop\\RFI\\DR";
File file = new File(dc);
BufferedImage image = ImageIO.read(file);
OutputStream os =new FileOutputStream(new File(dr));
Iterator<ImageWriter>writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.05f);
writer.write(null, new IIOImage(image, null, null), param);
os.close();
ios.close();
writer.dispose();
}
}
But i'm not get compressed image. Only get the below error on console
Exception in thread "main" javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1301)
at com.opencv.Compression.main(Compression.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Please suggest me any idea....
This would deserve a comment more than an answer but since my reputation is so low, I can't comment and am forced to write it as an answer.
Did you try to understand the error you get ? The call stack is pretty clear. You have an error at the line BufferedImage image = ImageIO.read(file);. The program can't find your image. Did you make sure that the image file specified in String dc = "C:\\Users\\admin\\Desktop\\RFI\\DC\\1_1_c.jpg"; actually existed ?
Hi everyone I am currently trying to write a program for an assignment that takes 4 separate text files then using a method, combines them into one. I was wondering if someone could help me find out what is wrong with this code. When i try to run it I get a error reading the following:
"Exception in thread "main" java.io.FileNotFoundException: wonder1.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at asig5.combineFile(asig5.java:26)
at asig5.main(asig5.java:17) "
Code:
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
public class asig5 {
public static void main(String[] args) throws FileNotFoundException {
PrintWriter newtext = new PrintWriter("wonder5.txt");
File f0 = new File("wonder1.txt");
File f1 = new File("wonder2.txt");
File f2 = new File("wonder3.txt");
File f3 = new File("wonder4.txt");
combineFile(f0, newtext);
combineFile(f1, newtext);
combineFile(f2, newtext);
combineFile(f3, newtext);
newtext.close();
}
public static void combineFile(File f0, PrintWriter output) throws FileNotFoundException {
Scanner input = new Scanner(f0);
while (input.hasNext()) {
String part1 = input.nextLine();
System.out.println(part1);
output.print(part1);
}
}
}
When you write new File("wonder1.txt") it means that if your project location is ~/Folder/MyProject, your file's full path is ~/Folder/MyProject/wonder1.txt.
You need to provide full path to your file or put your files at the root of your project folder.
I have just imported jena libraries to eclipse to work on rdf-s and it is my first try, but I cannot read a turtle (.ttl) file.
I tried it in the following way:
import java.io.*;
import java.util.*;
import com.hp.hpl.jena.rdf.model.*;
public class Simpsons {
public static void main(String[] args) throws IOException {
Model model=ModelFactory.createDefaultModel();
model.read(new FileInputStream("simpsons.ttl"),null);
}
}
The error I get is the following:
Exception in thread "main" org.apache.jena.riot.RiotException: [line: 1, col: 1 ] Content is not allowed in prolog.
at org.apache.jena.riot.system.ErrorHandlerFactory$ErrorHandlerStd.fatal(ErrorHandlerFactory.java:136)
at org.apache.jena.riot.lang.LangRDFXML$ErrorHandlerBridge.fatalError(LangRDFXML.java:252)
at com.hp.hpl.jena.rdf.arp.impl.ARPSaxErrorHandler.fatalError(ARPSaxErrorHandler.java:48)
at com.hp.hpl.jena.rdf.arp.impl.XMLHandler.warning(XMLHandler.java:209)
at com.hp.hpl.jena.rdf.arp.impl.XMLHandler.fatalError(XMLHandler.java:239)
at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source)
at org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source)
at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at com.hp.hpl.jena.rdf.arp.impl.RDFXMLParser.parse(RDFXMLParser.java:151)
at com.hp.hpl.jena.rdf.arp.ARP.load(ARP.java:119)
at org.apache.jena.riot.lang.LangRDFXML.parse(LangRDFXML.java:142)
at org.apache.jena.riot.RDFParserRegistry$ReaderRIOTFactoryImpl$1.read(RDFParserRegistry.java:142)
at org.apache.jena.riot.RDFDataMgr.process(RDFDataMgr.java:859)
at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:255)
at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:241)
at org.apache.jena.riot.adapters.RDFReaderRIOT_Web.read(RDFReaderRIOT_Web.java:62)
at com.hp.hpl.jena.rdf.model.impl.ModelCom.read(ModelCom.java:253)
at assignment2.Simpsons.main(Simpsons.java:11)
Please help me with some ideas because I have no clue what the problem would be as it's my very first try with Jena. I also got a hint from somewhere that I should do the following: :
It seems that Jena is not so good at discovering the RDF serialisation
used in files by itself, especially for files addressed with an URL. A
solution to this problem is to make a method that gets the file
extension of the filename by the use of string functions and returns
the appropriate RDF serialisation format in Jena’s predefined strings.
You can then use your method both for reading input and writing to file
in the correct serialisation format.
but I don't really understand how should I write that method.
The read method you are using assumes that the input format is RDF/XML.
you need to use one of the other read methods.
So it would be:
public static void main(String[] args) throws IOException {
Model model=ModelFactory.createDefaultModel();
model.read(new FileInputStream("simpsons.ttl"),null,"TTL");
}
Following Program will read and traverse over the TTL file
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.jena.graph.Triple ;
import org.apache.jena.riot.RDFDataMgr ;
import org.apache.jena.riot.lang.PipedRDFIterator;
import org.apache.jena.riot.lang.PipedRDFStream;
import org.apache.jena.riot.lang.PipedTriplesStream;
public class ReadingTTL
{
public static void main(String... argv) {
final String filename = "yagoTransitiveType2.ttl";
// Create a PipedRDFStream to accept input and a PipedRDFIterator to
// consume it
// You can optionally supply a buffer size here for the
// PipedRDFIterator, see the documentation for details about recommended
// buffer sizes
PipedRDFIterator<Triple> iter = new PipedRDFIterator<>();
final PipedRDFStream<Triple> inputStream = new PipedTriplesStream(iter);
// PipedRDFStream and PipedRDFIterator need to be on different threads
ExecutorService executor = Executors.newSingleThreadExecutor();
// Create a runnable for our parser thread
Runnable parser = new Runnable() {
#Override
public void run() {
// Call the parsing process.
RDFDataMgr.parse(inputStream, filename);
}
};
// Start the parser on another thread
executor.submit(parser);
// We will consume the input on the main thread here
// We can now iterate over data as it is parsed, parsing only runs as
// far ahead of our consumption as the buffer size allows
while (iter.hasNext()) {
Triple next = iter.next();
// Do something with each triple
System.out.println("Subject: "+next.getSubject());
System.out.println("Object: "+next.getObject());
System.out.println("Predicate: "+next.getPredicate());
System.out.println("\n");
}
}
}
I have a web app that needs to be able open a file locally on a client machine, with the ability to save the file after editing. The web app generates a document on the server in a folder that is shared out via WebDAV & FTP and this folder is mounted on the client machine.
I cannot use a file:// type URI as it would not permit saving back to the server.
I intend trying to solve the problem with a small java applet embedded in the web app that handles this file opening, but I am having difficulties with permissions in Java. (Java isn't my field of expertise). Anyhow, I've narrowed the code down to the following:
localfile.html
<html>
<body>
<input id="input" value="Call from Javascript" type="button" onclick="callApplet('/Users/conor/1.txt')">
<script type='text/javascript'>
function callApplet(path) {
applet = document.getElementById('localfile');
applet.openFile(path);
}
</script>
<applet id="localfile" code="localfile.class" archive="localfile.jar" width="150" height="50"></applet>
</body>
</html>
localfile.java
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.lang.*;
import java.text.*;
import java.awt.event.*;
import java.io.*;
import java.security.*;
public class localfile extends Applet {
public localfile() {
Panel p = new Panel();
p.add(new Button("Call from Java"));
add("North",p);
}
public void openFile(String path) {
System.out.println("File: " + path);
final File ffile = new File(path);
System.out.println("Got file.");
if (Desktop.isDesktopSupported()) {
System.out.println("Desktop is supported.");
final Desktop desktop = Desktop.getDesktop();
System.out.println("Got Desktop Handle.");
try {
desktop.open(ffile);
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("File Opened.");
}
}
public boolean action(Event evt, Object arg) {
openFile("/Users/conor/1.txt");
return true;
}
}
I have compiled, created a jar file and signed it from the java source.
This produces a page with two buttons - a Java one (for testing) and a Javascript one. The Java button works fine as expected - and I can save the file etc. I want to pass the file path to the applet though so it is really the Javascript button I wish to get working. The Javascript one throws the following though:
Stack Trace
java.security.AccessControlException: access denied ("java.awt.AWTPermission" "showWindowWithoutWarningBanner")
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:366)
at java.security.AccessController.checkPermission(AccessController.java:560)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
at java.awt.Desktop.checkAWTPermission(Desktop.java:239)
at java.awt.Desktop.open(Desktop.java:267)
at localfile.openFile(localfile.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at sun.plugin.javascript.JSInvoke.invoke(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at sun.plugin.javascript.JSClassLoader.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MethodInfo.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MemberBundle.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke0(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$DefaultInvocationDelegate.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo.doObjectOp(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$LiveConnectWorker.run(Unknown Source)
at java.lang.Thread.run(Thread.java:722)
I have also tried embedding the desktop.open call into a doPrivileged block, as follows:
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
desktop.open(ffile);
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
});
but that throws error for javascript & java buttons as follows:
java.lang.SecurityException: class "localfile$1" does not match trust level of other classes in the same package
Any help would be appreciated.
Got it to work, so thought I'd post the solution here...
When I was compiling the java file with the doPrivileged call in it, the javac compiler creates two files - localfile.class and localfile$1.class. I wasn't sure initially what the localfile$1.class was and just presumed it was a temporary file of some sort. It was however a class file corresponding to the anonymous class within the doPrilileged block and needed to be included in the .jar file and properly signed.
So anyway, html file is as before, and final java file is as follows:
localfile.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.security.*;
public class localfile extends Applet {
private static final long serialVersionUID = 1L;
public localfile() {
Panel p = new Panel();
p.add(new Button("Call from Java"));
add("North",p);
}
public void openFile(String path) {
System.out.println("File: " + path);
final File ffile = new File(path);
System.out.println("Got file.");
if (Desktop.isDesktopSupported()) {
System.out.println("Desktop is supported.");
final Desktop desktop = Desktop.getDesktop();
System.out.println("Got Desktop Handle.");
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
desktop.open(ffile);
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
});
System.out.println("File Opened.");
}
}
public boolean action(Event evt, Object arg) {
openFile("/Users/conor/1.txt");
return true;
}
}
I also found that there was no need to have the javascript in the html file create the applet and insert it into the DOM. I think this was mentioned in the link #VGR linked to but it worked for me without it.
Thanks for all the help guys!