Java Examples for javax.print.PrintServiceLookup

The following java examples will help you to understand the usage of javax.print.PrintServiceLookup. These source code samples are taken from different open source projects.

Example 1
Project: RipplePower-master  File: PrintDirectFunction.java View source code
@Override
public boolean print() {
    if (df == null) {
        return false;
    } else {
        try {
            PrintRequestAttributeSet requestAttributeSet = new HashPrintRequestAttributeSet();
            requestAttributeSet.add(MediaSizeName.ISO_A4);
            requestAttributeSet.add(new JobName(LSystem.applicationName + "-" + LSystem.getTime(), Locale.ENGLISH));
            PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
            DocPrintJob job = defaultService.createPrintJob();
            if (df == DocFlavor.SERVICE_FORMATTED.PRINTABLE) {
                doc = new SimpleDoc(new BufferedImagePrintable(path), df, null);
                requestAttributeSet.add(new PageRanges("1"));
            } else {
                FileInputStream fin = new FileInputStream(path);
                doc = new SimpleDoc(fin, df, null);
            }
            job.print(doc, requestAttributeSet);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
Example 2
Project: jdk7u-jdk-master  File: RasterPrinterJob.java View source code
/*
     * A convenience method which returns the default service
     * for 2D <code>PrinterJob</code>s.
     * May return null if there is no suitable default (although there
     * may still be 2D services available).
     * @return default 2D print service, or null.
     * @since     1.4
     */
protected static PrintService lookupDefaultPrintService() {
    PrintService service = PrintServiceLookup.lookupDefaultPrintService();
    /* Pageable implies Printable so checking both isn't strictly needed */
    if (service != null && service.isDocFlavorSupported(DocFlavor.SERVICE_FORMATTED.PAGEABLE) && service.isDocFlavorSupported(DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
        return service;
    } else {
        PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
        if (services.length > 0) {
            return services[0];
        }
    }
    return null;
}
Example 3
Project: Lucee-master  File: GetPrinterList.java View source code
public static String call(PageContext pc, String delimiter) {
    if (delimiter == null)
        delimiter = ",";
    StringBuilder sb = new StringBuilder();
    PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
    for (int i = 0; i < services.length; i++) {
        if (i > 0)
            sb.append(delimiter);
        sb.append(services[i].getName());
    }
    return sb.toString();
}
Example 4
Project: micro-Blagajna-master  File: ReportUtils.java View source code
/**
     *
     * @param printername
     * @return
     */
public static PrintService getPrintService(String printername) {
    if (printername == null) {
        return PrintServiceLookup.lookupDefaultPrintService();
    } else {
        if ("(Show dialog)".equals(printername)) {
            // null means "you have to show the print dialog"
            return null;
        } else if ("(Default)".equals(printername)) {
            return PrintServiceLookup.lookupDefaultPrintService();
        } else {
            PrintService[] pservices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
            for (PrintService s : pservices) {
                if (printername.equals(s.getName())) {
                    return s;
                }
            }
            return PrintServiceLookup.lookupDefaultPrintService();
        }
    }
}
Example 5
Project: micro-Blagajna-v1.x-master  File: ReportUtils.java View source code
/**
     *
     * @param printername
     * @return
     */
public static PrintService getPrintService(String printername) {
    if (printername == null) {
        return PrintServiceLookup.lookupDefaultPrintService();
    } else {
        if ("(Show dialog)".equals(printername)) {
            // null means "you have to show the print dialog"
            return null;
        } else if ("(Default)".equals(printername)) {
            return PrintServiceLookup.lookupDefaultPrintService();
        } else {
            PrintService[] pservices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
            for (PrintService s : pservices) {
                if (printername.equals(s.getName())) {
                    return s;
                }
            }
            return PrintServiceLookup.lookupDefaultPrintService();
        }
    }
}
Example 6
Project: Nor-master  File: ReportUtils.java View source code
public static PrintService getPrintService(String printername) {
    if (printername == null) {
        return PrintServiceLookup.lookupDefaultPrintService();
    } else {
        if ("(Show dialog)".equals(printername)) {
            // null means "you have to show the print dialog"
            return null;
        } else if ("(Default)".equals(printername)) {
            return PrintServiceLookup.lookupDefaultPrintService();
        } else {
            PrintService[] pservices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
            for (PrintService s : pservices) {
                if (printername.equals(s.getName())) {
                    return s;
                }
            }
            return PrintServiceLookup.lookupDefaultPrintService();
        }
    }
}
Example 7
Project: nordpos-master  File: ReportUtils.java View source code
public static PrintService getPrintService(String printername) {
    if (printername == null) {
        return PrintServiceLookup.lookupDefaultPrintService();
    } else {
        if ("(Show dialog)".equals(printername)) {
            // null means "you have to show the print dialog"
            return null;
        } else if ("(Default)".equals(printername)) {
            return PrintServiceLookup.lookupDefaultPrintService();
        } else {
            PrintService[] pservices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
            for (PrintService s : pservices) {
                if (printername.equals(s.getName())) {
                    return s;
                }
            }
            return PrintServiceLookup.lookupDefaultPrintService();
        }
    }
}
Example 8
Project: Openbravo-2B-master  File: ReportUtils.java View source code
public static PrintService getPrintService(String printername) {
    if (printername == null) {
        return PrintServiceLookup.lookupDefaultPrintService();
    } else {
        if ("(Show dialog)".equals(printername)) {
            // null means "you have to show the print dialog"
            return null;
        } else if ("(Default)".equals(printername)) {
            return PrintServiceLookup.lookupDefaultPrintService();
        } else {
            PrintService[] pservices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
            for (PrintService s : pservices) {
                if (printername.equals(s.getName())) {
                    return s;
                }
            }
            return PrintServiceLookup.lookupDefaultPrintService();
        }
    }
}
Example 9
Project: Openbravo-POS-master  File: ReportUtils.java View source code
public static PrintService getPrintService(String printername) {
    if (printername == null) {
        return PrintServiceLookup.lookupDefaultPrintService();
    } else {
        if ("(Show dialog)".equals(printername)) {
            // null means "you have to show the print dialog"
            return null;
        } else if ("(Default)".equals(printername)) {
            return PrintServiceLookup.lookupDefaultPrintService();
        } else {
            PrintService[] pservices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
            for (PrintService s : pservices) {
                if (printername.equals(s.getName())) {
                    return s;
                }
            }
            return PrintServiceLookup.lookupDefaultPrintService();
        }
    }
}
Example 10
Project: openjdk-master  File: WPrinterJob.java View source code
@Override
public PrintService getPrintService() {
    if (myService == null) {
        String printerName = getNativePrintService();
        if (printerName != null) {
            myService = PrintServiceLookupProvider.getWin32PrintLUS().getPrintServiceByName(printerName);
            // currently set in native
            if (myService != null) {
                return myService;
            }
        }
        myService = PrintServiceLookup.lookupDefaultPrintService();
        if (myService instanceof Win32PrintService) {
            try {
                setNativePrintServiceIfNeeded(myService.getName());
            } catch (Exception e) {
                myService = null;
            }
        }
    }
    return myService;
}
Example 11
Project: openjdk8-jdk-master  File: WPrinterJob.java View source code
public PrintService getPrintService() {
    if (myService == null) {
        String printerName = getNativePrintService();
        if (printerName != null) {
            myService = Win32PrintServiceLookup.getWin32PrintLUS().getPrintServiceByName(printerName);
            // currently set in native
            if (myService != null) {
                return myService;
            }
        }
        myService = PrintServiceLookup.lookupDefaultPrintService();
        if (myService != null) {
            try {
                setNativePrintServiceIfNeeded(myService.getName());
            } catch (Exception e) {
                myService = null;
            }
        }
    }
    return myService;
}
Example 12
Project: UniCenta-master  File: ReportUtils.java View source code
/**
     *
     * @param printername
     * @return
     */
public static PrintService getPrintService(String printername) {
    if (printername == null) {
        return PrintServiceLookup.lookupDefaultPrintService();
    } else {
        if ("(Show dialog)".equals(printername)) {
            // null means "you have to show the print dialog"
            return null;
        } else if ("(Default)".equals(printername)) {
            return PrintServiceLookup.lookupDefaultPrintService();
        } else {
            PrintService[] pservices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
            for (PrintService s : pservices) {
                if (printername.equals(s.getName())) {
                    return s;
                }
            }
            return PrintServiceLookup.lookupDefaultPrintService();
        }
    }
}
Example 13
Project: unicentaopos381-johnl-master  File: ReportUtils.java View source code
/**
     *
     * @param printername
     * @return
     */
public static PrintService getPrintService(String printername) {
    if (printername == null) {
        return PrintServiceLookup.lookupDefaultPrintService();
    } else {
        if ("(Show dialog)".equals(printername)) {
            // null means "you have to show the print dialog"
            return null;
        } else if ("(Default)".equals(printername)) {
            return PrintServiceLookup.lookupDefaultPrintService();
        } else {
            PrintService[] pservices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
            for (PrintService s : pservices) {
                if (printername.equals(s.getName())) {
                    return s;
                }
            }
            return PrintServiceLookup.lookupDefaultPrintService();
        }
    }
}
Example 14
Project: UnicentaPOS_AD-master  File: ReportUtils.java View source code
public static PrintService getPrintService(String printername) {
    if (printername == null) {
        return PrintServiceLookup.lookupDefaultPrintService();
    } else {
        if ("(Show dialog)".equals(printername)) {
            // null means "you have to show the print dialog"
            return null;
        } else if ("(Default)".equals(printername)) {
            return PrintServiceLookup.lookupDefaultPrintService();
        } else {
            PrintService[] pservices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
            for (PrintService s : pservices) {
                if (printername.equals(s.getName())) {
                    return s;
                }
            }
            return PrintServiceLookup.lookupDefaultPrintService();
        }
    }
}
Example 15
Project: WANDA-master  File: ReportUtils.java View source code
/**
     *
     * @param printername
     * @return
     */
public static PrintService getPrintService(String printername) {
    if (printername == null) {
        return PrintServiceLookup.lookupDefaultPrintService();
    } else {
        if ("(Show dialog)".equals(printername)) {
            // null means "you have to show the print dialog"
            return null;
        } else if ("(Default)".equals(printername)) {
            return PrintServiceLookup.lookupDefaultPrintService();
        } else {
            PrintService[] pservices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
            for (PrintService s : pservices) {
                if (printername.equals(s.getName())) {
                    return s;
                }
            }
            return PrintServiceLookup.lookupDefaultPrintService();
        }
    }
}
Example 16
Project: WandaPOS-master  File: ReportUtils.java View source code
/**
     *
     * @param printername
     * @return
     */
public static PrintService getPrintService(String printername) {
    if (printername == null) {
        return PrintServiceLookup.lookupDefaultPrintService();
    } else {
        if ("(Show dialog)".equals(printername)) {
            // null means "you have to show the print dialog"
            return null;
        } else if ("(Default)".equals(printername)) {
            return PrintServiceLookup.lookupDefaultPrintService();
        } else {
            PrintService[] pservices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
            for (PrintService s : pservices) {
                if (printername.equals(s.getName())) {
                    return s;
                }
            }
            return PrintServiceLookup.lookupDefaultPrintService();
        }
    }
}
Example 17
Project: bi-platform-v2-master  File: JFreeReportComponent.java View source code
public boolean print(final MasterReport report, final String jobName, final String printerName) {
    boolean result = false;
    if (jobName != null) {
        report.getReportConfiguration().setConfigProperty(PrintUtil.PRINTER_JOB_NAME_KEY, String.valueOf(jobName));
    }
    PrintService printer = null;
    PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
    for (final PrintService service : services) {
        if (service.getName().equals(printerName)) {
            printer = service;
        }
    }
    if ((printer == null) && (services.length > 0)) {
        printer = services[0];
    }
    try {
        Java14PrintUtil.printDirectly(report, printer);
        result = true;
    } catch (PrintException e) {
    } catch (ReportProcessingException e) {
    }
    return result;
}
Example 18
Project: ChromisPOS-master  File: ReportUtils.java View source code
/**
     *
     * @param printername
     * @return
     */
public static PrintService getPrintService(String printername) {
    if (printername == null) {
        return PrintServiceLookup.lookupDefaultPrintService();
    } else {
        if ("(Show dialog)".equals(printername)) {
            // null means "you have to show the print dialog"
            return null;
        } else if ("(Default)".equals(printername)) {
            return PrintServiceLookup.lookupDefaultPrintService();
        } else {
            PrintService[] pservices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
            for (PrintService s : pservices) {
                if (printername.equals(s.getName())) {
                    return s;
                }
            }
            return PrintServiceLookup.lookupDefaultPrintService();
        }
    }
}
Example 19
Project: Con-Badges-master  File: StartPrintingAction.java View source code
private void start() {
    running = true;
    PrintService ps = null;
    firePropertyChange(Action.NAME, START_TEXT, STOP_TEXT);
    if (badgePrinterUI.isPrintMode()) {
        final PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        pras.add(new Copies(1));
        final PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.PNG, pras);
        for (PrintService service : services) {
            final String name = service.getName();
            System.out.println(name);
            // TODO need to 
            if (name.startsWith("HiTi")) {
                ps = service;
            }
        }
        if (ps == null) {
            System.err.println("Could not find printer");
            this.setEnabled(true);
            return;
        }
    }
    final PrintService printService = ps;
    new Thread() {

        public void run() {
            badgePrinter = badgePrinterUI.getBadgePrinter();
            final File userHome = new File(System.getProperty("user.home"));
            final File outDir = new File(userHome, "badger");
            if (badgePrinterUI.isPrintMode()) {
                badgePrinter.printBadges(badgeSource, printService, outDir);
            } else {
                if (outDir.isDirectory() || outDir.mkdirs()) {
                    badgePrinter.generateBadgePNGs(badgeSource, outDir);
                } else {
                    LOGGER.log(Level.SEVERE, "Could not create badge output directory dir=" + outDir.getAbsolutePath());
                }
            }
            StartPrintingAction.this.firePropertyChange(Action.NAME, START_TEXT, STOP_TEXT);
        }
    }.start();
}
Example 20
Project: pentaho-platform-master  File: JFreeReportComponent.java View source code
public boolean print(final MasterReport report, final String jobName, final String printerName) {
    boolean result = false;
    if (jobName != null) {
        report.getReportConfiguration().setConfigProperty(PrintUtil.PRINTER_JOB_NAME_KEY, String.valueOf(jobName));
    }
    PrintService printer = null;
    PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
    for (final PrintService service : services) {
        if (service.getName().equals(printerName)) {
            printer = service;
        }
    }
    if ((printer == null) && (services.length > 0)) {
        printer = services[0];
    }
    try {
        Java14PrintUtil.printDirectly(report, printer);
        result = true;
    } catch (PrintException e) {
    } catch (ReportProcessingException e) {
    }
    return result;
}
Example 21
Project: pentaho-reporting-master  File: Java14PrintUtil.java View source code
private static PrintService lookupPrintService() throws PrintException {
    final PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
    if (defaultService != null && defaultService.isDocFlavorSupported(DocFlavor.SERVICE_FORMATTED.PAGEABLE)) {
        return defaultService;
    }
    final PrintService printService;
    final PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
    if (services.length == 0) {
        throw new PrintException("Unable to find a matching print service implementation.");
    }
    printService = services[0];
    return printService;
}
Example 22
Project: acs-master  File: PrintUtil.java View source code
/* (non-javadoc)
   * Locates among the available print services the one with the name defined by PRINTER_NAME. 
   * If that service is not available, the default print service is returned.
   */
private PrintService findPrinterService(DocFlavor flavor, PrintRequestAttributeSet aset) {
    PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, aset);
    for (int i = 0; i < services.length; i++) {
        if (services[i].getName().compareToIgnoreCase(PRINTER_NAME) == 0)
            return services[i];
    }
    return PrintServiceLookup.lookupDefaultPrintService();
}
Example 23
Project: deegree2-desktop-master  File: DirectPrinter.java View source code
/**
     * prints map onto a printer device
     */
public void print() {
    final String sCrLf = System.getProperty("line.separator");
    final String sPrintFile = "PrintFile.ps";
    final String sErrNoPrintService = sCrLf + "Es ist kein passender Print-Service installiert.";
    // Commandline parameter:
    // -1 means: no parameter
    int idxPrintService = -1;
    // Set DocFlavor and print attributes:
    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
    final PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    try {
        if (-2 == idxPrintService) {
            // Print to Stream (here to PostScript File):
            StreamPrintServiceFactory[] prservFactories = StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor, DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());
            if (null == prservFactories || 0 >= prservFactories.length) {
                LOG.logError(sErrNoPrintService);
                return;
            }
            LOG.logInfo("Stream-PrintService-Factory:");
            for (int i = prservFactories.length - 1; i >= 0; i--) {
                LOG.logInfo("  " + prservFactories[i] + " (" + prservFactories[i].getOutputFormat() + ")");
            }
            FileOutputStream fos = new FileOutputStream(sPrintFile);
            StreamPrintService sps = prservFactories[0].getPrintService(fos);
            LOG.logInfo("Stream-PrintService:");
            LOG.logInfo("  " + sps + " (" + sps.getOutputFormat() + ")");
            DocPrintJob pj = sps.createPrintJob();
            Doc doc = new SimpleDoc(new PrintableMap(mapModel), flavor, null);
            pj.print(doc, aset);
            fos.close();
            LOG.logInfo("Ausgabedatei '" + sPrintFile + "' ist erfolgreich generiert.");
        } else {
            // Print to PrintService (e.g. to Printer):
            PrintService prservDflt = PrintServiceLookup.lookupDefaultPrintService();
            PrintService[] prservices = PrintServiceLookup.lookupPrintServices(flavor, aset);
            if (null == prservices || 0 >= prservices.length)
                if (null != prservDflt) {
                    LOG.logWarning("Nur Default-Printer, da lookupPrintServices fehlgeschlagen. ");
                    prservices = new PrintService[] { prservDflt };
                } else {
                    LOG.logError(sErrNoPrintService);
                    return;
                }
            if (LOG.getLevel() == ILogger.LOG_DEBUG) {
                for (int i = 0; i < prservices.length; i++) {
                    LOG.logDebug("Print-Services:");
                    LOG.logDebug("  " + i + ":  " + prservices[i] + ((prservDflt != prservices[i]) ? "" : " (Default)"));
                }
            }
            final PrinterJob pjob = PrinterJob.getPrinterJob();
            pjob.setPrintService(prservDflt);
            if (pjob.printDialog()) {
                // pjob.setPrintable( new PrintableMap( mapModel ), pjob.pageDialog( aset ) );
                pjob.setPrintable(new PrintableMap(mapModel));
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        try {
                            pjob.print(aset);
                        } catch (PrinterException e) {
                            LOG.logError(e);
                        }
                    }
                });
            }
        }
    } catch (Exception pe) {
        LOG.logError(pe);
    }
}
Example 24
Project: gmf-runtime-master  File: PrintPreviewHelper.java View source code
/**
	 * Make sure printer is installed. Should not be able to print preview if no
	 * printer is installed, even though technically it will work.
	 * 
	 * Call this immediately with the rest of the initialization.
	 */
