Example usage for javax.print PrintService getName

List of usage examples for javax.print PrintService getName

Introduction

In this page you can find the example usage for javax.print PrintService getName.

Prototype

public String getName();

Source Link

Document

Returns a string name for this print service which may be used by applications to request a particular print service.

Usage

From source file:PrintServiceWebInterface.java

public static void main(String[] args) throws IOException {
    // Get the character encoders and decoders we'll need
    Charset charset = Charset.forName("ISO-8859-1");
    CharsetEncoder encoder = charset.newEncoder();

    // The HTTP headers we send back to the client are fixed
    String headers = "HTTP/1.1 200 OK\r\n" + "Content-type: text/html\r\n" + "Connection: close\r\n" + "\r\n";

    // We'll use two buffers in our response. One holds the fixed
    // headers, and the other holds the variable body of the response.
    ByteBuffer[] buffers = new ByteBuffer[2];
    buffers[0] = encoder.encode(CharBuffer.wrap(headers));
    ByteBuffer body = ByteBuffer.allocateDirect(16 * 1024);
    buffers[1] = body;/*from   ww  w  .j  a  va  2  s  .co  m*/

    // Find all available PrintService objects to describe
    PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);

    // All of the channels we use in this code will be in non-blocking
    // mode. So we create a Selector object that will block while
    // monitoring all of the channels and will only stop blocking when
    // one or more of the channels is ready for I/O of some sort.
    Selector selector = Selector.open();

    // Create a new ServerSocketChannel, and bind it to port 8000.
    // Note that we have to do this using the underlying ServerSocket.
    ServerSocketChannel server = ServerSocketChannel.open();
    server.socket().bind(new java.net.InetSocketAddress(8000));

    // Put the ServerSocketChannel into non-blocking mode
    server.configureBlocking(false);

    // Now register the channel with the Selector. The SelectionKey
    // represents the registration of this channel with this Selector.
    SelectionKey serverkey = server.register(selector, SelectionKey.OP_ACCEPT);

    for (;;) { // The main server loop. The server runs forever.
        // This call blocks until there is activity on one of the
        // registered channels. This is the key method in non-blocking I/O.
        selector.select();

        // Get a java.util.Set containing the SelectionKey objects for
        // all channels that are ready for I/O.
        Set keys = selector.selectedKeys();

        // Use a java.util.Iterator to loop through the selected keys
        for (Iterator i = keys.iterator(); i.hasNext();) {
            // Get the next SelectionKey in the set, and then remove it
            // from the set. It must be removed explicitly, or it will
            // be returned again by the next call to select().
            SelectionKey key = (SelectionKey) i.next();
            i.remove();

            // Check whether this key is the SelectionKey we got when
            // we registered the ServerSocketChannel.
            if (key == serverkey) {
                // Activity on the ServerSocketChannel means a client
                // is trying to connect to the server.
                if (key.isAcceptable()) {
                    // Accept the client connection, and obtain a
                    // SocketChannel to communicate with the client.
                    SocketChannel client = server.accept();

                    // Make sure we actually got a connection
                    if (client == null)
                        continue;

                    // Put the client channel in non-blocking mode.
                    client.configureBlocking(false);

                    // Now register the client channel with the Selector,
                    // specifying that we'd like to know when there is
                    // data ready to read on the channel.
                    SelectionKey clientkey = client.register(selector, SelectionKey.OP_READ);
                }
            } else {
                // If the key we got from the Set of keys is not the
                // ServerSocketChannel key, then it must be a key
                // representing one of the client connections.
                // Get the channel from the key.
                SocketChannel client = (SocketChannel) key.channel();

                // If we got here, it should mean that there is data to
                // be read from the channel, but we double-check here.
                if (!key.isReadable())
                    continue;

                // Now read bytes from the client. We assume that
                // we get all the client's bytes in one read operation
                client.read(body);

                // The data we read should be some kind of HTTP GET
                // request. We don't bother checking it however since
                // there is only one page of data we know how to return.
                body.clear();

                // Build an HTML document as our reponse.
                // The body of the document contains PrintService details
                StringBuffer response = new StringBuffer();
                response.append(
                        "<html><head><title>Printer Status</title></head>" + "<body><h1>Printer Status</h1>");
                for (int s = 0; s < services.length; s++) {
                    PrintService service = services[s];
                    response.append("<h2>").append(service.getName()).append("</h2><table>");
                    Attribute[] attrs = service.getAttributes().toArray();
                    for (int a = 0; a < attrs.length; a++) {
                        Attribute attr = attrs[a];
                        response.append("<tr><td>").append(attr.getName()).append("</td><td>").append(attr)
                                .append("</tr>");
                    }
                    response.append("</table>");
                }
                response.append("</body></html>\r\n");

                // Encode the response into the body ByteBuffer
                encoder.reset();
                encoder.encode(CharBuffer.wrap(response), body, true);
                encoder.flush(body);

                body.flip(); // Prepare the body buffer to be drained
                // While there are bytes left to write
                while (body.hasRemaining()) {
                    // Write both header and body buffers
                    client.write(buffers);
                }
                buffers[0].flip(); // Prepare header buffer for next write
                body.clear(); // Prepare body buffer for next read

                // Once we've sent our response, we have no more interest
                // in the client channel or its SelectionKey
                client.close(); // Close the channel.
                key.cancel(); // Tell Selector to stop monitoring it.
            }
        }
    }
}

