Can't print on virtual machine with java code - java

i am running a virtual machine with VMware 9.0. I added the printers via the Settings tab in the VM. To see that my printers are availabe on my vm i wrote a little program:
import java.io.PrintStream;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
public class ShowPrinter {
public static void main(String[] args) {
PrintService lookupDefaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
if (lookupDefaultPrintService != null)
System.out.println("default: " + lookupDefaultPrintService.getName());
else {
System.out.println("default: null");
}
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
for (PrintService service : services)
if (service != null)
System.out.println("- " + service.getName());
else
System.out.println("- null");
}
}
This works well and i get some printers listed (including the one i want to use). I wrote a little program which should print something:
package virtualMachinePrinter;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocFlavor.INPUT_STREAM;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
public class MyPrinter {
public static void main(String[] args) throws IOException {
File file = new File("C:/temp/printtest.txt");
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
DocPrintJob job = service.createPrintJob();
Doc doc = new SimpleDoc(inputStream, flavor, null);
try {
job.print(doc, null);
} catch (PrintException e) {
e.printStackTrace();
}
inputStream.close();
System.out.println("Printing done...");
}
}
On my local machine this works just well, and if i change the default printer, it prints to it. On the virtual machine this works not as intended. The XPS document writer doesn't even start. If i try the same with pdf-printer, the page setup opens at least (but nothing is printed). If i start the little programm above inside a web-application on a Tomcat 7, it doesn't print anything. Independent of which default printer is used. In both cases the print order is added to the printing queue. But only outside of a Tomcat something is printed. Inside the Tomcat nothing is printed. I am using no security manager in my Tomcat.

Two actions solved this problem:
1. I had to use 32-bit version of Java. This fixed the problem printing with XPS document writer.
2. I had to update my printer drivers. This fixed the problem printing with the printer.

Related

Google Cloud Trace Opentelemetry Java example code not showing up on Google Cloud Trace Dashboard

I followed the steps on Google Cloud's Java and OpenTelemetry site (https://cloud.google.com/trace/docs/setup/java-ot) and made a simple hello world Java application locally and am trying to get my traces to show up on Google Cloud Trace using their trace exporter.
All the setup code is the same, and the program compiles and runs successfully. However, I don't see anything on the Trace dashboard. I know it is not an issue with IAM or my service account key because I ran the Python example and it shows up in Cloud Trace dashboard just fine.
Anyone have any guidance on why the Java version could be silently failing?
Thanks
package hello;
import org.joda.time.LocalTime;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import io.opentelemetry.exporter.logging.LoggingSpanExporter;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.ContextPropagators;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
import io.opentelemetry.sdk.metrics.export.IntervalMetricReader;
import java.io.IOException;
import java.util.Random;
import com.google.cloud.opentelemetry.trace.TraceConfiguration;
import com.google.cloud.opentelemetry.trace.TraceExporter;
import java.util.Collections;
import static java.util.Collections.singleton;
import java.time.Duration;
public class HelloWorld {
private static final Random random = new Random();
private static OpenTelemetry setupTraceExporter() {
try {
TraceExporter traceExporter = TraceExporter.createWithConfiguration(
TraceConfiguration.builder().setProjectId("my-test-id").build());
// Register the TraceExporter with OpenTelemetry
return OpenTelemetrySdk.builder()
.setTracerProvider(
SdkTracerProvider.builder()
.addSpanProcessor(BatchSpanProcessor.builder(traceExporter).build())
.build())
.buildAndRegisterGlobal();
} catch (IOException e) {
System.out.println("Uncaught Exception");
System.out.println(e);
return null;
}
}
public static void main(String[] args) {
System.out.println("Starting the example application");
/* SET UP */
OpenTelemetry otel = setupTraceExporter();
/* Creating tracer */
Tracer tracer =
otel.getTracer("java foo");
Span span = tracer.spanBuilder("my span").startSpan();
// put the span into the current Context
try (Scope scope = span.makeCurrent()) {
System.out.println("Hello");
Thread.sleep(4000);
} catch (Throwable t) {
span.setStatus(StatusCode.ERROR, "error");
System.out.println(t);
} finally {
span.end();
}
System.out.println("Closing");
//otel.getSdkTracerProvider().shutdown();
}
}
After some debugging, I figured out the answer.
Seems like with this simple example, the BatchSpanProcessor is not a good idea because there is only one span that is getting traced.
SimpleSpanProcessor directly forwards the spans to Cloud Trace no matter what whereas BatchSpanProcessor waits until there is enough data before pushing to Cloud Trace. Hence why I was not seeing anything in Cloud Trace because BatchSpanProcessor hadn't registered enough spans for it to actually upload it to Google Cloud.
Span Processors Documentation
Change the following lines
return OpenTelemetrySdk.builder()
.setTracerProvider(
SdkTracerProvider.builder()
.addSpanProcessor(SimpleSpanProcessor.create(traceExporter))
.build())
.buildAndRegisterGlobal();
Hope this helps others!