protected boolean isPrinterInstalled() {
    try {
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        return printServices.length > 0;
    } catch (SWTError e) {
        Trace.catching(DiagramPrintingPlugin.getInstance(), DiagramPrintingDebugOptions.EXCEPTIONS_CATCHING, PrintPreviewHelper.class, "isPrinterInstalled", e);
        if (e.code == SWT.ERROR_NO_HANDLES) {
            return false;
        }
        Log.error(DiagramPrintingPlugin.getInstance(), DiagramPrintingStatusCodes.GENERAL_UI_FAILURE, "Failed to make instance of Printer object", e);
        Trace.throwing(DiagramPrintingPlugin.getInstance(), DiagramPrintingDebugOptions.EXCEPTIONS_CATCHING, PrintPreviewHelper.class, "isPrinterInstalled", e);
        throw e;
    }
}
Example 25
Project: jasperstarter-master  File: App.java View source code
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());
    }
}
Example 26
Project: jqm-master  File: PrintServiceImpl.java View source code
@Override
public void print(String printQueueName, String jobName, Object data, DocFlavor flavor, String endUserName) throws PrintException {
    // Arguments tests
    if (printQueueName == null || printQueueName.isEmpty()) {
        throw new IllegalArgumentException("printQueueName must be non null and non empty");
    }
    if (data == null) {
        throw new IllegalArgumentException("data must be non null");
    }
    if (flavor == null) {
        throw new IllegalArgumentException("flavor must be non null");
    }
    if (jobName == null || jobName.isEmpty()) {
        throw new IllegalArgumentException("job name must be non null and non empty");
    }
    if (endUserName != null && endUserName.isEmpty()) {
        throw new IllegalArgumentException("endUserName can be null but cannot be empty is specified");
    }
    // Find the queue
    AttributeSet set = new HashPrintServiceAttributeSet();
    set.add(new PrinterName(printQueueName, null));
    javax.print.PrintService[] services = PrintServiceLookup.lookupPrintServices(null, set);
    if (services.length == 0 || services[0] == null) {
        throw new IllegalArgumentException("There is no printer queue defined with name " + printQueueName + " supporting document flavour " + flavor.toString());
    }
    javax.print.PrintService queue = services[0];
    // Create job
    DocPrintJob job = queue.createPrintJob();
    PrintRequestAttributeSet jobAttrs = new HashPrintRequestAttributeSet();
    jobAttrs.add(new JobName(jobName, null));
    if (endUserName != null && queue.isAttributeCategorySupported(RequestingUserName.class)) {
        jobAttrs.add(new RequestingUserName(endUserName, null));
    }
    // Create payload
    Doc doc = new SimpleDoc(data, flavor, null);
    // Do it
    job.print(doc, jobAttrs);
}
Example 27
Project: swingsane-master  File: PreferredDefaultsImpl.java View source code
private boolean isA4PaperSize() {
    String timezone = System.getProperty("user.timezone");
    if ((timezone != null) && (timezone.length() > 0)) {
        return !System.getProperty("user.timezone").startsWith("America");
    }
    try {
        PrintService pservice = PrintServiceLookup.lookupDefaultPrintService();
        Object obj = pservice.getDefaultAttributeValue(Media.class);
        if (obj instanceof MediaSizeName) {
            MediaSizeName mediaSizeName = (MediaSizeName) obj;
            return mediaSizeName.equals(MediaSizeName.ISO_A4);
        }
    } catch (Exception ex) {
        LOG.info(ex.getLocalizedMessage());
    }
    String country = Locale.getDefault().getCountry();
    if ((country.equals("US")) || (country.equals("CA"))) {
        return false;
    }
    // default to true
    return true;
}
Example 28
Project: elexis-3-core-master  File: TextTemplatePrintSettingsDialog.java View source code
private void initSelection() {
    if (selPrinter == null) {
        PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
        if (defaultPrintService != null && printServices.contains(defaultPrintService)) {
            cvPrinters.setSelection(new StructuredSelection(defaultPrintService));
        }
    } else {
        for (PrintService ps : printServices) {
            if (ps.getName().equals(selPrinter)) {
                cvPrinters.setSelection(new StructuredSelection(ps));
            }
        }
    }
    if (!mediaTrays.isEmpty()) {
        if (selTray == null) {
            cvTrays.setSelection(new StructuredSelection(mediaTrays.get(0)));
        } else {
            for (MediaTray mt : mediaTrays) {
                if (mt.toString().equals(selTray)) {
                    cvTrays.setSelection(new StructuredSelection(mt));
                }
            }
        }
    }
}
Example 29
Project: fop-master  File: ExampleFO2JPSPrint.java View source code
private DocPrintJob createDocPrintJob() {
    PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
    PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
    PrintService printService = ServiceUI.printDialog(null, 50, 50, services, services[0], null, attributes);
    if (printService != null) {
        return printService.createPrintJob();
    } else {
        return null;
    }
}
Example 30
Project: ISJ-master  File: ExampleFO2JPSPrint.java View source code
private DocPrintJob createDocPrintJob() {
    PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
    PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
    PrintService printService = ServiceUI.printDialog(null, 50, 50, services, services[0], null, attributes);
    if (printService != null) {
        return printService.createPrintJob();
    } else {
        return null;
    }
}
Example 31
Project: zebra-zpl-master  File: ZebraUtils.java View source code
/**
	 * Function to print code Zpl to local zebra(usb)
	 * 
	 * @param zpl
	 *            code Zpl to print
	 * @param ip
	 *            ip adress
	 * @param port
	 *            port
	 * @throws ZebraPrintException
	 *             if zpl could not be printed
	 */