From source file:com.floreantpos.jasperreport.engine.print.JRPrinterAWT.java

/**
 * Fix for bug ID 6255588 from Sun bug database
 * @param job print job that the fix applies to
 *///from w w  w  .j a  v  a2s . c om
public static void initPrinterJobFields(PrinterJob job) {
    try {
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        PrintService printService = PrintServiceLookup.lookupDefaultPrintService();

        for (int i = 0; i < printServices.length; i++) {
            PrintService service = printServices[i];
            if (service.getName().equals(printerName)) {
                printService = service;
                break;
            }
        }

        job.setPrintService(printService);
    } catch (PrinterException e) {
    }
}

From source file:Print.java

public static void print(String printerName, String filename, PrintRequestAttributeSet attributes)
        throws IOException {
    // Look for a printer that can support the attributes
    PrintService service = getNamedPrinter(printerName, attributes);
    if (service == null) {
        System.out.println("Can't find a printer " + "with specified attributes");
        return;/*from   w ww  .  j av a 2 s .c o m*/
    }
    // Print the file to that printer. See method definition below
    printToService(service, filename, attributes);
    // Let the user know where to pick up their printout
    System.out.println("Printed " + filename + " to " + service.getName());
}

From source file:org.obiba.onyx.print.PdfPrintingService.java

public void afterPropertiesSet() throws Exception {
    // Try to find a PrintService instance with the specified name if any
    if (printerName != null && printerName.length() > 0) {
        log.info("Looking for a printer named '{}'", printerName);
        // Lookup all services
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        for (PrintService ps : printServices) {
            if (ps.getName().equalsIgnoreCase(printerName)) {
                log.info("Using printer '{}'", ps.getName());
                this.printService = ps;
                break;
            }// w w w.  jav  a  2s  .c o m
        }
        if (printService == null) {
            log.warn("Could not find printer with name '{}'. Will try default printer.", printerName);
        }
    }

    // If the printService is null, we weren't configured with a printerName or we couldn't
    // find one with the specified name
    if (printService == null) {
        printService = PrintServiceLookup.lookupDefaultPrintService();
        if (printService != null) {
            log.info("Using default printer '{}'.", printService.getName());
        }
    }

    // If the printService is null, there is no default printer installed.
    if (printService == null) {
        log.warn("No default printer found. Printing will not be available.");
    } else {
        // We have a PrintService instance. Find the first handler that this service accepts.
        for (PdfHandler handler : IMPLEMENTED_FLAVORS) {
            if (printService.isDocFlavorSupported(handler.getImplementedFlavor())) {
                supportedHandler = handler;
                break;
            }
        }

        if (supportedHandler != null) {
            log.info("Printer '{}' supports PDF printing through handler {}. PDF printing will be available.",
                    printService.getName(), supportedHandler.getClass().getSimpleName());
        } else {
            log.warn(
                    "Printer '{}' does not support printing PDF files directly. PDF printing will not be available.",
                    printService.getName());
            printService = null;
        }
    }
}