ORA-29532: Java call terminated by uncaught Java exception: java.awt.HeadlessException

i execute java class to screenshot of my screen with following code:
import java.awt.AWTException;
import java.awt.FlowLayout;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FullScreenCapture extends JFrame {
private static final long serialVersionUID = 1L;
public static String capture() {
FullScreenCapture f = new FullScreenCapture();
String Ret;
try {
Thread.sleep(5000);
System.setProperty("java.awt.headless", "true");
Robot robot = new Robot();
String fileName = "D://FullScreenshot.jpg";
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit()
.getScreenSize());
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
System.out.println("Headless mode: " + ge.isHeadless());
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage, "jpg", new File(fileName));
Ret ="Capture Saved Successfully";
} catch (Exception e) {
System.out.println("Exception occurred");
Ret ="Wrong Error";
}
return Ret;
}
}
the program don't have any problems when executed in netbeans or in cmd,
but when load java of java class into oracle database
to call it as function,return error message java.awt.HeadlessException
You are using java.awt.Robot which needs a graphical, non-headless environment to work. As per Robot() javadoc:
AWTException - if the platform configuration does not allow low-level input control. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true
The Oracle database server doesn't provide a graphical environment so it can't run your code. As per User Interfaces on the Server Oracle docs:
Oracle Database furnishes all core Java class libraries on the server, including those associated with presentation of the user interfaces. However, it is inappropriate for code running on the server to attempt to materialize or display a user interface on the server. Users running applications in Oracle JVM environment should not be expected nor allowed to interact with or depend on the display and input hardware of the server where Oracle Database is running.

Why Java Files.createFile with permissions doesn't work correctly?

I need to ceate file and set permissions(-rwxrw-r) to it, the permission of parent dir is (drwxrwxr--). The problem is that the write permission is
not set in created files. The user that ran this application is the owner of the parent dir.
Below is my test class that present the same problem. When I run this program, the permissions of generated file is (-rwxr--r--) though the class set permissions (-rwxrw-rw-). Why the write permission is not set
and I don't see any exception?
Any idea?
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public class TestPermission{
static String parentDir = "/tmp/test/";
static Set<PosixFilePermission> defaultPosixPermissions = null;
static {
defaultPosixPermissions = new HashSet<>();
defaultPosixPermissions.add(PosixFilePermission.OWNER_READ);
defaultPosixPermissions.add(PosixFilePermission.OWNER_WRITE);
defaultPosixPermissions.add(PosixFilePermission.OWNER_EXECUTE);
defaultPosixPermissions.add(PosixFilePermission.GROUP_READ);
defaultPosixPermissions.add(PosixFilePermission.GROUP_WRITE);
//Others have read permission so that ftp user who doesn't belong to the group can fetch the file
defaultPosixPermissions.add(PosixFilePermission.OTHERS_READ);
defaultPosixPermissions.add(PosixFilePermission.OTHERS_WRITE);
}
public static void createFileWithPermission(String fileName) throws IOException{
// File parentFolder = new File(parentDir);
// PosixFileAttributes attrs = Files.readAttributes(parentFolder.toPath(), PosixFileAttributes.class);
// System.out.format("parentfolder permissions: %s %s %s%n",
// attrs.owner().getName(),
// attrs.group().getName(),
// PosixFilePermissions.toString(attrs.permissions()));
// FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(attrs.permissions());
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(defaultPosixPermissions);
File file = new File(fileName);
Files.createFile(file.toPath(), attr);
}
public static void main(String[] args) throws IOException{
String fileName = parentDir + "testPermission_" + System.currentTimeMillis();
createFileWithPermission(fileName);
}
}
I believe the catch here is
The check for the existence of the file and the creation of the new
file if it does not exist are a single operation that is atomic with
respect to all other filesystem activities that might affect the
directory.
as mentioned in Class Files
This might be because of the OS operations that happen after a file is being created. The following modification in code should get things work fine:
File file = new File(fileName);
Files.createFile(file.toPath(), attr);
Files.setPosixFilePermissions(file.toPath(), defaultPosixPermissions); //Assure the permissions again after the file is created
It turns out that the reason is that my os has a umask as 0027(u=rwx,g=rx,o=) which means application has no way to
set permission for others group.
Files.createFile(file.toPath(), attr);
in the above line instead of using Files.createFile
use file.createNewFile() and if it returns true then the file is created.