public static void printZpl(String zpl, String printerName) throws ZebraPrintException {
    try {
        PrintService psZebra = null;
        String sPrinterName = null;
        PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
        for (int i = 0; i < services.length; i++) {
            PrintServiceAttribute attr = services[i].getAttribute(PrinterName.class);
            sPrinterName = ((PrinterName) attr).getValue();
            if (sPrinterName.toLowerCase().indexOf(printerName) >= 0) {
                psZebra = services[i];
                break;
            }
        }
        if (psZebra == null) {
            throw new ZebraPrintNotFoundException("Zebra printer not found : " + printerName);
        }
        DocPrintJob job = psZebra.createPrintJob();
        byte[] by = zpl.getBytes();
        DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        Doc doc = new SimpleDoc(by, flavor, null);
        job.print(doc, null);
    } catch (PrintException e) {
        throw new ZebraPrintException("Cannot print label on this printer : " + printerName, e);
    }
}
Example 32
Project: ikvm-openjdk-master  File: RasterPrinterJob.java View source code
/*
     * A convenience method which returns the default service
     * for 2D <code>PrinterJob</code>s.
     * May return null if there is no suitable default (although there
     * may still be 2D services available).
     * @return default 2D print service, or null.
     * @since     1.4
     */
protected static PrintService lookupDefaultPrintService() {
    PrintService service = PrintServiceLookup.lookupDefaultPrintService();
    /* Pageable implies Printable so checking both isn't strictly needed */
    if (service != null && service.isDocFlavorSupported(DocFlavor.SERVICE_FORMATTED.PAGEABLE) && service.isDocFlavorSupported(DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
        return service;
    } else {
        PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
        if (services.length > 0) {
            return services[0];
        }
    }
    return null;
}
Example 33
Project: ManagedRuntimeInitiative-master  File: RasterPrinterJob.java View source code
/*
     * A convenience method which returns the default service
     * for 2D <code>PrinterJob</code>s.
     * May return null if there is no suitable default (although there
     * may still be 2D services available).
     * @return default 2D print service, or null.
     * @since     1.4
     */
protected static PrintService lookupDefaultPrintService() {
    PrintService service = PrintServiceLookup.lookupDefaultPrintService();
    /* Pageable implies Printable so checking both isn't strictly needed */
    if (service != null && service.isDocFlavorSupported(DocFlavor.SERVICE_FORMATTED.PAGEABLE) && service.isDocFlavorSupported(DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
        return service;
    } else {
        PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
        if (services.length > 0) {
            return services[0];
        }
    }
    return null;
}
Example 34
Project: camel-master  File: PrinterPrintTest.java View source code
@Test
public void moreThanOneLprEndpoint() throws Exception {
    if (isAwtHeadless()) {
        return;
    }
    int numberOfPrintservicesBefore = PrintServiceLookup.lookupPrintServices(null, null).length;
    // setup javax.print 
    PrintService ps1 = mock(PrintService.class);
    when(ps1.getName()).thenReturn("printer1");
    when(ps1.isDocFlavorSupported(any(DocFlavor.class))).thenReturn(Boolean.TRUE);
    PrintService ps2 = mock(PrintService.class);
    when(ps2.getName()).thenReturn("printer2");
    boolean res1 = PrintServiceLookup.registerService(ps1);
    assertTrue("PrintService #1 should be registered.", res1);
    boolean res2 = PrintServiceLookup.registerService(ps2);
    assertTrue("PrintService #2 should be registered.", res2);
    PrintService[] pss = PrintServiceLookup.lookupPrintServices(null, null);
    assertEquals("lookup should report two PrintServices.", numberOfPrintservicesBefore + 2, pss.length);
    DocPrintJob job1 = mock(DocPrintJob.class);
    when(ps1.createPrintJob()).thenReturn(job1);
    context.addRoutes(new RouteBuilder() {

        public void configure() {
            from("direct:start1").to("lpr://localhost/printer1?sendToPrinter=true");
            from("direct:start2").to("lpr://localhost/printer2?sendToPrinter=false");
        }
    });
    context.start();
    // Are there two different PrintConfigurations?
    Map<String, Endpoint> epm = context().getEndpointMap();
    assertEquals("Four endpoints", 4, epm.size());
    Endpoint lp1 = null;
    Endpoint lp2 = null;
    for (Map.Entry<String, Endpoint> ep : epm.entrySet()) {
        if (ep.getKey().contains("printer1")) {
            lp1 = ep.getValue();
        }
        if (ep.getKey().contains("printer2")) {
            lp2 = ep.getValue();
        }
    }
    assertNotNull(lp1);
    assertNotNull(lp2);
    assertEquals("printer1", ((PrinterEndpoint) lp1).getConfig().getPrintername());
    assertEquals("printer2", ((PrinterEndpoint) lp2).getConfig().getPrintername());
    template.sendBody("direct:start1", "Hello Printer 1");
    context.stop();
    verify(job1, times(1)).print(any(Doc.class), any(PrintRequestAttributeSet.class));
}
Example 35
Project: Clotho-Core-master  File: TextComponentUtil.java View source code
/**
     * Prints the contents of a text component.
     * 
     * @param textComponent
     */
public static void print(JTextComponent textComponent) throws TextComponentUtilException {
    InputStream is = null;
    try {
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.AUTOSENSE, null);
        if (printServices.length > 0) {
            PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
            printRequestAttributeSet.add(new JobName("JAligner", null));
            PrintService service = ServiceUI.printDialog(null, 50, 50, printServices, PrintServiceLookup.lookupDefaultPrintService(), DocFlavor.INPUT_STREAM.AUTOSENSE, printRequestAttributeSet);
            if (service != null) {
                DocPrintJob printJob = service.createPrintJob();
                PrintJobMointor printJobMointor = new PrintJobMointor(printJob);
                is = new ByteArrayInputStream(textComponent.getText().getBytes());
                DocumentName documentName = new DocumentName("JAligner", null);
                HashDocAttributeSet docAttributeSet = new HashDocAttributeSet();
                docAttributeSet.add(documentName);
                Doc doc = new SimpleDoc(is, DocFlavor.INPUT_STREAM.AUTOSENSE, docAttributeSet);
                printJob.print(doc, printRequestAttributeSet);
                printJobMointor.waitForPrintJob();
            }
        } else {
            throw new TextComponentUtilException("No print service found!");
        }
    } catch (Exception e) {
        throw new TextComponentUtilException(e.getMessage());
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                logger.log(Level.WARNING, "Failed closing input stream: " + e.getMessage(), e);
            }
        }
    }
}
Example 36
Project: ClothoBiofabEdition-master  File: TextComponentUtil.java View source code
/**
     * Prints the contents of a text component.
     * 
     * @param textComponent
     */
public static void print(JTextComponent textComponent) throws TextComponentUtilException {
    InputStream is = null;
    try {
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.AUTOSENSE, null);
        if (printServices.length > 0) {
            PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
            printRequestAttributeSet.add(new JobName("JAligner", null));
            PrintService service = ServiceUI.printDialog(null, 50, 50, printServices, PrintServiceLookup.lookupDefaultPrintService(), DocFlavor.INPUT_STREAM.AUTOSENSE, printRequestAttributeSet);
            if (service != null) {
                DocPrintJob printJob = service.createPrintJob();
                PrintJobMointor printJobMointor = new PrintJobMointor(printJob);
                is = new ByteArrayInputStream(textComponent.getText().getBytes());
                DocumentName documentName = new DocumentName("JAligner", null);
                HashDocAttributeSet docAttributeSet = new HashDocAttributeSet();
                docAttributeSet.add(documentName);
                Doc doc = new SimpleDoc(is, DocFlavor.INPUT_STREAM.AUTOSENSE, docAttributeSet);
                printJob.print(doc, printRequestAttributeSet);
                printJobMointor.waitForPrintJob();
            }
        } else {
            throw new TextComponentUtilException("No print service found!");
        }
    } catch (Exception e) {
        throw new TextComponentUtilException(e.getMessage());
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                logger.log(Level.WARNING, "Failed closing input stream: " + e.getMessage(), e);
            }
        }
    }
}
Example 37
Project: FloreantPos-master  File: PrintConfigurationView.java View source code
@Override
public void initialize() throws Exception {
    PrinterType[] values = PrinterType.values();
    cbReceiptPrinterType.setModel(new DefaultComboBoxModel(values));
    cbKitchenPrinterType.setModel(new DefaultComboBoxModel(values));
    PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
    cbReceiptPrinterName.setModel(new DefaultComboBoxModel(printServices));
    cbKitchenPrinterName.setModel(new DefaultComboBoxModel(printServices));
    PrintServiceComboRenderer comboRenderer = new PrintServiceComboRenderer();
    cbReceiptPrinterName.setRenderer(comboRenderer);
    cbKitchenPrinterName.setRenderer(comboRenderer);
    cbReceiptPrinterType.setSelectedItem(PrinterType.fromString(ApplicationConfig.getString(PrintConfig.P_RECEIPT_PRINTER_TYPE, PrinterType.OS_PRINTER.getName())));
    cbKitchenPrinterType.setSelectedItem(PrinterType.fromString(ApplicationConfig.getString(PrintConfig.P_KITCHEN_PRINTER_TYPE, PrinterType.OS_PRINTER.getName())));
    tfReceiptPrinterName.setText(ApplicationConfig.getString(PrintConfig.P_JAVAPOS_PRINTER_FOR_RECEIPT, "POSPrinter"));
    tfReceiptCashDrawerName.setText(ApplicationConfig.getString(PrintConfig.P_CASH_DRAWER_NAME, "CashDrawer"));
    tfKitchenPrinterName.setText(ApplicationConfig.getString(PrintConfig.P_JAVAPOS_PRINTER_FOR_KITCHEN, "KitchenPrinter"));
    setSelectedPrinter(cbReceiptPrinterName, PrintConfig.P_OS_PRINTER_FOR_RECEIPT);
    setSelectedPrinter(cbKitchenPrinterName, PrintConfig.P_OS_PRINTER_FOR_KITCHEN);
    chkPrintReceiptWhenTicketSettled.setSelected(ApplicationConfig.getBoolean(PrintConfig.P_PRINT_RECEIPT_WHEN_SETTELED, true));
    chkPrintReceiptWhenTicketPaid.setSelected(ApplicationConfig.getBoolean(PrintConfig.P_PRINT_RECEIPT_WHEN_PAID, false));
    chkPrintKitchenWhenTicketSettled.setSelected(ApplicationConfig.getBoolean(PrintConfig.P_PRINT_KITCHEN_WHEN_SETTELED, false));
    chkPrintKitchenWhenTicketPaid.setSelected(ApplicationConfig.getBoolean(PrintConfig.P_PRINT_KITCHEN_WHEN_PAID, false));
    setInitialized(true);
}
Example 38
Project: icepdf-master  File: PrintServices.java View source code
/**
     * Attempts to Print PDF documents which are specified as application
     * arguments.
     *
     * @param args list of files which should be printed by the application
     */
