java.awt.print.PrinterException: Printer is not accepting job - java

I am facing java.awt.print.PrinterException: Printer is not accepting job..Exception in my jsp page when sending documents to print dyanamically................
String pdfFile = "D://Records.pdf";
boolean silentPrint = false;
String printerindx = "1";
String password = "";
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
if (pdfFile == null) {
System.out.println("No PDF file available");
}
PDDocument document = null;
try {
document = PDDocument.load(pdfFile);
if (document.isEncrypted()) {
document.decrypt(password);
}
PrinterJob printJob = PrinterJob.getPrinterJob();
if (printerindx != null) {
PrintService[] printServices = PrinterJob.lookupPrintServices();
for (PrintService printService : printServices) {
if (printService.getName().equals("HP LaserJet P1007") {
System.out.println("Printer found ....");
printJob.setPrintService(printService);
System.out.println(printService);
}
}
}
document.print(printJob);
} finally {
if (document != null) {
document.close();
}
}
System.out.println("Printing Completed...");
whats going wrong ?

According to this: openjdk bug it is an error in printing libraries, and you have some options:
Use different JRE where error is fixed.
Repeat printing until it will not throw, people with similar problem say it often worked on first repeat.
Use hack from here: hack, see ForcedAcceptPrintService class

What Failed
I've previously attempted the solution from Piro's third suggestion, but I received the same error that the succeeding poster (post #10) experienced.
What Worked
I performed the bytecode hack, which overwrites the Win32PrintService getPrinterIsAcceptingJobs() method to always return a status of "ACCEPTING_JOBS." This worked perfectly for my needs: The printer is always seen as available and even if it's actually offline, print jobs are queued for whenever it comes back online. The only thing I had to do differently was grab an older version of Javassist (3.18) from GitHub since I'm compiling with Java 7. Attempting to compile with the latest version (3.20) -- which is built with Java 8 -- gave me the following error:
java.lang.UnsupportedClassVersionError: sun/print/Win32PrintService : Unsupported major.minor version 52.0
For anyone else unfamiliar with the compilations necessary to create the PrintServiceFixer.jar, here are the steps I took:
Copied javassist.jar to <JAVA_HOME>\jre\lib\ext
Compiled Win32PrintServiceFixer.java (from within <JAVA_HOME>\jre\lib)
javac -classpath .\rt.jar -bootclasspath ext\javassist.jar Win32PrintServiceFixer.java
Created PrintServiceFixer.jar file:
java -cp .;.\ext\javassist.jar Win32PrintServiceFixer
Copied PrintServiceFixer.jar from <JAVA_HOME>\jre\lib\target to the directory where I store my program's library/JAR files.
Ran my program
java -jar -Xbootclasspath/p:path\to\my\program's\libs\PrintServiceFixer.jar MyPrintingProgram.jar

Related

How to get the opened document using UNO?

I'm writing an add-on that opens a dialog and I need to access the currently opened text document but I don't know how get it.
I'm using the OpenOffice plug-in in NetBeans and I started from an Add-on project. It created a class that gives me a XComponentContext instance but I don't know how to use it to get a OfficeDocument instance of the current document.
I've been googling for some time and I can't find any example that uses an existing, opened, document. They all start from a new document or a document that is loaded first so they have an URL for it.
I gave it a try based on the OpenOffice wiki (https://wiki.openoffice.org/wiki/API/Samples/Java/Office/DocumentHandling) and this is what I came up with:
private OfficeDocument getDocument() {
if (this.officeDocument == null) {
try {
// this causes the error
XMultiComponentFactory xMultiComponentFactory = this.xComponentContext.getServiceManager();
Object oDesktop = xMultiComponentFactory.createInstanceWithContext("com.sun.star.frame.Desktop", this.xComponentContext);
XComponentLoader xComponentLoader = UnoRuntime.queryInterface(XComponentLoader.class, oDesktop);
String url = "private:factory/swriter";
String targetFrameName = "_self";
int searchFlags = FrameSearchFlag.SELF;
PropertyValue[] propertyValues = new PropertyValue[1];
propertyValues[0] = new PropertyValue();
propertyValues[0].Name = "Hidden";
propertyValues[0].Value = Boolean.TRUE;
XComponent xComponent = xComponentLoader.loadComponentFromURL(url, targetFrameName, searchFlags, propertyValues);
XModel xModel = UnoRuntime.queryInterface(XModel.class, xComponent);
this.officeDocument = new OfficeDocument(xModel);
} catch (com.sun.star.uno.Exception ex) {
throw new RuntimeException(ex);
}
}
return this.officeDocument;
}
But there is something strange going on. Just having this method in my class, even if it's never been called anywhere, causes an error when adding the add-on.
(com.sun.star.depoyment.DeploymentDescription){{ Message = "Error during activation of: VaphAddOn.jar", Context = (com.sun.star.uno.XInterface) #6ce03e0 }, Cause = (any) {(com.sun.star.registry.CannotRegisterImplementationException){{ Message = "", Context = (com.sun.star.uno.XInterface) #0 }}}}
It seems this line causes the error:
XMultiComponentFactory xMultiComponentFactory = this.xComponentContext.getServiceManager();
I have no idea how to preceed.
I posted this question on the OpenOffice forum but I haven't got a response there. I'm trying my luck here now.
Use this in your code to get the current document:
import com.sun.star.frame.XDesktop;
...
XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, oDesktop);
XComponent xComponent = xDesktop.getCurrentComponent();
I opened the BookmarkInsertion sample in NetBeans and added this code to use the current document instead of loading a new document.
As far as the error, there may be a problem with how it is getting built. A couple of things to check:
Does the Office SDK version match the Office version? Check version number and whether it's 32- or 64-bit.
Make sure that 4 .jar files (juh.jar, jurt.jar, unoil.jar, ridl.jar) are shown under Libraries in NetBeans, because they need to be included along with the add-on.
If you get frustrated with trying to get the build set up correctly, then you might find it easier to use python, since it doesn't need to be compiled. Also python does not require queryInterface().

Can't print text file using Java 8 in Windows 7

I've created a report and exported it as a text file, to print in a matrix printer, however, the result of the job is a blank page. I did the same in ubuntu and it is printing correctly.
Is it a Java bug?
This is a example code I did to show you the problem:
public class PrintError extends Application {
public static void main(String args[]) {
launch(args);
}
public void start(Stage stage) throws PrintException {
PrinterJob printerJob = PrinterJob.createPrinterJob();
printerJob.showPrintDialog(stage);
PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
printRequestAttributeSet.add(new Copies(printerJob.getJobSettings().getCopies()));
printRequestAttributeSet.add(new JobName("test", Locale.getDefault()));
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc mydoc = new SimpleDoc(ClassLoader.class.getResourceAsStream("/should-be-printed.txt"), flavor, null);
DocPrintJob job = getPrintService(printerJob.getPrinter().getName()).createPrintJob();
job.print(mydoc, printRequestAttributeSet);
}
private PrintService getPrintService(String name) {
for (PrintService printService : java.awt.print.PrinterJob.lookupPrintServices()) {
if (name.equalsIgnoreCase(printService.getName())) {
return printService;
}
}
return null;
}
}
This example was created in JavaFx 8 and is running in Java build 1.8.0-b132 in Windows 7.
I've also created a simple project at github
From the documentation:
Recommended DocFlavors
The Java Print Service API does not define any mandatorily supported DocFlavors. …
When you have a PrintService instance, you can use the method getSupportedDocFlavors() to find out which flavors it supports.
When you find out that none of the DocFlavor. INPUT_STREAM. TEXT_PLAIN_… flavors is in the list, it doesn’t help to use AUTOSENSE as that simply means “best guess” and it’s unlikely that a PrintService will guess a type it doesn’t support, instead, it’s more likely that the data will be misinterpreted as one of the formats it supports.
On my Windows machine, none of the provided PrintServices supports printing plaintext…
If anyone else comes across a similar problem (Printing blank in Windows 7 but working in Windows 10 in my case), but the DocFlavor is set correctly (i.e. One supported by a chosen print service)...
I was able to solve my issue by updating the JRE from 32-bit 8u101 to 64-bit 8u121.

How to get jboss7 version in java programatically through? [duplicate]

This question already has answers here:
How do I programmatically obtain the version in JBoss AS 5.1?
(2 answers)
Closed 8 years ago.
i have use j boss 4.2.2 to latest version.i have use java development kit 1.5 to 1.7 latest version all j boss version in get all java development kit. how to get j boss version in java code through.
With 5 there is a properties file: /org/jboss/version.properties where the keys version.major and version.minor looks for your case. Sust load the file to Properties and read. See link below:
http://grepcode.com/file/repository.jboss.org/nexus/content/repositories/releases/org.jboss.jbossas/jboss-as-main/5.0.0.CR2/org/jboss/version.properties
This file has been kept also in jboss6.1
http://grepcode.com/file/repository.jboss.org/nexus/content/repositories/releases/org.jboss.jbossas/jboss-as-main/6.1.0.Final/org/jboss/version.properties?av=f
I realized you asked for jboss7.... but I leave the work I did in case can be useful (it is anyway an approach valid for 5 and 6 versions)
For jboss7 I found two ways:
WAY 1
Checking out the code from github I cannot find anymore this Versoin.properties in the sources.
But I could find a Version.class which stores the version and release code name as properties; you can use Version.AS_VERSION to get what you want as you can see from the source code:
public class Version {
public static final String AS_VERSION;
public static final String AS_RELEASE_CODENAME;
public static final int MANAGEMENT_MAJOR_VERSION = 1;
public static final int MANAGEMENT_MINOR_VERSION = 4;
public static final int MANAGEMENT_MICRO_VERSION = 0;
static {
InputStream stream = Version.class.getClassLoader().getResourceAsStream("META-INF/MANIFEST.MF");
Manifest manifest = null;
try {
if (stream != null)
manifest = new Manifest(stream);
} catch (Exception e) {
}
String version = null, code = version;
if (manifest != null) {
version = manifest.getMainAttributes().getValue("JBossAS-Release- Version");
code = manifest.getMainAttributes().getValue("JBossAS-Release-Codename");
}
if (version == null) {
version = "Unknown";
}
if (code == null) {
code = "Unknown";
}
AS_VERSION = version;
AS_RELEASE_CODENAME = code;
}
}
WAY2
Another option that I found googling but I didn't verify personally is going through JMX (perhaps you prefer this approach):
ModelControllerClient client = ModelControllerClient.Factory.create(InetAddress.getByName("localhost"), 9999);
ModelNode op = new ModelNode();
op.get(ClientConstants.OP).set("read-resource");
ModelNode returnVal = client.execute(op);
logger.info("release-version: " + returnVal.get("result").get("release-version").asString());
logger.info("release-codename: " + returnVal.get("result").get("release-codename").asString());
And from the jboss-admin command line interface, you can get the info from these commands:
/:read-attribute(name=release-version)
/:read-attribute(name=release-codename)
NOTE:
The source code are now under git clone https://github.com/wildfly/wildfly.git (the jboss website still send to an outdated link)
Try this tutorial: https://community.jboss.org/thread/176932?start=0&tstart=0
or this: How do I programmatically obtain the version in JBoss AS 5.1?

java.lang.nosuchfielderror in j2me app

Hey Hi Friends I am created one j2me app. it runs perfectly in Emulator but in Mobile it showing error like java.lang.nosuchfielderror:No such field HEADERS.[[Ljava/lang/String;.
Why this happening with mobile, it runs good in emulator......
Please help me to remove this error......
public String connectPhoneName() throws Exception{
String url = "http://122.170.122.186/Magic/getPhonetype.jsp";
String phoneType;
if ((conn = connectHttp.connect(url, HEADERS)) != null) {
if ((in = connectHttp.getDataInputStream(conn)) != null) {
byte[] data = connectHttp.readDATA(in, 100);
phoneType = new String(data);
System.out.println("DATA : " + phoneType);
} else {
throw new Exception("ERROR WHILE OPENING INPUTSTREAM");
}
} else {
throw new Exception("COULD NOT ESTABLISH CONNECTION TO THE SERVER");
}
return phoneType;
}
In this code i have used HEADERS.
It looks like your app is using some (I guess) or static final or final field of some library class that does not exist in the profile of Java ME your mobile device implements.
But I can't figure out where that field comes from. Perhaps you should search your codebase for use of "HEADER" as an identifier ...
If the HEADER field is properly declared in your codebase (your MagiDEF interface) and the code you showed is using the HEADER from that interface, then you must have something wrong with your build or deployment process. Specifically, you are not deploying the version of MagiDEF that your code (above) has been compiled against. Maybe you've got an old version of something in some JAR file?
Basically, the error indicates that you have a binary incompatibility between some of the classes / interfaces that make up your app.

Execute a Java program from our Java program

I used
Runtime.getRuntime().exec("_____")
but it throws a IOException as below:
java.io.IOException: CreateProcess: c:/ error=5
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Win32Process.java:63)
at java.lang.Runtime.execInternal(Native Method
I don't know whether I have the problem with specifying the path or something else. Can anyone please help me with the code.
You're trying to execute "C:/". You'll want to execute something like:
"javaw.exe d:\\somejavaprogram\\program.jar"
Notice the path separators.
I'm assuming this is for an ad-hoc project, rather than something large. However, for best practice running external programs from code:
Don't hardcode the executable location, unless you're certain it will never change
Look up directories like %windir% using System.getenv
Don't assume programs like javaw.exe are in the search path: check them first, or allow the user to specify a location
Make sure you're taking spaces into account: "cmd /c start " + myProg will not work if myProg is "my program.jar".
You can either launch another JVM (as described in detail in other answers).
But that is not a solution i would prefer.
Reasons are:
calling a native program from java is "dirty" (and sometimes crashes your own VM)
you need to know the path to the external JVM (modern JVMs don't set JAVA_HOME anymore)
you have no control on the other program
Main reason to do it anyway is, that the other application has no control over your part of the program either. And more importantly there's no trouble with unresponsive system threads like the AWT-Thread if the other application doesn't know its threading 101.
But! You can achieve more control and similar behaviour by using an elementary plugin technique. I.e. just call "a known interface method" the other application has to implement. (in this case the "main" method).
Only it's not quite as easy as it sounds to pull this off.
you have to dynamically include required jars at runtime (or include them in the classpath for your application)
you have to put the plugin in a sandbox that prevents compromising critical classes to the other application
And this calls for a customized classloader. But be warned - there are some well hidden pitfalls in implementing that. On the other hand it's a great exercise.
So, take your pick: either quick and dirty or hard but rewarding.
java.io.IOException: CreateProcess: c:/ error=5
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Win32Process.java:63)
at java.lang.Runtime.execInternal(Native Method)
If I recall correctly, error code 5 means access denied. This could be because your path is incorrect (trying to execute "c:/") or you are bumping against your OS security (in which case, look at the permissions).
If you are having trouble locating the Java executable, you can usually find it using system properties:
public class LaunchJre {
private static boolean isWindows() {
String os = System.getProperty("os.name");
if (os == null) {
throw new IllegalStateException("os.name");
}
os = os.toLowerCase();
return os.startsWith("windows");
}
public static File getJreExecutable() throws FileNotFoundException {
String jreDirectory = System.getProperty("java.home");
if (jreDirectory == null) {
throw new IllegalStateException("java.home");
}
File exe;
if (isWindows()) {
exe = new File(jreDirectory, "bin/java.exe");
} else {
exe = new File(jreDirectory, "bin/java");
}
if (!exe.isFile()) {
throw new FileNotFoundException(exe.toString());
}
return exe;
}
public static int launch(List<String> cmdarray) throws IOException,
InterruptedException {
byte[] buffer = new byte[1024];
ProcessBuilder processBuilder = new ProcessBuilder(cmdarray);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
InputStream in = process.getInputStream();
while (true) {
int r = in.read(buffer);
if (r <= 0) {
break;
}
System.out.write(buffer, 0, r);
}
return process.waitFor();
}
public static void main(String[] args) {
try {
Runtime.getRuntime().exec("c:/");
List<String> cmdarray = new ArrayList<String>();
cmdarray.add(getJreExecutable().toString());
cmdarray.add("-version");
int retValue = launch(cmdarray);
if (retValue != 0) {
System.err.println("Error code " + retValue);
}
System.out.println("OK");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
(Tested Windows XP, Sun JRE 1.6; Ubuntu 8.04, OpenJDK JRE 1.6)
This is the equivalent of running:
java -version
You may also want to look at the "java.library.path" system property (and "path.separator") when trying to locate the executable.
How about just calling the main from your java program?
Test.main(null);
This worked fine for me
Is there any reason you can't just call it directly in your Java code?
If there is a reason I've not tried it for executing a Java Program but you could try Jakarta Commons Exec works well for executing most programs.
I had to do this recently.
Here is how I did it, picking up only the relevant parts:
private static final String[] straJavaArgs =
{
"?i/j2re/bin/java",
"-ms64m",
"-mx64m",
"-Djava.ext.dirs=?i/lib;?i/jar/lib;?i/jar"
};
// ...
// AppDesc appToRun;
List<String> params = new ArrayList<String>();
// Java exe and parameters
params.addAll(ExpandStrings(straJavaArgs));
// Common VM arguments
params.addAll(Arrays.asList(AppDesc.GetCommonVMArgs()));
// Specific VM arguments
params.addAll(ExpandStrings(appToRun.GetVMArgs()));
// The program to run
params.add(appToRun.GetClass());
// Its arguments
params.addAll(ExpandStrings(appToRun.GetProgramArgs()));
// The common arguments
params.addAll(ExpandStrings(AppDesc.GetCommonProgramArgs()));
ProcessBuilder processBuilder = new ProcessBuilder(params);
process = processBuilder.start();
return CaptureProcessOutput(); // Uses a StreamGobbler class
protected ArrayList<String> ExpandStrings(String[] stra)
{
ArrayList<String> alResult = new ArrayList<String>();
for (int i = 0; i < stra.length; i++)
{
// Super flexible, eh? Ad hoc for the current task, at least...
alResult.add(stra[i]
.replaceAll("\\?i", strInstallDir)
.replaceAll("\\?c", strConfigDir)
);
}
return alResult;
}
public enum AppDesc
{
// Enumerate the applications to run, with their parameters
}
Incomplete, if you need more details, just ask.
public class Test {
public static void main(String[] args) throws Exception {
Process p = Runtime.getRuntime().exec("\"c:/program files/windows/notepad.exe\"");
p.waitFor();
}
}
The above works quite well, instead of passing \"c:/program files/windows/notepad.exe\" as the arguments for the executable, use the path to your program, I'm not sure if this solution is JVM version dependent, or if it can use relative paths.
You must pass the path of your executable at the exec method. Are you really trying to execute the "-" process?
Also, have a look at this for some useful tips.
Put ant lib in you classpath ( project lib ) and run this code :
import org.apache.tools.ant.taskdefs.Execute;
Execute exe = new Execute();
exe.setCommandline(new String[]{"java", "-version"});
exe.execute();
I can't remember the exact code that I used to get this to work, but you have to pass "java.exe" (or the equivalent) as the executable, and then the class or jar to run as the parameter, with the correct working directory. So it's not as simple as just calling one method.
I had a similiar problem. I needed to run a section of Java code in a seperate VM as it invoked native code via JNI that occasionally blew up taking out the entire VM.
I cheated a little though. I initially used Runtime to invoke a simple batch command file and put the work-in-progress java command in there. This enabled me to tweak it as needed and to run the command in a DOS prompt for easy testing. Once it was finished I simply copied the result into the Runtime invocation.
First you compile the prog-A code and convert to jar file(ie:In NetBeans Shift-F11)and the path is of netbeans(NetBeansProjects/prog-A/dist/prog-A.jar)
public class ProgA {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Helllo print thr ProgA");
}
}
}
Second open the new project in prog-B and add the libraries, and select the jar and give to the prog-A.jar file and write the two line in your program
public class ProgB {
public static void main(String[] args) {
ProgA progA = new ProgA();
String arg[] = null;
progA.main(arg);
}
}
I agree with Ushsa Varghese, if you just want to run your jar file instead of compiling the .java file that is in the same directory you are executing your application from try the code below. This is the same as executing your java application from the command line so you have to invoke the jvm in order to run your application. Also make sure you have the complete path to your jar file the example below assumes that the jar file is in the same directory as the application that is executing the code below. keep in mind this is system dependent code.
try {
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("java -jar deleteDriveC.jar");
} catch (IOException ex) {
//jar file doesnt exist
//Logger.getLogger(this.class.getName()).log(Level.SEVERE, null, ex);
}
The answer is simple all you have to do is put the code -
$ process p = Runtime.getRuntime().exec("javac factorial.java"); in the try catch block
The code would look like this -
try
{
process p = Runtime.getRuntime().exec("javac factorial.java");
}
catch(IOException e)
{
e.printStackTrace();
}
Hey I think this should work. Atleast for me it did work

Categories