Unable to get correct letters when sending special characters to the printer in Java

I am writing a program that are working with adresses and I want the final output to be sent to a printer. As most of the adresses are located in northen Europe I need to be able to handle some special characters. However I seem to be unable to do this when printing.
When writing to the terminal or to a *.txt file everything works fine but on the printed pages I get gibberish.
This is basicly what I am trying to do:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.print.*;
public class PrintExample {
public static void main(String[] args) throws PrintException,IOException {
String testData = "ÅÄÖ, åäö";
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
InputStream is = new ByteArrayInputStream(testData.getBytes("UTF-8"));
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
DocPrintJob job = service.createPrintJob();
Doc doc = new SimpleDoc(is, flavor, null);
job.print(doc, null);
is.close();
}
}
Does anyone have a clue as to what's wrong?

Win Scheduled Task cannot see PrintService

I have a java code that sends PDF files to printers.
Java code goes something like this:
import java.awt.print.PrinterJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.pdmodel.PDDocument;
public class PrintPdf {
protected final Log logger = LogFactory.getLog(getClass());
public void print(String pdfFile, String printer, int copies) throws Exception {
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
PDDocument document = null;
try
{
document = PDDocument.load( pdfFile );
PrinterJob printJob = PrinterJob.getPrinterJob();
PrintService[] printServices = PrinterJob.lookupPrintServices();
PrintService myService = null;
if (printServices.length > 0)
{
for(PrintService service : printServices) {
if(service.getName().toLowerCase().contains(printer.toLowerCase())) {
myService = service;
break;
}
}
if (myService == null) {
throw new Exception("Printer not found " + printer);
} else {
logger.info("Printer found " + myService.getName());
}
} else {
throw new Exception("No print services found");
}
printJob.setPrintService(myService);
printJob.setCopies(copies);
document.silentPrint( printJob );
}
finally {
if( document != null ) {
document.close();
}
}
}
This java is called from batch file. I've scheduled a windows task to run the file every X minutes. Scheduled Task is run with a user that has admin rights. All this is run on a Windows 2003 server.
Printers are set up using a TCP/IP address.
The problem: When the user is logged in, the Task runs and can send PDF files to the printers.
When the user is not logged in, the Task runs but java returns an error:
java.awt.print.PrinterException: Invalid name of PrintService
Java program successfully lists available Print Services in the loop, just before the print command, but for some reason is not able to print the document while the user is not logged in.
Could anyone, please, give me some advice on what might be the problem here?
EDIT:
Exception occurs in the line:
printJob.setPrintService(myService);
The solution to this problem was to upgrade the existing java on the OS from version 6u45 to 7u21.

Categories

Resources