From source file:ru.trett.cis.services.PrinterServiceImpl.java

@Override
public String print(String file) throws ApplicationException, FileNotFoundException, PrintException {
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    aset.add(MediaSizeName.ISO_A4);
    PrintService printServices = PrintServiceLookup.lookupDefaultPrintService();
    if (printServices == null)
        throw new ApplicationException("Default printer not found");
    LOGGER.info("Default printer is " + printServices.getName());
    DocPrintJob printJob = printServices.createPrintJob();
    FileInputStream fis = new FileInputStream(file);
    Doc doc = new SimpleDoc(fis, flavor, null);
    printJob.print(doc, aset);/*from  w  ww  .j av  a  2 s  .c  om*/
    return printServices.getName();
}

From source file:net.sf.jasperreports.engine.print.JRPrinterAWT.java

/**
 *
 *//*from  w  ww  . j  a v  a2  s. c o m*/
public boolean printPages(int firstPageIndex, int lastPageIndex, boolean withPrintDialog) throws JRException {
    boolean isOK = true;

    if (firstPageIndex < 0 || firstPageIndex > lastPageIndex
            || lastPageIndex >= jasperPrint.getPages().size()) {
        throw new JRException("Invalid page index range : " + firstPageIndex + " - " + lastPageIndex + " of "
                + jasperPrint.getPages().size());
    }

    pageOffset = firstPageIndex;

    PrinterJob printJob = PrinterJob.getPrinterJob();

    // fix for bug ID 6255588 from Sun bug database
    initPrinterJobFields(printJob);
    if (jasperPrint.getProperty("printService") != null) {
        String printServiceName = jasperPrint.getProperty("printService");
        try {
            PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
            for (PrintService se : services) {
                if (se.getName().contains(printServiceName)) {
                    printJob.setPrintService(se);
                    break;
                }
            }

        } catch (PrinterException ex) {
            Logger.getLogger(JRPrinterAWT.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    PageFormat pageFormat = printJob.defaultPage();
    Paper paper = pageFormat.getPaper();

    printJob.setJobName("JasperReports - " + jasperPrint.getName());

    switch (jasperPrint.getOrientationValue()) {
    case LANDSCAPE: {
        pageFormat.setOrientation(PageFormat.LANDSCAPE);
        paper.setSize(jasperPrint.getPageHeight(), jasperPrint.getPageWidth());
        paper.setImageableArea(0, 0, jasperPrint.getPageHeight(), jasperPrint.getPageWidth());
        break;
    }
    case PORTRAIT:
    default: {
        pageFormat.setOrientation(PageFormat.PORTRAIT);
        paper.setSize(jasperPrint.getPageWidth(), jasperPrint.getPageHeight());
        paper.setImageableArea(0, 0, jasperPrint.getPageWidth(), jasperPrint.getPageHeight());
    }
    }

    pageFormat.setPaper(paper);

    Book book = new Book();
    book.append(this, pageFormat, lastPageIndex - firstPageIndex + 1);
    printJob.setPageable(book);
    try {
        if (withPrintDialog) {
            if (printJob.printDialog()) {
                printJob.print();
            } else {
                isOK = false;
            }
        } else {
            printJob.print();
        }
    } catch (Exception ex) {
        throw new JRException("Error printing report.", ex);
    }

    return isOK;
}

From source file:com.floreantpos.config.ui.AddPrinterDialog.java

public void setPrinter(Printer printer) {
    this.printer = printer;
    this.virtualPrinter = printer.getVirtualPrinter();

    tfName.setText(printer.getVirtualPrinter().getName());
    if (printer != null) {
        cbVirtualPrinter.setSelectedItem(printer.getVirtualPrinter());
        chckbxDefault.setSelected(printer.isDefaultPrinter());

        if (printer.getDeviceName() == "No Print") {
            cbDevice.setSelectedItem(DO_NOT_PRINT);
            return;
        }// ww  w .  j a  v  a  2  s.co m
        ComboBoxModel deviceModel = (ComboBoxModel) cbDevice.getModel();
        for (int i = 0; i < deviceModel.getSize(); i++) {
            Object selectedObject = deviceModel.getElementAt(i);
            if (!(selectedObject instanceof PrintService))
                continue;
            PrintService printService = (PrintService) selectedObject;
            if (printService != null)
                if (printService.getName().equals(printer.getDeviceName())) {
                    cbDevice.setSelectedIndex(i);
                    break;
                }

        }
    }
}

From source file:com.akman.enjoyfood.SelectPrinters.java

/**
 * This method get all the printer installed in the system. Add then into
 * JTable./*from  w w  w  .  j av  a  2 s .  co  m*/
 */
public void getPrinters() {

    model.setRowCount(0);

    DocFlavor doc_flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
    PrintRequestAttributeSet attr_set = new HashPrintRequestAttributeSet();

    PrintService[] service = PrintServiceLookup.lookupPrintServices(doc_flavor, attr_set);
    for (PrintService printService : service) {

        PrintServiceAttributeSet printServiceAttributes = printService.getAttributes();
        PrinterState printerState = (PrinterState) printServiceAttributes.get(PrinterState.class);

        if (printService != null) {
            Object row[] = { new Printer(printService.getName(), true), "Online" };
            model.addRow(row);
        } else {
            Object row[] = { new Printer(printService.getName(), true), "Offline" };
            model.addRow(row);
        }
    }

}

From source file:de.cenote.jasperstarter.App.java

private void listPrinters() {
    PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
    System.out.println("Default printer:");
    System.out.println("-----------------");
    System.out.println((defaultService == null) ? "--- not set ---" : defaultService.getName());
    System.out.println("");
    PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
    System.out.println("Available printers:");
    System.out.println("--------------------");
    for (PrintService service : services) {
        System.out.println(service.getName());
    }//from  www .ja  v a2s.com
}

From source file:com.floreantpos.config.ui.AddPrinterDialog.java

protected void doAddPrinter() {
    /*VirtualPrinter vp = (VirtualPrinter) cbVirtualPrinter.getSelectedItem();
    if (vp == null) {/*from   w w w  .  j  a  v  a  2s .co m*/
       POSMessageDialog.showError(this, Messages.getString("AddPrinterDialog.18")); //$NON-NLS-1$
       return;
    }*/
    String name = tfName.getText();
    if (StringUtils.isEmpty(name)) {
        POSMessageDialog.showMessage(this, Messages.getString("VirtualPrinterConfigDialog.11")); //$NON-NLS-1$
        return;
    }

    if (virtualPrinter == null) {
        virtualPrinter = new VirtualPrinter();
    }

    virtualPrinter.setName(name);

    PrintService printService = null;
    Object selectedObject = cbDevice.getSelectedItem();
    if (selectedObject instanceof PrintService) {
        /*POSMessageDialog.showMessage(this, Messages.getString("AddPrinterDialog.19")); //$NON-NLS-1$
        return;*/
        printService = (PrintService) selectedObject;
    }

    boolean defaultPrinter = chckbxDefault.isSelected();

    if (printer == null) {
        printer = new Printer();
    }
    printer.setVirtualPrinter(virtualPrinter);
    if (printService != null && printService.getName() != null) {
        printer.setDeviceName(printService.getName());
    } else {
        printer.setDeviceName(null);
    }
    printer.setDefaultPrinter(defaultPrinter);

    setCanceled(false);
    dispose();
}