public static void main(String[] args) {
    // setup for input from command line
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    /**
         * Find Available printers
         */
    PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
    int selectedPrinter = 0;
    // q, otherwise just keep asking them which printer to use.
    while (!(selectedPrinter > 0 && selectedPrinter <= services.length)) {
        System.out.println("Please select the printer number your wish to print to (q to quit):");
        int printerIndex = 1;
        for (int i = 0, max = services.length - 1; i <= max; i++) {
            System.out.println("  " + printerIndex++ + ". " + services[i].getName());
        }
        System.out.print("Printer selection? ");
        String input = "";
        // get users choice
        try {
            input = stdin.readLine();
        } catch (IOException e) {
        }
        if (input.length() == 0) {
            System.out.println("Please select a valid printer number.");
            System.out.println();
        } else if (input.toLowerCase().equals("q")) {
            System.exit(0);
        } else {
            try {
                selectedPrinter = Integer.parseInt(input);
                if ((selectedPrinter > 0 && selectedPrinter <= services.length)) {
                    break;
                }
            } catch (NumberFormatException e) {
            }
            System.out.println("Please select a valid printer number.");
            System.out.println();
        }
    }
    /**
         * Selected Printer, via user input
         */
    PrintService selectedService = services[selectedPrinter - 1];
    /**
         * Show selected Printer default attributes.
         */
    System.out.println("Supported Job Properties for printer: " + selectedService.getName());
    Class[] supportedAttributes = selectedService.getSupportedAttributeCategories();
    for (Class supportedAttribute : supportedAttributes) {
        System.out.println("   " + supportedAttribute.getName() + ":= " + selectedService.getDefaultAttributeValue(supportedAttribute));
    }
    // Open the document, create a PrintHelper and finally print the document
    Document pdf = new Document();
    try {
        // load the file specified by the command line
        String filePath;
        if (args.length > 0) {
            filePath = args[0];
        } else {
            throw new FileNotFoundException("Specify a PDF document.");
        }
        pdf.setFile(filePath);
        // create a new print helper with a specified paper size and print
        // quality
        PrintHelper printHelper = new PrintHelper(null, pdf.getPageTree(), 0f, MediaSizeName.NA_LEGAL, PrintQuality.DRAFT);
        // try and print pages 1 - 10, 1 copy, scale to fit paper.
        printHelper.setupPrintService(selectedService, 0, 0, 1, true);
        // print the document
        printHelper.print();
    } catch (FileNotFoundException e) {
        logger.log(Level.WARNING, "PDF file not found.", e);
    } catch (IOException e) {
        logger.log(Level.WARNING, "Error loading PDF file", e);
    } catch (PDFSecurityException e) {
        logger.log(Level.WARNING, "PDF security exception, unspported encryption type.", e);
    } catch (PDFException e) {
        logger.log(Level.WARNING, "Error loading PDF document.", e);
    } catch (PrintException e) {
        logger.log(Level.WARNING, "Error Printing document.", e);
    } finally {
        pdf.dispose();
    }
}
Example 39
Project: idart-jss-master  File: PrintLabel.java View source code
/**
	 * Method printiDARTLabels.
	 * 
	 * @param labelsToPrint
	 *            List<Object>
	 */
