I'm developing a JAVA program that prints a file.
I need to know when the printer has completed printing the file, I've found this simple code that it is interesting:
import javax.print.*;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.PrintServiceAttributeSet;
import javax.print.attribute.standard.PrinterStateReason;
import javax.print.attribute.standard.PrinterStateReasons;
import javax.print.attribute.standard.Severity;
import javax.print.event.*;
import java.awt.*;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.*;
import java.util.Set;
/**
* PrintTest
*/
public class PrintTest implements PrintServiceAttributeListener,PrintJobListener,Doc, Printable, PrintJobAttributeListener {
private static final transient String TEXT = "12345";
public static void main(String[] args) {
PrintTest test = new PrintTest();
test.checkPrinters();
}
public void checkPrinters() {
Thread newThread = new Thread(new Runnable() {
public void run() {
PrintService ps = PrinterJob.getPrinterJob().getPrintService();
DocFlavor[] myFlavors = ps.getSupportedDocFlavors();
ps.addPrintServiceAttributeListener(PrintTest.this);
DocPrintJob docJob = ps.createPrintJob();
docJob.addPrintJobAttributeListener(PrintTest.this, null);
docJob.addPrintJobListener(PrintTest.this);
try {
docJob.print(PrintTest.this,null);
}
catch (PrintException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} });
newThread.start();
/**
PrintServiceAttributeSet attSet = ps.getAttributes();
PrinterStateReasons psr = ps.getAttribute(PrinterStateReasons.class);
if (psr != null) {
Set<PrinterStateReason> errors = psr.printerStateReasonSet(Severity.REPORT);
for (PrinterStateReason reason : errors)
System.out.printf(" Reason : %s",reason.getName());
System.out.println();
} */
}
public void attributeUpdate(PrintServiceAttributeEvent psae) {
System.out.println(psae.getAttributes());
}
public void printDataTransferCompleted(PrintJobEvent pje) {
System.out.println("Transfer completed");
}
public void printJobCompleted(PrintJobEvent pje) {
System.out.println("Completed");
}
public void printJobFailed(PrintJobEvent pje) {
System.out.println("Failed");
PrinterStateReasons psr = pje.getPrintJob().getPrintService().getAttribute(PrinterStateReasons.class);
if (psr != null) {
Set<PrinterStateReason> errors = psr.printerStateReasonSet(Severity.REPORT);
for (PrinterStateReason reason : errors)
System.out.printf(" Reason : %s",reason.getName());
System.out.println();
}
}
public void printJobCanceled(PrintJobEvent pje) {
System.out.println("Canceled");
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
System.out.println("No more events");
}
public void printJobRequiresAttention(PrintJobEvent pje) {
System.out.println("Job requires attention");
PrinterStateReasons psr = pje.getPrintJob().getPrintService().getAttribute(PrinterStateReasons.class);
if (psr != null) {
Set<PrinterStateReason> errors = psr.printerStateReasonSet(Severity.REPORT);
for (PrinterStateReason reason : errors)
System.out.printf(" Reason : %s",reason.getName());
System.out.println();
}
}
public DocFlavor getDocFlavor() {
return DocFlavor.SERVICE_FORMATTED.PRINTABLE; //To change body of implemented methods use File | Settings | File Templates.
}
public Object getPrintData() throws IOException {
return this;
}
public DocAttributeSet getAttributes() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Reader getReaderForText() throws IOException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public InputStream getStreamForBytes() throws IOException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
return pageIndex == 0 ? PAGE_EXISTS : NO_SUCH_PAGE; //To change body of implemented methods use File | Settings | File Templates.
}
public void attributeUpdate(PrintJobAttributeEvent pjae) {
System.out.println("Look out");
}
}
So, the method that interest me is this:
public void printJobCompleted(PrintJobEvent pje) {
System.out.println("Completed");
}
but it doesn't works for me. The issue is that the printer doesn't support this type of code. Can someone tell me a model of printer that support this code?
Look at the sample code here:
It looks like you need to implement your PrintJobAdapter. The relevant bits are:
package com.your.package;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
public class DetermineThatPrintJobHasFinished {
public static void main(String[] args) throws Exception {
//... see example in link
// Locate the default print service for this environment.
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
// Create and return a PrintJob capable of handling data from
// any of the supported document flavors.
DocPrintJob printJob = service.createPrintJob();
// register a listener to get notified when the job is complete
JobCompleteMonitor monitor = new JobCompleteMonitor();
printJob.addPrintJobListener(monitor);
// Construct a SimpleDoc with the specified print data, doc flavor and doc attribute set.
Doc doc = new SimpleDoc(is, flavor, null);
// Print a document with the specified job attributes.
printJob.print(doc, null);
monitor.waitForJobCompletion();
is.close();
}
private static class JobCompleteMonitor extends PrintJobAdapter {
private boolean completed = false;
#Override
public void printJobCanceled(PrintJobEvent pje) {
signalCompletion();
}
#Override
public void printJobCompleted(PrintJobEvent pje) {
signalCompletion();
}
#Override
public void printJobFailed(PrintJobEvent pje) {
signalCompletion();
}
#Override
public void printJobNoMoreEvents(PrintJobEvent pje) {
signalCompletion();
}
private void signalCompletion() {
synchronized (JobCompleteMonitor.this) {
completed = true;
JobCompleteMonitor.this.notify();
}
}
public synchronized void waitForJobCompletion() {
try {
while (!completed) {
wait();
}
} catch (InterruptedException e) {
}
}
}
}
it's not the best efficient but you could wait until the Attribute: 'queued-job-count' is equal to Zero :
public final static void waitEndJobs(final PrintService printService) throws InterruptedException {
int queue = 1;
while (queue != 0) {
final AttributeSet attributes = printService.getAttributes();
final Attribute a = Arrays.stream(attributes.toArray())//
.filter(o -> o.getName().equalsIgnoreCase("queued-job-count"))//
.findFirst()//
.orElse(null);
queue = Integer.parseInt(attributes.get(a.getClass()).toString());
Thread.sleep(5000);
}
}
To my point Rx or Project Reactor can very help with this old java printer api. I also have faced this problem recently, and currently I have finished on next version. maybe it will help to somebody
first, if you are using pdfbox as me, then
#Slf4j
#Service
#RequiredArgsConstructor
public class PrinterDeviceServiceImpl implements PrinterDeviceService {
#Override
public StreamEx<PrintService> getAvailablePrinters() {
return of(PrintServiceLookup.lookupPrintServices(null, null));
}
#Override
public boolean isPrinterExists(String printerName) {
return getAvailablePrinters()
.anyMatch(p -> p.getName().equals(printerName));
}
#Override
public PrintService getPrinter(String printerName) {
return getAvailablePrinters()
.findFirst(p -> p.getName().equals(printerName))
.orElse(null);
}
#Override
public Mono<PrintTaskStatus> print(String printerName, InputStream source) {
try {
PrintService printer = getPrinter(printerName);
if (printer == null) {
return Mono.error(new RuntimeException("printer is null"));
}
PDDocument document = Unchecked.supplier(() -> PDDocument.load(source));
PrinterJob job = PrinterJob.getPrinterJob();
job.setPageable(new PDFPageable(document, Orientation.PORTRAIT));
job.setPrintService(printer);
Paper paper = new Paper();
paper.setSize(500, 500); //TODO: lets get it from configs or task request
paper.setImageableArea(0.0, 0.0, paper.getWidth(), paper.getHeight()); // no margins
// custom page format
PageFormat pageFormat = new PageFormat();
pageFormat.setPaper(paper);
Book book = new Book();
book.append(new PDFPrintable(document), pageFormat, document.getNumberOfPages());
job.setPageable(book);
HashPrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
attr.add(OrientationRequested.PORTRAIT);
attr.add(PrintQuality.HIGH);
job.print(attr);
return Mono.create(sink -> {
/*If exec thread is UI or from http pool, then maybe better idea is to attach it to another independent one or run print in another one!*/
while (!isPrintCompleted(printer)) {
log.debug("I'm waiting to printer processed queue");
Unchecked.runnable(() -> Thread.sleep(1000));
}
/*you can wait some fixed or dynamic time based on how big your document etc and finish with error state if it needed*/
log.debug("printer queue have processed :)");
sink.success(PrintTaskStatus.Completed);
});
} catch (Throwable ex) {
ExceptionHelpers.logError(ex, log);
return Mono.just(PrintTaskStatus.Failed);
}
}
private boolean isPrintCompleted(PrintService printer) {
return Arrays.stream(printer.getAttributes().toArray())
.filter(att -> att instanceof QueuedJobCount)
.map(QueuedJobCount.class::cast)
.findFirst()
.map(queuedJobCount -> queuedJobCount.getValue() == 0)
.orElse(false);
}
}
second, if you are preferred only default printer api then replace print method to:
#Override
public Mono<PrintTaskStatus> print(String printerName, InputStream source) {
PrintService printer = getPrinter(printerName);
if (printer == null) {
return Mono.error(new RuntimeException("printer is null"));
}
try {
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
DocPrintJob printJob = printer.createPrintJob();
CustomPrintJobListener monitor = new CustomPrintJobListener();
printJob.addPrintJobListener(monitor);
Doc doc = new SimpleDoc(source, flavor, null);
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(OrientationRequested.PORTRAIT);
pras.add(PrintQuality.NORMAL);
pras.add(new Copies(1));
printJob.print(doc, pras);
return monitor.getJobMono();
} catch (Exception ex) {
ExceptionHelpers.logError(ex, log);
return Mono.just(PrintTaskStatus.Failed);
}
}
#Slf4j
private static class CustomPrintJobListener extends PrintJobAdapter {
private final EmitterProcessor<PrintTaskStatus> emitter = EmitterProcessor.create();
#Override
public void printJobCanceled(PrintJobEvent pje) {
emitter.onNext(PrintTaskStatus.Canceled);
log.info("Print job canceled :| ");
}
#Override
public void printDataTransferCompleted(PrintJobEvent pje) {
log.info("Print data transfer completed ;) ");
}
#Override
public void printJobCompleted(PrintJobEvent pje) {
emitter.onNext(PrintTaskStatus.Completed);
log.info("Print job completed :) ");
}
#Override
public void printJobFailed(PrintJobEvent pje) {
emitter.onNext(PrintTaskStatus.Failed);
log.info("Print job failed :( ");
}
#Override
public void printJobNoMoreEvents(PrintJobEvent pje) {
emitter.onNext(PrintTaskStatus.Completed);
log.info("No more events to the job :|");
}
#Override
public void printJobRequiresAttention(PrintJobEvent pje) {
log.info("Print job requires attention :O ");
}
public Mono<PrintTaskStatus> getJobMono() {
return emitter.next();
}
}
Good luck :)
Related
Why would this code be having memory issues? It runs fine once, and then when I try to run it again it hangs on "Enabling plugin". It'll then give me an OutOfMemoryException such as
"Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "Worker-Main-10""
The code I am using is as follows from the Spigot API
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Bat;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.UUID;
public class COVID19 extends JavaPlugin {
private static ArrayList<CovidInfection> infections;
#Override
public void onEnable() {
infections = new ArrayList<CovidInfection>();
System.out.println("1");
try {
readInfections();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
System.out.println("2");
this.getCommand("getInfected").setExecutor(new CommandGetInfected());
BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
#Override
public void run() {
batCovid();
}
}, 0, 10);
System.out.println(4);
}
#Override
public void onDisable() {
try {
writeInfections();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void batCovid() {
System.out.println(3);
for(Player player : Bukkit.getOnlinePlayers()) {
for(Entity nearby : player.getNearbyEntities(6, 6, 6)) {
if (nearby instanceof Bat) {
String name = player.getName();
UUID uuid = player.getUniqueId();
infections.add(new CovidInfection(uuid, name, 14));
}
}
}
}
public void readInfections() throws FileNotFoundException {
File file = new File("infected.txt");
if(file.length() == 0) {
return;
}
Scanner input = new Scanner(file);
String line = input.nextLine();
while (!(line.equals(""))) {
infections.add(parseInfectionLine(line));
}
input.close();
}
public void writeInfections() throws IOException {
//File will be written as UUID,Name,DaysRemaining
FileWriter writer = new FileWriter("infected.txt", false);
for(CovidInfection infection : infections) {
writer.write(infection.toString());
}
writer.close();
}
private CovidInfection parseInfectionLine(String line) {
String[] words = line.replace("\n","").split(",");
return new CovidInfection(UUID.fromString(words[0]), words[1], Integer.parseInt(words[2]));
}
public static String getInfected() {
String compiled = "";
for (CovidInfection infection : infections) {
compiled += infection.toString() + "\n";
}
return compiled;
}
}
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandGetInfected implements CommandExecutor {
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
String message = COVID19.getInfected();
if(!(message.equals(""))) {
sender.sendMessage(message);
} else {
sender.sendMessage("There are no infected!");
}
return(true);
}
}
import java.util.UUID;
public class CovidInfection {
private UUID uuid;
private String name;
private int days;
public CovidInfection(UUID uuid, String name, int days) {
this.uuid = uuid;
this.name = name;
this.days = days;
}
public int getDays() {
return days;
}
public String getName() {
return name;
}
public UUID getUuid() {
return uuid;
}
public void newDay() {
days--;
}
public String toString() {
return uuid.toString() + "," + name + "," + days + "\n";
}
}
Any help would be greatly appreciated, thank you!
Firstly, you are make I/O request on main thread.
To fix this issue, use multithreading such as explained here or here
Then, this :
Scanner input = new Scanner(file);
String line = input.nextLine();
Can't be used in a server.
An input like that already exist, it's the console sender.
To do that, I suggest you to use ServerCommandEvent and use spigot's console.
I am building a collection program in Java that collects data from websites using their apis. I am encountering this problem where it will hang on an http call. I tried to work around it by executing an http call over an executor service with a timeout. That doesn't seem to work as it would keep timing out and retrying. I figured it might be something to do with the API so after a retry I would reinitialize a whole new object per website API. Still no solution. I am trying to identify the root cause of this but can't seem to put my finger on it.
Here is a look at my flickr manager class that handles the calls to flickr.
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.scribe.exceptions.OAuthConnectionException;
import com.flickr4java.flickr.Flickr;
import com.flickr4java.flickr.FlickrException;
import com.flickr4java.flickr.FlickrRuntimeException;
import com.flickr4java.flickr.REST;
import com.flickr4java.flickr.RequestContext;
import com.flickr4java.flickr.auth.Auth;
import com.flickr4java.flickr.auth.Permission;
import com.flickr4java.flickr.people.User;
import com.flickr4java.flickr.photos.Exif;
import com.flickr4java.flickr.photos.Extras;
import com.flickr4java.flickr.photos.Photo;
import com.flickr4java.flickr.photos.PhotoList;
import com.flickr4java.flickr.photos.SearchParameters;
import com.flickr4java.flickr.photos.Size;
import com.google.common.util.concurrent.RateLimiter;
public class FlickrManager {
private final static Logger LOG = Logger.getLogger(FlickrManager.class.getName());
private final static ExecutorService executorService = Executors.newSingleThreadExecutor();
private Flickr flickr;
private final int MAX_PER_PAGE = 500;
private final RateLimiter rateLimiter;
private String ApiKey;
private String ApiSecret;
private String authToken;
private String authTokenSecret;
private Integer hostPort;
private String hostAddress;
private String httpScheme;
public FlickrManager(Flickr flickr, double apiCallsPerSecond) throws FlickrException {
this.flickr = flickr;
flickr.getTestInterface().echo(Collections.emptyMap());
//get flickr info to reinitialize flickr object if necessary
this.ApiKey = flickr.getApiKey();
this.ApiSecret = flickr.getSharedSecret();
this.hostPort = flickr.getTransport().getPort();
this.hostAddress = flickr.getTransport().getHost();
this.httpScheme = flickr.getTransport().getScheme();
if(flickr.getAuth() != null){
this.authToken = flickr.getAuth().getToken();
this.authTokenSecret = flickr.getAuth().getTokenSecret();
}
this.rateLimiter = RateLimiter.create(apiCallsPerSecond);
}
private void initialize(){
this.flickr = null;
REST rest = new REST(this.hostAddress,this.hostPort);
rest.setScheme(this.httpScheme);
this.flickr = new Flickr(this.ApiKey, this.ApiSecret,rest);
if(this.authToken != null && this.authTokenSecret != null){
RequestContext requestContext = RequestContext.getRequestContext();
Auth auth = new Auth();
auth.setPermission(Permission.READ);
auth.setToken(this.authToken);
auth.setTokenSecret(this.authTokenSecret);
requestContext.setAuth(auth);
flickr.setAuth(auth);
}
}
public User getUserInfo(String flickrProfileId) throws FlickrException{
return doFlickrAction(new CallableFlickrTask<User>(){
#Override
public User execute() throws FlickrException {
return flickr.getPeopleInterface().getInfo(flickrProfileId);
}
});
}
public PhotoList<Photo> search(SearchParameters params, int page) throws FlickrException{
return doFlickrAction(new CallableFlickrTask<PhotoList<Photo>>(){
#Override
public PhotoList<Photo> execute() throws FlickrException {
return flickr.getPhotosInterface().search(params, MAX_PER_PAGE, page);
}
});
}
public PhotoList<Photo> getUserPhotos(String userNSID, int page) throws FlickrException{
return doFlickrAction(new CallableFlickrTask<PhotoList<Photo>>(){
#Override
public PhotoList<Photo> execute() throws FlickrException {
return flickr.getPeopleInterface().getPhotos(
userNSID,
null, null, null, null, null,
Flickr.CONTENTTYPE_PHOTO, null,
Extras.ALL_EXTRAS, 100, page);
}
});
}
//Catch the execption inside the function for failure to get exif
public Collection<Exif> getPhotoExif(Photo photo) throws FlickrException, FlickrRuntimeException {
return doFlickrAction(new CallableFlickrTask<Collection<Exif>>(){
#Override
public Collection<Exif> execute() throws FlickrException {
return flickr.getPhotosInterface().getExif(photo.getId(),photo.getSecret());
}
});
}
public Collection<Size> getAvailablePhotoSizes(Photo photo) throws FlickrException{
return doFlickrAction(new CallableFlickrTask<Collection<Size>>(){
#Override
public Collection<Size> execute() throws FlickrException {
return flickr.getPhotosInterface().getSizes(photo.getId());
}
});
}
private abstract class CallableFlickrTask<T> {
public abstract T execute() throws FlickrException, FlickrRuntimeException;
}
private <T> T doFlickrAction(CallableFlickrTask<T> callable) throws FlickrException {
while(true){
rateLimiter.acquire();
Future<T> future = executorService.submit(new Callable<T>() {
#Override
public T call() throws Exception {
return callable.execute();
}});
try {
return future.get(5, TimeUnit.MINUTES);
} catch (InterruptedException e) {
LOG.log(Level.INFO,"Interrupted exception: {0}",e.getMessage());
initialize(); //initialize if it's been interupted
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if( cause instanceof UnknownHostException ||
cause instanceof SocketException ||
cause instanceof OAuthConnectionException ){
//sleep and retry
LOG.log(Level.INFO,"Unknown Host or Socket exception. Retry: {0}",e.getMessage());
try {
Thread.sleep(10000);
initialize();
} catch (InterruptedException ex) {
LOG.log(Level.INFO, "Thread sleep was interrupted exception: {0}", ex.getMessage());
}
}
//if it's not of the above exceptions, then rethrow
else if (cause instanceof FlickrException) {
throw (FlickrException) cause;
}
else {
throw new IllegalStateException(e);
}
} catch (TimeoutException e) {
LOG.log(Level.INFO,"Timeout Exception: {0}",e.getMessage());
initialize(); //initialize again after timeout
}
}
}
}
I also used jvisualvm to get a look at what the collection is doing while it's hanging. The thread dump is here: Thread dump
I want to print a PDF file to Zebra printer using a Java application. I have generated a PDF using Jasper reports with 2D bar codes. If I am performing manual print to Zebra printer it's printing that PDF file but once I am trying to print the same pdf file using the Java application, the job is submitting to printer but print is not happening.
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
public class ZebraPrintUtil {
public static void main(String[] args) throws IOException, InterruptedException {
byte[] content = convertFileToBytes("D://old files/test123.pdf");
print(content, "ZDesigner GX420t");
}
private static byte[] convertFileToBytes(String absoluteFilePath) throws IOException {
File file = new File(absoluteFilePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum;
(readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); // no doubt here is 0
}
} catch (IOException ex) {
} finally {
if (fis != null) {
fis.close();
}
}
byte[] bytes = bos.toByteArray();
return bytes;
}
private static boolean print(byte[] byteArray, String reqPrinterId)
throws IOException, InterruptedException {
boolean isPrintedSuccessfully = false;
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
PrintService[] services = PrintServiceLookup.lookupPrintServices(
flavor, null);
if (services.length > 0) {
PrintService myService = null;
for (PrintService service: services) {
if (service.getName().contains(reqPrinterId)) {
myService = service;
break;
}
}
DocPrintJob printJob = myService.createPrintJob();
JobCompleteMonitor monitor = new JobCompleteMonitor();
printJob.addPrintJobListener(monitor);
Doc document = new SimpleDoc(byteArray, flavor, null);
try {
printJob.print(document, null);
monitor.waitForJobCompletion();
System.out.println("-------------------- Print Completed " + monitor.completed);
isPrintedSuccessfully = true;
} catch (Exception e) {
e.printStackTrace();
}
}
return isPrintedSuccessfully;
}
private static class JobCompleteMonitor extends PrintJobAdapter {
private boolean completed = false;
#Override
public void printJobCanceled(PrintJobEvent pje) {
signalCompletion();
}
#Override
public void printJobCompleted(PrintJobEvent pje) {
signalCompletion();
}
#Override
public void printJobFailed(PrintJobEvent pje) {
signalCompletion();
}
#Override
public void printJobNoMoreEvents(PrintJobEvent pje) {
signalCompletion();
}
private void signalCompletion() {
synchronized(JobCompleteMonitor.this) {
completed = true;
JobCompleteMonitor.this.notify();
}
}
public synchronized void waitForJobCompletion() {
try {
while (!completed) {
wait();
}
} catch (InterruptedException e) {
}
}
}
}
For Desktop integration:
File file = ...
if (Desktop.isDesktopAvailable()) {
Desktop.getDesktop().print(file);
}
I used Pramod code but before that I have to pass my printer id that is name of printer. I am getting byte array from my db.
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.DocFlavor;
try {
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.GIF, pras);
if (pss.length == 0)
throw new RuntimeException("No printer services available.");
//You have to check which printer you want to print.
PrintService ps = pss[1];
logger.info("Printing to " + ps);
//Here I am calling Pramod method.
boolean result = PrintPDF.print(byteArray, ps.getName());
logger.info("result " + result);
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
This is not answer, this code will call Pramod method which is precise solution.
Thanks
I am working with JADE ( Java Agent Development framework), and I am trying to write a behavior which makes an agent moving from container to another. I tried this command:
public void action() {
ACLMessage msg = myAgent.receive(template);
if (msg != null) {
moveRequest = msg;
String destination =
doMove(new ContainerID(destination, null));
}
else {
block();
}
}
but it seems that I have a failure in moving:
jade.core.mobility.AgentMobilityService$CommandSourceSink handleInformMoved Grave: Mobility protocol not supported. Aborting transfer
It will be better if I get the source code for a complete behavior.
Thanks in advance
this is the code to start the jade platform:
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.core.Runtime;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;
public class Run {
public Run() {
Runtime rt = Runtime.instance();
rt.setCloseVM(true);
AgentContainer mc = rt.createMainContainer(new ProfileImpl());
Profile p = new ProfileImpl();
p.setParameter("container-name", "Foo");
AgentContainer ac = rt.createAgentContainer(p);
try{
AgentController rma = mc.createNewAgent("rma", "jade.tools.rma.rma", null);
rma.start();
AgentController ma = mc.createNewAgent("MA", "MobileAgent", null);
ma.start();
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
new Run();
}
}
And this is the code for the mobile agent. After being created, the agent moves immediately to the container Foo.
import jade.core.Agent;
import jade.core.Location;
public class MobileAgent extends Agent {
private static final long serialVersionUID = 1L;
#Override
protected void setup() {
System.out.println("Hello World");
Location destination = new jade.core.ContainerID("Foo", null);
doMove(destination);
super.setup();
}
#Override
protected void beforeMove() {
System.out.println("Preparing to move");
super.beforeMove();
}
#Override
protected void afterMove() {
System.out.println("Arrived to destination");
super.afterMove();
}
}
Can someone please provide me very simple example of websocket client using javax.websocket?
I want to connect to websocket (ws://socket.example.com:1234), send message (add channel) and listen to messages. All messages (sent & listened) are in JSON format.
And btw is this library the best for simple websocket communication?
I've found a great example using javax.websocket here:
http://www.programmingforliving.com/2013/08/jsr-356-java-api-for-websocket-client-api.html
Here the code based on the example linked above:
TestApp.java:
package testapp;
import java.net.URI;
import java.net.URISyntaxException;
public class TestApp {
public static void main(String[] args) {
try {
// open websocket
final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(new URI("wss://real.okcoin.cn:10440/websocket/okcoinapi"));
// add listener
clientEndPoint.addMessageHandler(new WebsocketClientEndpoint.MessageHandler() {
public void handleMessage(String message) {
System.out.println(message);
}
});
// send message to websocket
clientEndPoint.sendMessage("{'event':'addChannel','channel':'ok_btccny_ticker'}");
// wait 5 seconds for messages from websocket
Thread.sleep(5000);
} catch (InterruptedException ex) {
System.err.println("InterruptedException exception: " + ex.getMessage());
} catch (URISyntaxException ex) {
System.err.println("URISyntaxException exception: " + ex.getMessage());
}
}
}
WebsocketClientEndpoint.java:
package testapp;
import java.net.URI;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
/**
* ChatServer Client
*
* #author Jiji_Sasidharan
*/
#ClientEndpoint
public class WebsocketClientEndpoint {
Session userSession = null;
private MessageHandler messageHandler;
public WebsocketClientEndpoint(URI endpointURI) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, endpointURI);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Callback hook for Connection open events.
*
* #param userSession the userSession which is opened.
*/
#OnOpen
public void onOpen(Session userSession) {
System.out.println("opening websocket");
this.userSession = userSession;
}
/**
* Callback hook for Connection close events.
*
* #param userSession the userSession which is getting closed.
* #param reason the reason for connection close
*/
#OnClose
public void onClose(Session userSession, CloseReason reason) {
System.out.println("closing websocket");
this.userSession = null;
}
/**
* Callback hook for Message Events. This method will be invoked when a client send a message.
*
* #param message The text message
*/
#OnMessage
public void onMessage(String message) {
if (this.messageHandler != null) {
this.messageHandler.handleMessage(message);
}
}
#OnMessage
public void onMessage(ByteBuffer bytes) {
System.out.println("Handle byte buffer");
}
/**
* register message handler
*
* #param msgHandler
*/
public void addMessageHandler(MessageHandler msgHandler) {
this.messageHandler = msgHandler;
}
/**
* Send a message.
*
* #param message
*/
public void sendMessage(String message) {
this.userSession.getAsyncRemote().sendText(message);
}
/**
* Message handler.
*
* #author Jiji_Sasidharan
*/
public static interface MessageHandler {
public void handleMessage(String message);
}
}
TooTallNate has a simple client side https://github.com/TooTallNate/Java-WebSocket
Just add the java_websocket.jar in the dist folder into your project.
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_10;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;
WebSocketClient mWs = new WebSocketClient( new URI( "ws://socket.example.com:1234" ), new Draft_10() )
{
#Override
public void onMessage( String message ) {
JSONObject obj = new JSONObject(message);
String channel = obj.getString("channel");
}
#Override
public void onOpen( ServerHandshake handshake ) {
System.out.println( "opened connection" );
}
#Override
public void onClose( int code, String reason, boolean remote ) {
System.out.println( "closed connection" );
}
#Override
public void onError( Exception ex ) {
ex.printStackTrace();
}
};
//open websocket
mWs.connect();
JSONObject obj = new JSONObject();
obj.put("event", "addChannel");
obj.put("channel", "ok_btccny_ticker");
String message = obj.toString();
//send message
mWs.send(message);
// and to close websocket
mWs.close();
Have a look at this Java EE 7 examples from Arun Gupta.
I forked it on github.
Main
/**
* #author Arun Gupta
*/
public class Client {
final static CountDownLatch messageLatch = new CountDownLatch(1);
public static void main(String[] args) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "ws://echo.websocket.org:80/";
System.out.println("Connecting to " + uri);
container.connectToServer(MyClientEndpoint.class, URI.create(uri));
messageLatch.await(100, TimeUnit.SECONDS);
} catch (DeploymentException | InterruptedException | IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
ClientEndpoint
/**
* #author Arun Gupta
*/
#ClientEndpoint
public class MyClientEndpoint {
#OnOpen
public void onOpen(Session session) {
System.out.println("Connected to endpoint: " + session.getBasicRemote());
try {
String name = "Duke";
System.out.println("Sending message to endpoint: " + name);
session.getBasicRemote().sendText(name);
} catch (IOException ex) {
Logger.getLogger(MyClientEndpoint.class.getName()).log(Level.SEVERE, null, ex);
}
}
#OnMessage
public void processMessage(String message) {
System.out.println("Received message in client: " + message);
Client.messageLatch.countDown();
}
#OnError
public void processError(Throwable t) {
t.printStackTrace();
}
}
Use this library org.java_websocket
First thing you should import that library in build.gradle
repositories {
mavenCentral()
}
then add the implementation in dependency{}
implementation "org.java-websocket:Java-WebSocket:1.3.0"
Then you can use this code
In your activity declare object for Websocketclient like
private WebSocketClient mWebSocketClient;
then add this method for callback
private void ConnectToWebSocket() {
URI uri;
try {
uri = new URI("ws://your web socket url");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
}
#Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = (TextView)findViewById(R.id.edittext_chatbox);
textView.setText(textView.getText() + "\n" + message);
}
});
}
#Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
#Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
I have Spring 4.2 in my project and many SockJS Stomp implementations usually work well with Spring Boot implementations. This implementation from Baeldung worked(for me without changing from Spring 4.2 to 5). After Using the dependencies mentioned in his blog, it still gave me ClassNotFoundError. I added the below dependency to fix it.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
Here is such a solution from - com.neovisionary.ws.client.Web socket - https://github.com/TakahikoKawasaki/nv-websocket-client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFactory;
import com.neovisionaries.ws.client.WebSocketFrame;
public class WssM {
public static List<String> ListMessage = new ArrayList<>();
public static boolean WebSocketLog = true;
public static final String WssURL = "wss://site.com/api/sport_tree_ws/v1";
public static final String WebsocketMessage = "{\"type\": \"subscribe_state\", \"subscribe_state\": {\"uid\": \"-1\"}}";
public static void main(String[] args) throws IOException, WebSocketException {
WebSocket socket = connect(WssURL);
BufferedReader in = getInput();
socket.sendText(WebsocketMessage);
String text;
try {
while ((text = in.readLine()) != null) {
if (text.equals("exit")) break;
if (!socket.isOpen()) {
System.out.println("Socket is closed. Trying to reconnect...");
socket.recreate().connect();
System.out.println("Reconnected!");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket.isOpen()) {
System.out.println("Disconnecting connection to server!");
socket.disconnect(); //Close the WebSocket.
}
}
}
private static WebSocket connect(String Host) throws IOException, WebSocketException {
WebSocketFactory wsFactory = new WebSocketFactory().setConnectionTimeout(55000);
WebSocket socket = wsFactory.createSocket(URI.create(Host)).addProtocol("json");//.addHeader("Sec-WebSocket-Protocol", "json")
//WebSocket socket = wsFactory.createSocket(URI.create(HOST + "?Authorization=" + DUMMY_JWT_TOKEN));
socket.addListener(new WebSocketAdapter() {
#Override
public void onSendingHandshake(WebSocket websocket, String requestLine, List<String[]> headers) {
if (WebSocketLog) System.out.println(requestLine);
for (String[] header : headers) { //Print the header, "{name}: {value}"
if (WebSocketLog) System.out.format("%s: %s\n", header[0], header[1]);
}
}
#Override
public void onConnected(WebSocket websocket, Map<String, List<String>> headers) {
if (WebSocketLog) System.out.println("Success! WebSocket - Connected!");
}
#Override
public void onTextMessage(WebSocket websocket, String text) {
if (WebSocketLog) System.out.printf("MessageToClient: %s%n", text); ListMessage.add(text);
}
#Override
public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) {
if (WebSocketLog) System.out.println("Disconnecting...");
if (WebSocketLog) System.out.printf(" Opcode: %d%n", serverCloseFrame.getOpcode());
}
#Override
public void onPongFrame(WebSocket websocket, WebSocketFrame frame) {
if (WebSocketLog) System.out.printf("Received some pong..!! Payload text: %s%n", frame.getPayloadText());
System.out.printf(" Opcode: %d%n", frame.getOpcode());
}
#Override
public void onPingFrame(WebSocket websocket, WebSocketFrame frame) {
if (WebSocketLog) System.out.printf("I have been pinged by server at %s%n", LocalDateTime.now());
websocket.sendPong("Ponging from client");
}
#Override
public void onTextFrame(WebSocket websocket, WebSocketFrame frame) {
if (WebSocketLog) System.out.printf("onTextFrame - %s%n", LocalDateTime.now());
websocket.sendPong("onTextFrame from client");
}
#Override
public void onError(WebSocket websocket, WebSocketException cause) {
System.out.printf("I have received exception %s%n", cause.getMessage());
}
}).connect();
return socket;
}
private static BufferedReader getInput() {
return new BufferedReader(new InputStreamReader(System.in));
}
}