public static void printiDARTLabels(List<Object> labelsToPrint) throws Exception {
    if (System.getProperty("os.name").toUpperCase().startsWith("WINDOWS")) {
        List<Printable> printableLabelList = new ArrayList<Printable>();
        for (Object o : labelsToPrint) {
            printableLabelList.add((Printable) o);
        }
        printWindowsLabels(printableLabelList);
    } else if (!System.getProperty("os.name").toUpperCase().startsWith("LINUX")) {
        PrintService[] allServices = PrintServiceLookup.lookupPrintServices(null, null);
        /* rashid temp code */
        PrintService serv = null;
        for (PrintService s : allServices) {
            if (s.getName().contains("Zebra")) {
                serv = s;
            }
        }
        if (serv != null) {
            List<DefaultLabel> defaultLabelList = new ArrayList<DefaultLabel>();
            for (Object o : labelsToPrint) {
                defaultLabelList.add((DefaultLabel) o);
            }
            printLinuxZebraLabels(defaultLabelList, serv);
            return;
        }
        /* rashid temp code */
        boolean foundZebra = false;
        for (int j = 0; j < allServices.length; j++) {
            PrintService service = allServices[j];
            if (// Is this printer a Zebra?
            service != null) {
                try {
                    Runtime // search for this
                    rt = // search for this
                    Runtime.getRuntime();
                    // printer in list
                    // from lpstat
                    Process p = rt.exec(new String[] { "/bin/sh", "-c", "lpstat -v| grep '" + service.getName() + "' | grep Zebra" });
                    InputStream inputstream = p.getInputStream();
                    InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
                    BufferedReader bufferedReader = new BufferedReader(inputstreamreader);
                    // read the output
                    String line = bufferedReader.readLine();
                    bufferedReader.close();
                    if (line != null) {
                        foundZebra = true;
                        List<DefaultLabel> defaultLabelList = new ArrayList<DefaultLabel>();
                        for (Object o : labelsToPrint) {
                            defaultLabelList.add((DefaultLabel) o);
                        }
                        printLinuxZebraLabels(defaultLabelList, service);
                        return;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (!foundZebra) {
            List<Printable> printableLabelList = new ArrayList<Printable>();
            for (Object o : labelsToPrint) {
                printableLabelList.add((Printable) o);
            }
            printWindowsLabels(printableLabelList);
        }
    }
}
Example 40
Project: Offene-Pflege.de-master  File: PnlLabelPrinterSetup.java View source code
private void initPanel() {
    testStock = null;
    cmbPhysicalPrinters.setModel(new DefaultComboBoxModel());
    cmbForm.setModel(new DefaultComboBoxModel());
    cmbLogicalPrinters.setModel(new DefaultComboBoxModel());
    //todo: seit macos sierra funktioniert das so gut wie nicht mehr.
    PrintService[] prservices = PrintServiceLookup.lookupPrintServices(null, null);
    // this prevents exceptions when there are no printers installed on the OS yet
    if (prservices != null && prservices.length == 0) {
        prservices = null;
    }
    if (prservices != null) {
        cmbPhysicalPrinters.setModel(new DefaultComboBoxModel(prservices));
        cmbPhysicalPrinters.setRenderer(( jList,  o,  i,  isSelected,  cellHasFocus) -> {
            if (o == null)
                return new DefaultListCellRenderer().getListCellRendererComponent(jList, SYSTools.xx("misc.msg.error"), i, isSelected, cellHasFocus);
            return new DefaultListCellRenderer().getListCellRendererComponent(jList, ((PrintService) o).getName(), i, isSelected, cellHasFocus);
        });
        cmbLogicalPrinters.setRenderer(( jList,  o,  i,  isSelected,  cellHasFocus) -> {
            if (o == null)
                return new DefaultListCellRenderer().getListCellRendererComponent(jList, SYSTools.xx("misc.msg.error"), i, isSelected, cellHasFocus);
            return new DefaultListCellRenderer().getListCellRendererComponent(jList, ((LogicalPrinter) o).getLabel(), i, isSelected, cellHasFocus);
        });
        cmbForm.setRenderer(( jList,  o,  i,  isSelected,  cellHasFocus) -> {
            if (o == null)
                return new DefaultListCellRenderer().getListCellRendererComponent(jList, SYSTools.xx("misc.msg.error"), i, isSelected, cellHasFocus);
            return new DefaultListCellRenderer().getListCellRendererComponent(jList, ((PrinterForm) o).getLabel(), i, isSelected, cellHasFocus);
        });
        cmbPhysicalPrinters.addItemListener( e -> {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                PrintService printService = (PrintService) cmbPhysicalPrinters.getSelectedItem();
                OPDE.getProps().setProperty(SYSPropsTools.KEY_PHYSICAL_PRINTER, printService.getName());
                OPDE.getLocalProps().setProperty(SYSPropsTools.KEY_PHYSICAL_PRINTER, printService.getName());
                OPDE.saveLocalProps();
            }
        });
        cmbLogicalPrinters.addItemListener( e -> {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                LogicalPrinter logicalPrinter = (LogicalPrinter) cmbLogicalPrinters.getSelectedItem();
                cmbForm.setModel(new DefaultComboBoxModel(logicalPrinter.getForms().values().toArray()));
                if (OPDE.getProps().containsKey(SYSPropsTools.KEY_MEDSTOCK_LABEL) && logicalPrinter.getForms().containsKey(OPDE.getProps().getProperty(SYSPropsTools.KEY_MEDSTOCK_LABEL))) {
                    cmbForm.setSelectedItem(logicalPrinter.getForms().get(OPDE.getProps().getProperty(SYSPropsTools.KEY_MEDSTOCK_LABEL)));
                }
                OPDE.getLocalProps().setProperty(SYSPropsTools.KEY_LOGICAL_PRINTER, logicalPrinter.getName());
                OPDE.getProps().setProperty(SYSPropsTools.KEY_LOGICAL_PRINTER, logicalPrinter.getName());
                OPDE.getLocalProps().setProperty(SYSPropsTools.KEY_MEDSTOCK_LABEL, ((PrinterForm) cmbForm.getSelectedItem()).getName());
                OPDE.getProps().setProperty(SYSPropsTools.KEY_MEDSTOCK_LABEL, ((PrinterForm) cmbForm.getSelectedItem()).getName());
            }
        });
        cmbForm.addItemListener( e -> {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                OPDE.getProps().setProperty(SYSPropsTools.KEY_MEDSTOCK_LABEL, ((PrinterForm) cmbForm.getSelectedItem()).getName());
                OPDE.getLocalProps().setProperty(SYSPropsTools.KEY_MEDSTOCK_LABEL, ((PrinterForm) cmbForm.getSelectedItem()).getName());
            }
        });
        if (OPDE.getPrintProcessor().isWorking()) {
            cmbLogicalPrinters.setModel(new DefaultComboBoxModel(OPDE.getLogicalPrinters().getLogicalPrintersList().toArray()));
            LogicalPrinter logicalPrinter = OPDE.getLogicalPrinters().getMapName2LogicalPrinter().get(OPDE.getProps().getProperty(SYSPropsTools.KEY_LOGICAL_PRINTER));
            cmbLogicalPrinters.setSelectedItem(logicalPrinter);
            cmbForm.setModel(new DefaultComboBoxModel(logicalPrinter.getForms().values().toArray()));
            cmbForm.setSelectedItem(logicalPrinter.getForms().get(OPDE.getProps().getProperty(SYSPropsTools.KEY_MEDSTOCK_LABEL)));
        }
        if (OPDE.getProps().containsKey(SYSPropsTools.KEY_PHYSICAL_PRINTER) && OPDE.getLogicalPrinters().getPrintService(OPDE.getProps().getProperty(SYSPropsTools.KEY_PHYSICAL_PRINTER)) != null) {
            cmbPhysicalPrinters.setSelectedItem(OPDE.getLogicalPrinters().getPrintService(OPDE.getProps().getProperty(SYSPropsTools.KEY_PHYSICAL_PRINTER)));
        } else {
            PrintService printService = (PrintService) cmbPhysicalPrinters.getSelectedItem();
            OPDE.getProps().setProperty(SYSPropsTools.KEY_PHYSICAL_PRINTER, printService.getName());
            OPDE.getLocalProps().setProperty(SYSPropsTools.KEY_PHYSICAL_PRINTER, printService.getName());
        }
        if (!OPDE.getLogicalPrinters().getLogicalPrintersList().isEmpty()) {
            cmbLogicalPrinters.setModel(new DefaultComboBoxModel(OPDE.getLogicalPrinters().getLogicalPrintersList().toArray()));
            LogicalPrinter logicalPrinter = OPDE.getLogicalPrinters().getMapName2LogicalPrinter().get(OPDE.getProps().getProperty(SYSPropsTools.KEY_LOGICAL_PRINTER));
            if (logicalPrinter == null)
                logicalPrinter = OPDE.getLogicalPrinters().getLogicalPrintersList().get(0);
            if (!OPDE.getProps().containsKey(SYSPropsTools.KEY_LOGICAL_PRINTER)) {
                OPDE.getLocalProps().setProperty(SYSPropsTools.KEY_LOGICAL_PRINTER, logicalPrinter.getName());
                OPDE.getProps().setProperty(SYSPropsTools.KEY_LOGICAL_PRINTER, logicalPrinter.getName());
            }
            cmbLogicalPrinters.setSelectedItem(logicalPrinter);
            cmbForm.setModel(new DefaultComboBoxModel(logicalPrinter.getForms().values().toArray()));
            if (OPDE.getProps().containsKey(SYSPropsTools.KEY_MEDSTOCK_LABEL) && logicalPrinter.getForms().containsKey(OPDE.getProps().getProperty(SYSPropsTools.KEY_MEDSTOCK_LABEL))) {
                cmbForm.setSelectedItem(logicalPrinter.getForms().get(OPDE.getProps().getProperty(SYSPropsTools.KEY_MEDSTOCK_LABEL)));
            } else {
                cmbForm.setSelectedIndex(0);
                OPDE.getLocalProps().setProperty(SYSPropsTools.KEY_MEDSTOCK_LABEL, ((PrinterForm) cmbForm.getSelectedItem()).getName());
                OPDE.getProps().setProperty(SYSPropsTools.KEY_MEDSTOCK_LABEL, ((PrinterForm) cmbForm.getSelectedItem()).getName());
            }
        }
    } else {
        cmbPhysicalPrinters.setEnabled(false);
        cmbLogicalPrinters.setEnabled(false);
        cmbPhysicalPrinters.setEnabled(false);
    }
    btnTestLabel.setEnabled(prservices != null);
    cmbForm.setEnabled(prservices != null);
    cmbLogicalPrinters.setEnabled(prservices != null);
    cmbPhysicalPrinters.setEnabled(prservices != null);
}
Example 41
Project: openelisglobal-core-master  File: SampleLabelPrintProvider.java View source code
/*
	 * (non-Javadoc)
	 * 
	 * @see us.mn.state.health.lims.common.provider.reports.BaseReportsProvider#processRequest(java.util.Map,
	 *      javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 * bugzilla 2380: this method now throws exceptions instead of returning boolean successful
	 */
public void processRequest(Map parameters, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, PrintException, LIMSPrintException, LIMSInvalidPrinterException {
    try {
        PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
        String printer = null;
        PrinterName printerName = null;
        PrintService ps = null;
        //bugzilla 2380
        String validPrintersMessage = "";
        for (int i = 0; i < services.length; i++) {
            printer = services[i].getName();
            //bugzilla 2380 this is for error message to list valid printers in ActionError
            if (i == 0) {
                validPrintersMessage = "\\n";
            }
            validPrintersMessage += "\\n     " + printer;
            //bugzilla 2380: name must match - not start with
            if (printer.equalsIgnoreCase(SystemConfiguration.getInstance().getLabelPrinterName())) {
                printerName = new PrinterName(printer, null);
                //System.out.println("This is the printer I will use "
                //+ printerName);
                ps = services[i];
            //bugzilla 2380: load all valid printer names for error message
            //break;
            }
        }
        // System.out.println("Printer is found " + printer);
        if (printerName == null) {
            throw new LIMSInvalidPrinterException(validPrintersMessage);
        }
        String numberOfLabelCopiesString = null;
        int numberOfLabelCopies = 1;
        try {
            numberOfLabelCopiesString = SystemConfiguration.getInstance().getLabelNumberOfCopies("print.label.numberofcopies");
            numberOfLabelCopies = Integer.parseInt(numberOfLabelCopiesString);
        } catch (NumberFormatException nfe) {
            LogEvent.logError("SampleLabelPrintProvider", "processRequest()", nfe.toString());
        }
        String accessionNumber = (String) parameters.get("Accession_Number");
        if (ps == null) {
            throw new LIMSPrintException("no print service");
        }
        DocPrintJob job = ps.createPrintJob();
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        aset.add(new Copies(numberOfLabelCopies));
        String label = SystemConfiguration.getInstance().getDefaultSampleLabel(accessionNumber);
        byte[] byt = label.getBytes();
        DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        Doc doc = new SimpleDoc(byt, flavor, null);
        job.addPrintJobListener(new MyPrintJobListener());
        job.print(doc, aset);
    } catch (Exception e) {
        throw new LIMSRuntimeException("Error in SampleLabelPrintProvider processRequest()", e);
    }
}
Example 42
Project: simple-escp-master  File: SimpleEscp.java View source code
/**
     * Use the printer that matches the specified <code>AttributeSet</code>.
     *
     * @param attributeSet use printer that matches this value.
     * @throws java.lang.IllegalArgumentException if printer is not found.
     *
     */
public void usePrinter(AttributeSet attributeSet) {
    PrintService[] services = PrintServiceLookup.lookupPrintServices(null, attributeSet);
    if (services.length == 0) {
        throw new IllegalArgumentException("Printer not found.");
    } else if (services.length > 1) {
        LOG.warning("Found more than one printer. Only the first printer will be used.");
    }
    printService = services[0];
}
Example 43
Project: topsun-master  File: TicketTest.java View source code
// 以jdk1.4新版本æ??供的API实现打å?°åŠ¨ä½œæŒ‰é’®ç›‘å?¬ï¼Œå¹¶å®Œæˆ?具体的打å?°æ“?作
private void printText2Action() {
    // 打�标志清零
    printFlag = 0;
    // 获�需�打�的目标文本
    printStr = area.getText().trim();
    System.out.println("the   content   are   ::: ");
    System.out.println(printStr);
    if (//当打�内容�为空时
    printStr != null && printStr.length() > 0) {
        //获�打�总页数
        PAGES = getPagesCount(printStr);
        //指定打�输出格�
        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        //定�默认的打��务
        PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
        System.out.println("11" + printService + "----------");
        //创建打�作业
        DocPrintJob job = printService.createPrintJob();
        //设置打�属性
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        DocAttributeSet das = new HashDocAttributeSet();
        //指定打�内容
        Doc doc = new SimpleDoc(this, flavor, das);
        //�显示打�对�框,直接进行打�工作
        try {
            // 进行�一页的具体打��作
            job.print(doc, pras);
        } catch (PrintException pe) {
            pe.printStackTrace();
        }
    } else {
        JOptionPane.showConfirmDialog(null, "Sorry,   Printer   Job   is   Empty,   Print   Cancelled! ", "Empty ", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
    }
}
Example 44
Project: biobank-master  File: ReportingUtils.java View source code
private static PrintService getPrinterService(PrinterData data) {
    // use the standard java method to retrieve print services
    PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
    PrintService service = null;
    // information
    for (PrintService ps : services) {
        if (ps.getName().equals(data.name)) {
            service = ps;
        }
    }
    return service;
}
Example 45
Project: ConcesionariaDB-master  File: JRPrintServiceExporter.java View source code
/**
	 *
	 */
public void exportReport() throws JRException {
    /*   */
    setOffset();
    try {
        /*   */
        setExportContext();
        /*   */
        setInput();
        /*   */
        if (!isModeBatch) {
            setPageRange();
        }
        PrintServiceAttributeSet printServiceAttributeSet = (PrintServiceAttributeSet) parameters.get(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET);
        if (printServiceAttributeSet == null) {
            printServiceAttributeSet = new HashPrintServiceAttributeSet();
        }
        Boolean pageDialog = (Boolean) parameters.get(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG);
        if (pageDialog != null) {
            displayPageDialog = pageDialog.booleanValue();
        }
        Boolean pageDialogOnlyOnce = (Boolean) parameters.get(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG_ONLY_ONCE);
        if (displayPageDialog && pageDialogOnlyOnce != null) {
            // it can be (eventually) set to true only if displayPageDialog is true
            displayPageDialogOnlyOnce = pageDialogOnlyOnce.booleanValue();
        }
        Boolean printDialog = (Boolean) parameters.get(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG);
        if (printDialog != null) {
            displayPrintDialog = printDialog.booleanValue();
        }
        Boolean printDialogOnlyOnce = (Boolean) parameters.get(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG_ONLY_ONCE);
        if (displayPrintDialog && printDialogOnlyOnce != null) {
            //				 it can be (eventually) set to true only if displayPrintDialog is true
            displayPrintDialogOnlyOnce = printDialogOnlyOnce.booleanValue();
        }
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        JRPrinterAWT.initPrinterJobFields(printerJob);
        printerJob.setPrintable(this);
        printStatus = null;
        // determining the print service only once
        printService = (PrintService) parameters.get(JRPrintServiceExporterParameter.PRINT_SERVICE);
        if (printService == null) {
            PrintService[] services = PrintServiceLookup.lookupPrintServices(null, printServiceAttributeSet);
            if (services.length > 0) {
                printService = services[0];
            }
        }
        if (printService == null) {
            throw new JRException("No suitable print service found.");
        }
        try {
            printerJob.setPrintService(printService);
        } catch (PrinterException e) {
            throw new JRException(e);
        }
        PrintRequestAttributeSet printRequestAttributeSet = null;
        if (displayPrintDialogOnlyOnce || displayPageDialogOnlyOnce) {
            printRequestAttributeSet = new HashPrintRequestAttributeSet();
            setDefaultPrintRequestAttributeSet(printRequestAttributeSet);
            setOrientation((JasperPrint) jasperPrintList.get(0), printRequestAttributeSet);
            if (displayPageDialogOnlyOnce) {
                if (printerJob.pageDialog(printRequestAttributeSet) == null) {
                    return;
                } else {
                    displayPageDialog = false;
                }
            }
            if (displayPrintDialogOnlyOnce) {
                if (!printerJob.printDialog(printRequestAttributeSet)) {
                    printStatus = new Boolean[] { Boolean.FALSE };
                    return;
                } else {
                    displayPrintDialog = false;
                }
            }
        }
        List status = new ArrayList();
        // fix for bug ID artf1455 from jasperforge.org bug database
        for (reportIndex = 0; reportIndex < jasperPrintList.size(); reportIndex++) {
            setJasperPrint((JasperPrint) jasperPrintList.get(reportIndex));
            exporter = new JRGraphics2DExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.PROGRESS_MONITOR, parameters.get(JRExporterParameter.PROGRESS_MONITOR));
            exporter.setParameter(JRExporterParameter.OFFSET_X, parameters.get(JRExporterParameter.OFFSET_X));
            exporter.setParameter(JRExporterParameter.OFFSET_Y, parameters.get(JRExporterParameter.OFFSET_Y));
            exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, parameters.get(JRGraphics2DExporterParameter.ZOOM_RATIO));
            exporter.setParameter(JRExporterParameter.CLASS_LOADER, classLoader);
            exporter.setParameter(JRExporterParameter.URL_HANDLER_FACTORY, urlHandlerFactory);
            exporter.setParameter(JRExporterParameter.FILE_RESOLVER, fileResolver);
            if (parameters.containsKey(JRExporterParameter.FILTER)) {
                exporter.setParameter(JRExporterParameter.FILTER, filter);
            }
            exporter.setParameter(JRGraphics2DExporterParameter.MINIMIZE_PRINTER_JOB_SIZE, parameters.get(JRGraphics2DExporterParameter.MINIMIZE_PRINTER_JOB_SIZE));
            if (displayPrintDialog || displayPageDialog || (!displayPrintDialogOnlyOnce && !displayPageDialogOnlyOnce)) {
                printRequestAttributeSet = new HashPrintRequestAttributeSet();
                setDefaultPrintRequestAttributeSet(printRequestAttributeSet);
                setOrientation(jasperPrint, printRequestAttributeSet);
            }
            try {
                if (!isModeBatch) {
                    printRequestAttributeSet.add(new PageRanges(startPageIndex + 1, endPageIndex + 1));
                }
                printerJob.setJobName("JasperReports - " + jasperPrint.getName());
                if (displayPageDialog) {
                    printerJob.pageDialog(printRequestAttributeSet);
                }
                if (displayPrintDialog) {
                    if (printerJob.printDialog(printRequestAttributeSet)) {
                        status.add(Boolean.TRUE);
                        printerJob.print(printRequestAttributeSet);
                    } else {
                        status.add(Boolean.FALSE);
                    }
                } else {
                    PageFormat pageFormat = printerJob.defaultPage();
                    Paper paper = pageFormat.getPaper();
                    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());
                            }
                    }
                    printerJob.setPrintable(this, pageFormat);
                    printerJob.print(printRequestAttributeSet);
                }
            } catch (PrinterException e) {
                throw new JRException(e);
            }
        }
        printStatus = (Boolean[]) status.toArray(new Boolean[status.size()]);
        printService = printerJob.getPrintService();
    } finally {
        resetExportContext();
    }
}
Example 46
Project: JCGO-master  File: RasterPrinterJob.java View source code
/*
     * A convenience method which returns the default service
     * for 2D <code>PrinterJob</code>s.
     * May return null if there is no suitable default (although there
     * may still be 2D services available).
     * @return default 2D print service, or null.
     * @since     1.4
     */
protected static PrintService lookupDefaultPrintService() {
    PrintService service = PrintServiceLookup.lookupDefaultPrintService();
    /* Pageable implies Printable so checking both isn't strictly needed */
    if (service != null && service.isDocFlavorSupported(DocFlavor.SERVICE_FORMATTED.PAGEABLE) && service.isDocFlavorSupported(DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
        return service;
    } else {
        PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
        if (services.length > 0) {
            return services[0];
        }
    }
    return null;
}
Example 47
Project: monsiaj-master  File: PDFPrint.java View source code
public static void main(String args[]) throws Exception {
    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
    PrintService[] pss = PrintServiceLookup.lookupPrintServices(flavor, null);
    PrintService ps = null;
    System.out.println("---- print service");
    for (PrintService _ps : pss) {
        System.out.println(_ps.getName());
        if (_ps.getName().equals(args[0])) {
            ps = _ps;
        }
    }
    for (int i = 0; i < 1; i++) {
        if (ps == null) {
            PDFPrint printer = new PDFPrint(new File(args[1]));
            printer.start();
        } else {
            PDFPrint printer = new PDFPrint(new File(args[1]), ps);
            printer.start();
        }
        System.out.println(i);
        Thread.sleep(2000);
    }
}
Example 48
Project: ofbiz-master  File: OutputServices.java View source code
public static Map<String, Object> sendPrintFromScreen(DispatchContext dctx, Map<String, ? extends Object> serviceContext) {
    Locale locale = (Locale) serviceContext.get("locale");
    String screenLocation = (String) serviceContext.remove("screenLocation");
    Map<String, Object> screenContext = UtilGenerics.checkMap(serviceContext.remove("screenContext"));
    String contentType = (String) serviceContext.remove("contentType");
    String printerContentType = (String) serviceContext.remove("printerContentType");
    if (UtilValidate.isEmpty(screenContext)) {
        screenContext = new HashMap<String, Object>();
    }
    screenContext.put("locale", locale);
    if (UtilValidate.isEmpty(contentType)) {
        contentType = "application/postscript";
    }
    if (UtilValidate.isEmpty(printerContentType)) {
        printerContentType = contentType;
    }
    try {
        MapStack<String> screenContextTmp = MapStack.create();
        screenContextTmp.put("locale", locale);
        Writer writer = new StringWriter();
        // substitute the freemarker variables...
        ScreenStringRenderer foScreenStringRenderer = new MacroScreenRenderer(EntityUtilProperties.getPropertyValue("widget", "screenfop.name", dctx.getDelegator()), EntityUtilProperties.getPropertyValue("widget", "screenfop.screenrenderer", dctx.getDelegator()));
        ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContextTmp, foScreenStringRenderer);
        screensAtt.populateContextForService(dctx, screenContext);
        screenContextTmp.putAll(screenContext);
        screensAtt.getContext().put("formStringRenderer", foFormRenderer);
        screensAtt.render(screenLocation);
        // create the input stream for the generation
        StreamSource src = new StreamSource(new StringReader(writer.toString()));
        // create the output stream for the generation
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
        ApacheFopWorker.transform(src, null, fop);
        baos.flush();
        baos.close();
        // Print is sent
        DocFlavor psInFormat = new DocFlavor.INPUT_STREAM(printerContentType);
        InputStream bais = new ByteArrayInputStream(baos.toByteArray());
        DocAttributeSet docAttributeSet = new HashDocAttributeSet();
        List<Object> docAttributes = UtilGenerics.checkList(serviceContext.remove("docAttributes"));
        if (UtilValidate.isNotEmpty(docAttributes)) {
            for (Object da : docAttributes) {
                Debug.logInfo("Adding DocAttribute: " + da, module);
                docAttributeSet.add((DocAttribute) da);
            }
        }
        Doc myDoc = new SimpleDoc(bais, psInFormat, docAttributeSet);
        PrintService printer = null;
        // lookup the print service for the supplied printer name
        String printerName = (String) serviceContext.remove("printerName");
        if (UtilValidate.isNotEmpty(printerName)) {
            PrintServiceAttributeSet printServiceAttributes = new HashPrintServiceAttributeSet();
            printServiceAttributes.add(new PrinterName(printerName, locale));
            PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, printServiceAttributes);
            if (printServices.length > 0) {
                printer = printServices[0];
                Debug.logInfo("Using printer: " + printer.getName(), module);
                if (!printer.isDocFlavorSupported(psInFormat)) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotSupportDocFlavorFormat", UtilMisc.toMap("psInFormat", psInFormat, "printerName", printer.getName()), locale));
                }
            }
            if (printer == null) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotFound", UtilMisc.toMap("printerName", printerName), locale));
            }
        } else {
            // if no printer name was supplied, try to get the default printer
            printer = PrintServiceLookup.lookupDefaultPrintService();
            if (printer != null) {
                Debug.logInfo("No printer name supplied, using default printer: " + printer.getName(), module);
            }
        }
        if (printer == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotAvailable", locale));
        }
        PrintRequestAttributeSet praset = new HashPrintRequestAttributeSet();
        List<Object> printRequestAttributes = UtilGenerics.checkList(serviceContext.remove("printRequestAttributes"));
        if (UtilValidate.isNotEmpty(printRequestAttributes)) {
            for (Object pra : printRequestAttributes) {
                Debug.logInfo("Adding PrintRequestAttribute: " + pra, module);
                praset.add((PrintRequestAttribute) pra);
            }
        }
        DocPrintJob job = printer.createPrintJob();
        job.print(myDoc, praset);
    } catch (Exception e) {
        Debug.logError(e, "Error rendering [" + contentType + "]: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentRenderingError", UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale));
    }
    return ServiceUtil.returnSuccess();
}
Example 49
Project: osp-master  File: PrintUtils.java View source code
public static void printComponent(Component c) {
    // Get a list of all printers that can handle Printable objects.
    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
    PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, null);
    // Set some define printing attributes
    PrintRequestAttributeSet printAttributes = new HashPrintRequestAttributeSet();
    //printAttributes.add(OrientationRequested.LANDSCAPE); // landscape mode
    // PORTRAIT mode
    printAttributes.add(OrientationRequested.PORTRAIT);
    // print in mono
    printAttributes.add(Chromaticity.MONOCHROME);
    // highest resolution
    printAttributes.add(javax.print.attribute.standard.PrintQuality.HIGH);
    // Display a dialog that allows the user to select one of the
    // available printers and to edit the default attributes
    PrintService service = ServiceUI.printDialog(null, 100, 100, services, null, null, printAttributes);
    // If the user canceled, don't do anything
    if (service == null) {
        return;
    }
    // Now call a method defined below to finish the printing
    printToService(c, service, printAttributes);
}
Example 50
Project: trade-manager-master  File: ComponentPrintService.java View source code
/**
	 * Method print.
	 * 
	 * @param printMode
	 *            PrintMode
	 * @param headerFormat
	 *            MessageFormat
	 * @param footerFormat
	 *            MessageFormat
	 * @param showPrintDialog
	 *            boolean
	 * @param attr
	 *            PrintRequestAttributeSet
	 * @param interactive
	 *            boolean
	 * @param service
	 *            PrintService
	 * @return boolean
	 * @throws Exception
	 */
public boolean print(PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat, boolean showPrintDialog, PrintRequestAttributeSet attr, boolean interactive, PrintService service) throws Exception {
    // complain early if an invalid parameter is specified for headless mode
    boolean isHeadless = GraphicsEnvironment.isHeadless();
    if (isHeadless) {
        if (showPrintDialog) {
            throw new HeadlessException("Can't show print dialog.");
        }
        if (interactive) {
            throw new HeadlessException("Can't run interactively.");
        }
    }
    // Get a PrinterJob.
    // Do this before anything with side-effects since it may throw a
    // security exception - in which case we don't want to do anything else.
    final PrinterJob job = PrinterJob.getPrinterJob();
    if (attr == null) {
        attr = new HashPrintRequestAttributeSet();
    }
    // fetch the Printable
    Printable printable = this;
    DocFlavor doc_flavor = DocFlavor.INPUT_STREAM.JPEG;
    PrintRequestAttributeSet attr_set = new HashPrintRequestAttributeSet();
    PrintService[] services = PrintServiceLookup.lookupPrintServices(doc_flavor, attr_set);
    if (services.length > 0) {
        service = services[1];
    }
    if (interactive) {
        // wrap the Printable so that we can print on another thread
        printable = new ThreadSafePrintable(printable);
    }
    // set the printable on the PrinterJob
    job.setPrintable(printable);
    // if specified, set the PrintService on the PrinterJob
    if (service != null) {
        job.setPrintService(service);
    }
    // if requested, show the print dialog
    if (showPrintDialog && !job.printDialog(attr)) {
        // the user cancelled the print dialog
        return false;
    }
    // if not interactive, just print on this thread (no dialog)
    if (!interactive) {
        // do the printing
        job.print(attr);
        // we're done
        return true;
    }
    // make sure this is clear since we'll check it after
    printError = null;
    // to synchronize on
    final Object lock = new Object();
    // copied so we can access from the inner class
    final PrintRequestAttributeSet copyAttr = attr;
    // this runnable will be used to do the printing
    // (and save any throwables) on another thread
    Runnable runnable = new Runnable() {

        public void run() {
            try {
                // do the printing
                job.print(copyAttr);
            } catch (Throwable t) {
                synchronized (lock) {
                    printError = t;
                }
            }
        }
    };
    // start printing on another thread
    Thread th = new Thread(runnable, "PrinterThread");
    th.start();
    // look for any error that the printing may have generated
    Throwable pe;
    synchronized (lock) {
        pe = printError;
        printError = null;
    }
    // check the type of error and handle it
    if (pe != null) {
        // in this case, by the user
        if (pe instanceof PrinterAbortException) {
            return false;
        } else if (pe instanceof PrinterException) {
            throw (PrinterException) pe;
        } else if (pe instanceof Exception) {
            throw (Exception) pe;
        } else if (pe instanceof Error) {
            throw (Error) pe;
        }
        // can not happen
        throw new AssertionError(pe);
    }
    return true;
}
Example 51
Project: josm-plugins-master  File: PrintDialog.java View source code
protected void loadPrintSettings() {
    for (Collection<String> setting : Main.pref.getArray("print.settings.service-attributes")) {
        try {
            PrintServiceAttribute a = (PrintServiceAttribute) unmarshallPrintSetting(setting);
            if ("printer-name".equals(a.getName())) {
                job.setPrintService(PrintServiceLookup.lookupPrintServices(null, new HashPrintServiceAttributeSet(a))[0]);
            }
        } catch (PrinterExceptionReflectiveOperationException |  e) {
            Main.warn(e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }
    for (Collection<String> setting : Main.pref.getArray("print.settings.request-attributes")) {
        try {
            attrs.add(unmarshallPrintSetting(setting));
        } catch (ReflectiveOperationException e) {
            Main.warn(e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }
}
Example 52
Project: OpenDolphin-master  File: KartePDFImpl2.java View source code
//s.oh^ 2013/02/07 �刷対応
public static void printPDF(ArrayList<String> pdfFileNames) {
    if (pdfFileNames == null || pdfFileNames.size() <= 0)
        return;
    //s.oh^ 2013/06/24 �刷対応
    if (Project.getBoolean(Project.KARTE_PRINT_SHOWPDF)) {
        for (String pdfFileName : pdfFileNames) {
            File file = new File(pdfFileName);
            URI uri = file.toURI();
            try {
                Desktop.getDesktop().browse(uri);
            } catch (IOException ex) {
                Logger.getLogger(KartePDFImpl2.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    //s.oh$
    } else if (Project.getBoolean(Project.KARTE_PRINT_DIRECT)) {
        // ダイアログ�表示
        //// docフレー�を設定
        //DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
        //// �刷�求属性を設定
        //PrintRequestAttributeSet requestAttributes = new HashPrintRequestAttributeSet();
        //requestAttributes.add(new Copies(3));
        //requestAttributes.add(MediaSizeName.ISO_A4);
        //// �刷サービスを検出
        //PrintService service = PrintServiceLookup.lookupDefaultPrintService();
        //// �刷ジョブを作�
        //DocPrintJob job = service.createPrintJob();
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
        PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
        PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
        for (String pdfFileName : pdfFileNames) {
            DocPrintJob job = (defaultService == null) ? null : defaultService.createPrintJob();
            if (job == null) {
                if (printService.length > 0) {
                    job = printService[0].createPrintJob();
                }
            }
            if (job == null)
                continue;
            try {
                // docオブジェクトを生�
                FileInputStream data = new FileInputStream(pdfFileName);
                DocAttributeSet docAttributes = new HashDocAttributeSet();
                Doc doc = new SimpleDoc(data, flavor, docAttributes);
                // �刷
                job.print(doc, pras);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (PrintException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
            }
        }
    } else {
        // ダイアログ表示(プロパティ等ã?¯é?¸æŠžã?§ã??ã?ªã?„)
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
        PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
        PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
        if (printService.length > 0) {
            PrintService service = ServiceUI.printDialog(null, 200, 200, printService, defaultService, flavor, pras);
            if (service != null) {
                for (String pdfFileName : pdfFileNames) {
                    DocPrintJob job = service.createPrintJob();
                    //DocPrintJob job = defaultService.createPrintJob();
                    //FileOutputStream fis;
                    FileInputStream fis;
                    try {
                        fis = new FileInputStream(pdfFileName);
                        DocAttributeSet das = new HashDocAttributeSet();
                        Doc doc = new SimpleDoc(fis, flavor, das);
                        //Doc doc = new SimpleDoc(fis, flavor, null);
                        job.print(doc, pras);
                    //job.print(doc, null);
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(LaboTestOutputPDF.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (PrintException ex) {
                        Logger.getLogger(LaboTestOutputPDF.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                    }
                }
            }
        }
    }
}
Example 53
Project: saiku-adhoc-master  File: SaikuReportingComponent.java View source code
public boolean execute() throws Exception {
    final MasterReport report = getReport();
    try {
        final DefaultParameterContext parameterContext = new DefaultParameterContext(report);
        // open parameter context
        final ValidationResult vr = applyInputsToReportParameters(parameterContext, null);
        if (vr.isEmpty() == false) {
            return false;
        }
        parameterContext.close();
        if (isPrint()) {
            // handle printing
            // basic logic here is: get the default printer, attempt to resolve the user specified printer, default
            // back as needed
            PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
            if (StringUtils.isEmpty(getPrinter()) == false) {
                final PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
                for (final PrintService service : services) {
                    if (service.getName().equals(printer)) {
                        printService = service;
                    }
                }
                if ((printer == null) && (services.length > 0)) {
                    printService = services[0];
                }
            }
            Java14PrintUtil.printDirectly(report, printService);
            return true;
        }
        final String outputType = computeEffectiveOutputTarget();
        final ReportOutputHandler reportOutputHandler = createOutputHandlerForOutputType(outputType);
        if (reportOutputHandler == null) {
            log.warn(Messages.getInstance().getString("ReportPlugin.warnUnprocessableRequest", outputType));
            return false;
        }
        synchronized (reportOutputHandler.getReportLock()) {
            try {
                pageCount = reportOutputHandler.generate(report, acceptedPage, outputStream, getYieldRate());
                return pageCount != -1;
            } finally {
                reportOutputHandler.close();
            }
        }
    } catch (Throwable t) {
        log.error(Messages.getInstance().getString("ReportPlugin.executionFailed"), t);
    }
    // lets not pretend we were successfull, if the export type was not a valid one.
    return false;
}
Example 54
Project: servoy-client-master  File: JSApplication.java View source code
/**
	 * Get all the printer names in an array.
	 *
	 * @sample var printersArray = application.getPrinters();
	 *
	 * @return All printer names
	 */
@ServoyClientSupport(ng = false, wc = true, sc = true)
public String[] js_getPrinters() {
    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    PrintService[] printServices = PrintServiceLookup.lookupPrintServices(flavor, pras);
    if (printServices == null)
        return new String[0];
    String[] retval = new String[printServices.length];
    for (int i = 0; i < printServices.length; i++) {
        retval[i] = printServices[i].getName();
    }
    return retval;
}
Example 55
Project: get-organized-master  File: PrintDialog.java View source code
//GEN-LAST:event_ascDescComboBoxActionPerformed
private void nameComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
    //GEN-FIRST:event_nameComboBoxActionPerformed
    if (!initLoading) {
        for (PrintService printer : PrintServiceLookup.lookupPrintServices(null, null)) {
            if (printer.hashCode() == ((PrinterItem) nameComboBox.getSelectedItem()).code) {
                AttributeSet att = printer.getAttributes();
                for (Attribute a : att.toArray()) {
                    // Change to the new printer
                    curPrinter = printer;
                    String attributeName;
                    String attributeValue;
                    attributeName = a.getName();
                    attributeValue = att.get(a.getClass()).toString();
                    if (attributeName.equals("printer-is-accepting-jobs")) {
                        if (attributeValue.equals("accepting-jobs")) {
                            statusResponseLabel.setText("Online");
                        } else {
                            statusResponseLabel.setText("Offline");
                        }
                    } else if (attributeName.equals("color-supported")) {
                        if (attributeValue.equals("supported")) {
                            infoResponseLabel.setText("Color support");
                        } else {
                            infoResponseLabel.setText("No color support");
                        }
                    }
                }
            }
        }
    }
}
Example 56
Project: gtitool-master  File: PrintDialog.java View source code
/**
   * Initializes this {@link PrintDialog}.
   */
private final void initialize() {
    //$NON-NLS-1$
    this.normalFont = new Font("Dialog", Font.PLAIN, FONT_SIZE);
    this.headerFont = this.normalFont.deriveFont(Font.BOLD);
    // printer
    PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
    this.gui.jGTIComboBoxPrinter.setModel(new DefaultComboBoxModel(printServices));
    this.gui.jGTIComboBoxPrinter.setRenderer(new PrintServiceListCellRenderer());
    // margin
    this.gui.jSpinnerMarginLeft.setModel(new SpinnerNumberModel(20, 0, 50, 1));
    this.gui.jSpinnerMarginRight.setModel(new SpinnerNumberModel(20, 0, 50, 1));
    this.gui.jSpinnerMarginTop.setModel(new SpinnerNumberModel(20, 0, 50, 1));
    this.gui.jSpinnerMarginBottom.setModel(new SpinnerNumberModel(20, 0, 50, 1));
}
Example 57
Project: pentaho-platform-plugin-reporting-master  File: SimpleReportingComponent.java View source code
/**
   * Perform the primary function of this component, this is, to execute. This method will be invoked immediately
   * following a successful validate().
   *
   * @return true if successful execution
   * @throws Exception
   */
public boolean execute() throws Exception {
    final MasterReport report = getReport();
    int yieldRate = getYieldRate();
    if (yieldRate > 0) {
        report.getReportConfiguration().setConfigProperty("org.pentaho.reporting.engine.classic.core.YieldRate", String.valueOf(yieldRate));
    }
    try {
        final DefaultParameterContext parameterContext = new DefaultParameterContext(report);
        // open parameter context
        final ValidationResult vr = applyInputsToReportParameters(parameterContext, null);
        if (vr.isEmpty() == false) {
            return false;
        }
        parameterContext.close();
        if (isPrint()) {
            // handle printing
            // basic logic here is: get the default printer, attempt to resolve the user specified printer, default back as
            // needed
            PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
            if (StringUtils.isEmpty(getPrinter()) == false) {
                final PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
                for (final PrintService service : services) {
                    if (service.getName().equals(printer)) {
                        printService = service;
                    }
                }
                if ((printer == null) && (services.length > 0)) {
                    printService = services[0];
                }
            }
            Java14PrintUtil.printDirectly(report, printService);
            return true;
        }
        final String outputType = computeEffectiveOutputTarget();
        final ReportOutputHandler reportOutputHandler = createOutputHandlerForOutputType(outputType);
        if (reportOutputHandler == null) {
            log.warn(Messages.getInstance().getString("ReportPlugin.warnUnprocessableRequest", outputType));
            return false;
        }
        synchronized (reportOutputHandler.getReportLock()) {
            try {
                pageCount = reportOutputHandler.generate(report, acceptedPage, outputStream, getYieldRate());
                return pageCount != -1;
            } finally {
                reportOutputHandler.close();
            }
        }
    } catch (ReportDataFactoryException e) {
        throw e;
    } catch (ReportInterruptedException interrupt) {
        log.info("Report execution interrupted.");
    } catch (Exception e) {
        log.error(Messages.getInstance().getString("ReportPlugin.executionFailed"), e);
    }
    // lets not pretend we were successfull, if the export type was not a valid one.
    return false;
}
Example 58
Project: Electric8-master  File: FileMenu.java View source code
/**
     * This method implements the command to print the current window.
     */
public static void printCommand() {
    WindowFrame wf = WindowFrame.getCurrentWindowFrame();
    if (wf == null) {
        System.out.println("No current window to print");
        return;
    }
    Cell cell = WindowFrame.needCurCell();
    if (cell == null)
        return;
    PrinterJob pj = PrinterJob.getPrinterJob();
    pj.setJobName(wf.getTitle());
    PrintService[] printers = new PrintService[0];
    try {
        SecurityManager secman = System.getSecurityManager();
        secman.checkPrintJobAccess();
        //	    	printers = PrinterJob.lookupPrintServices();
        printers = PrintServiceLookup.lookupPrintServices(null, null);
    } catch (Exception e) {
    }
    // see if a default printer should be mentioned
    String pName = IOTool.getPrinterName();
    PrintService printerToUse = null;
    for (PrintService printer : printers) {
        if (pName.equals(printer.getName())) {
            printerToUse = printer;
            break;
        }
    }
    if (printerToUse != null) {
        try {
            pj.setPrintService(printerToUse);
        } catch (PrinterException e) {
            System.out.println("Printing error " + e);
        }
    }
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    if (pj.printDialog(aset)) {
        // disable double-buffering so prints look better
        JPanel overall = wf.getContent().getPanel();
        RepaintManager currentManager = RepaintManager.currentManager(overall);
        currentManager.setDoubleBufferingEnabled(false);
        if (!(wf.getContent() instanceof EditWindow)) {
            String message = "Can't print from a non-EditWindow.";
            System.out.println(message);
            JOptionPane.showMessageDialog(Main.getCurrentJFrame(), message, "Printing Cell", JOptionPane.ERROR_MESSAGE);
            return;
        }
        ElectricPrinter ep = getOutputPreferences(wf.getContent(), pj);
        Dimension oldSize = overall.getSize();
        ep.setOldSize(oldSize);
        // determine area to print
        EditWindow_ wnd = null;
        if (wf.getContent() instanceof EditWindow)
            wnd = (EditWindow_) wf.getContent();
        Rectangle2D printBounds = Output.getAreaToPrint(cell, false, wnd);
        ep.setRenderArea(printBounds);
        // initialize for content-specific printing
        if (!wf.getContent().initializePrinting(ep, pageFormat)) {
            String message = "Problems initializing printers. Check printer setup.";
            System.out.println(message);
            JOptionPane.showMessageDialog(Main.getCurrentJFrame(), message, "Printing Cell", JOptionPane.ERROR_MESSAGE);
            return;
        }
        printerToUse = pj.getPrintService();
        if (printerToUse != null)
            IOTool.setPrinterName(printerToUse.getName());
        SwingUtilities.invokeLater(new PrintJobAWT(wf, pj, oldSize, aset));
    }
}
Example 59
Project: classlib6-master  File: RasterPrinterJob.java View source code
/*
     * A convenience method which returns the default service
     * for 2D <code>PrinterJob</code>s.
     * May return null if there is no suitable default (although there
     * may still be 2D services available).
     * @return default 2D print service, or null.
     * @since     1.4
     */
protected static PrintService lookupDefaultPrintService() {
    PrintService service = PrintServiceLookup.lookupDefaultPrintService();
    /* Pageable implies Printable so checking both isn't strictly needed */
    if (service != null && service.isDocFlavorSupported(DocFlavor.SERVICE_FORMATTED.PAGEABLE) && service.isDocFlavorSupported(DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
        return service;
    } else {
        PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
        if (services.length > 0) {
            return services[0];
        }
    }
    return null;
}
Example 60
Project: Electric-VLSI-master  File: FileMenu.java View source code
/**
     * This method implements the command to print the current window.
     */
public static void printCommand() {
    WindowFrame wf = WindowFrame.getCurrentWindowFrame();
    if (wf == null) {
        System.out.println("No current window to print");
        return;
    }
    Cell cell = WindowFrame.needCurCell();
    if (cell == null)
        return;
    PrinterJob pj = PrinterJob.getPrinterJob();
    pj.setJobName(wf.getTitle());
    PrintService[] printers = new PrintService[0];
    try {
        SecurityManager secman = System.getSecurityManager();
        secman.checkPrintJobAccess();
        //	    	printers = PrinterJob.lookupPrintServices();
        printers = PrintServiceLookup.lookupPrintServices(null, null);
    } catch (Exception e) {
    }
    // see if a default printer should be mentioned
    String pName = IOTool.getPrinterName();
    PrintService printerToUse = null;
    for (PrintService printer : printers) {
        if (pName.equals(printer.getName())) {
            printerToUse = printer;
            break;
        }
    }
    if (printerToUse != null) {
        try {
            pj.setPrintService(printerToUse);
        } catch (PrinterException e) {
            System.out.println("Printing error " + e);
        }
    }
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    if (pj.printDialog(aset)) {
        // disable double-buffering so prints look better
        JPanel overall = wf.getContent().getPanel();
        RepaintManager currentManager = RepaintManager.currentManager(overall);
        currentManager.setDoubleBufferingEnabled(false);
        if (!(wf.getContent() instanceof EditWindow)) {
            String message = "Can't print from a non-EditWindow.";
            System.out.println(message);
            JOptionPane.showMessageDialog(Main.getCurrentJFrame(), message, "Printing Cell", JOptionPane.ERROR_MESSAGE);
            return;
        }
        ElectricPrinter ep = getOutputPreferences(wf.getContent(), pj);
        Dimension oldSize = overall.getSize();
        ep.setOldSize(oldSize);
        // determine area to print
        EditWindow_ wnd = null;
        if (wf.getContent() instanceof EditWindow)
            wnd = (EditWindow_) wf.getContent();
        Rectangle2D printBounds = Output.getAreaToPrint(cell, false, wnd);
        ep.setRenderArea(printBounds);
        // initialize for content-specific printing
        if (!wf.getContent().initializePrinting(ep, pageFormat)) {
            String message = "Problems initializing printers. Check printer setup.";
            System.out.println(message);
            JOptionPane.showMessageDialog(Main.getCurrentJFrame(), message, "Printing Cell", JOptionPane.ERROR_MESSAGE);
            return;
        }
        printerToUse = pj.getPrintService();
        if (printerToUse != null)
            IOTool.setPrinterName(printerToUse.getName());
        SwingUtilities.invokeLater(new PrintJobAWT(wf, pj, oldSize, aset));
    }
}
Example 61
Project: rt.equinox.framework-master  File: ClassLoadingBundleTests.java View source code
public void testContextFinderGetResource() throws IOException, InvalidSyntaxException {
    // get the context finder explicitly to test incase the thread context class loader has changed
    ClassLoader contextFinder = getContext().getService(getContext().getServiceReferences(ClassLoader.class, "(equinox.classloader.type=contextClassLoader)").iterator().next());
    // Using a resource we know is in java 8.
    String resource = "META-INF/services/javax.print.PrintServiceLookup";
    URL systemURL = ClassLoader.getSystemClassLoader().getResource(resource);
    assertNotNull("Did not find a parent resource: " + resource, systemURL);
    //should return the file defined in test bundle.
    URL url = contextFinder.getResource(resource);
    //the first element should be the file define in this bundle.
    List<URL> urls = Collections.list(contextFinder.getResources(resource));
    // make sure we have a resource located in the parent
    assertTrue("Did not find a parent resource: " + urls, urls.size() > 1);
    //assert failed as it return the one defined in parent class.
    assertEquals(url.toExternalForm(), urls.get(0).toExternalForm());
}
Example 62
Project: JamVM-PH-master  File: PrinterJob.java View source code
/**
   * Find and return 2D image print services.
   * 
   * This is the same as calling PrintServiceLookup.lookupPrintServices()
   * with Pageable service-specified DocFlavor.
   * @return Array of PrintService objects, could be empty.
   * @since 1.4
   */
public static PrintService[] lookupPrintServices() {
    return PrintServiceLookup.lookupPrintServices(new DocFlavor("application/x-java-jvm-local-objectref", "java.awt.print.Pageable"), null);
}
Example 63
Project: ae-awt-master  File: PrinterJob.java View source code
/**
     * A convenience method which looks up 2D print services.
     * Services returned from this method may be installed on
     * <code>PrinterJob</code>s which support print services.
     * Calling this method is equivalent to calling
     * {@link javax.print.PrintServiceLookup#lookupPrintServices(
     * DocFlavor, AttributeSet)
     * <code>PrintServiceLookup.lookupPrintServices()</code>}
     * and specifying a Pageable DocFlavor.
     * @return a possibly empty array of 2D print services.
     * @since     1.4
     */
public static PrintService[] lookupPrintServices() {
    return PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
}
Example 64
Project: JDK-master  File: PrinterJob.java View source code
/**
     * A convenience method which looks up 2D print services.
     * Services returned from this method may be installed on
     * <code>PrinterJob</code>s which support print services.
     * Calling this method is equivalent to calling
     * {@link javax.print.PrintServiceLookup#lookupPrintServices(
     * DocFlavor, AttributeSet)
     * <code>PrintServiceLookup.lookupPrintServices()</code>}
     * and specifying a Pageable DocFlavor.
     * @return a possibly empty array of 2D print services.
     * @since     1.4
     */
public static PrintService[] lookupPrintServices() {
    return PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
}
Example 65
Project: property-db-master  File: PrinterJob.java View source code
/** {@collect.stats} 
     * A convenience method which looks up 2D print services.
     * Services returned from this method may be installed on
     * <code>PrinterJob</code>s which support print services.
     * Calling this method is equivalent to calling
     * {@link javax.print.PrintServiceLookup#lookupPrintServices(
     * DocFlavor, AttributeSet)
     * <code>PrintServiceLookup.lookupPrintServices()</code>}
     * and specifying a Pageable DocFlavor.
     * @return a possibly empty array of 2D print services.
     * @since     1.4
     */
public static PrintService[] lookupPrintServices() {
    return PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
}