`

CUPSPrintServiceProvider

    博客分类:
  • j2ee
阅读更多
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
/** 
 * @author Igor A. Pyankov 
 */ 

package org.apache.harmony.x.print.cups;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Vector;

import javax.print.DocFlavor;
import javax.print.MultiDocPrintService;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.AttributeSet;

import org.apache.harmony.x.print.DefaultPrintService;
import org.apache.harmony.x.print.ipp.IppAttribute;
import org.apache.harmony.x.print.ipp.IppAttributeGroup;
import org.apache.harmony.x.print.ipp.IppClient;
import org.apache.harmony.x.print.ipp.IppOperation;
import org.apache.harmony.x.print.ipp.IppPrinter;
import org.apache.harmony.x.print.ipp.IppRequest;
import org.apache.harmony.x.print.ipp.IppResponse;


/*
 * The class extends PrintServiceLookup and is intended for
 * looking up CUPS/IPP printers
 * 
 * 1. The class allways looks printers on http://localhost:631
 *    This URL is default URL for default installation of CUPS server
 * 2. The class accepts two properties:
 *      print.cups.servers - a list of CUPS servers
 *      print.ipp.printers - a list of IPP printers 
 *                           (note, that CUPS printer is IPP printer too) 
 */
public class CUPSPrintServiceProvider extends PrintServiceLookup {
    private static String cupsdefault = "http://localhost:631";
    private static ArrayList services = new ArrayList();
    /*
     * 0 - no
     * 1 - more
     * 2 - more and more
     * ...
     */
    private static int verbose = 0;

    static {
        String verbose_property = (String) AccessController
                .doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        return System.getProperty("print.cups.verbose");
                    }
                });
        if (verbose_property != null) {
            try {
                Integer v = new Integer(verbose_property);
                setVerbose(v.intValue());
            } catch (NumberFormatException e) {
                setVerbose(0);
            }

        }
    }

    public CUPSPrintServiceProvider() {
        super();
    }

    /*
     * The method returns array of URLs of CUPS servers
     */
    private static String[] getCUPSServersByProperty() {
        ArrayList cupslist = new ArrayList();
        cupslist.add(cupsdefault);

        String cupspath = (String) AccessController
                .doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        return System.getProperty("print.cups.servers");
                    }
                });
        String pathsep = ",";
        if (cupspath != null && !cupspath.equals("")) {
            String[] cupss = cupspath.split(pathsep);
            for (int i = 0, ii = cupss.length; i < ii; i++) {
                if (!cupss[i].equals("")) {
                    try {
                        URI cupsuri = new URI(cupss[i]);
                        cupslist.add(cupsuri.toString());
                    } catch (URISyntaxException e) {
                        if (verbose > 0) {
                            System.err.println("CUPS url: " + cupss[i]);
                            e.printStackTrace();
                        } else {
                            // IGNORE bad URI exception
                        }
                    }
                }
            }
        }

        return (String[]) cupslist.toArray(new String[0]);
    }

    /*
     * The method returns array of URLs of IPP printers
     */
    private static String[] getIppPrintersByProperty() {
        ArrayList ipplist = new ArrayList();

        String ipppath = (String) AccessController
                .doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        return System.getProperty("print.ipp.printers");
                    }
                });
        String pathsep = ","; //System.getProperty("path.separator");
        if (ipppath != null && !ipppath.equals("")) {
            String[] ipps = ipppath.split(pathsep);
            for (int i = 0, ii = ipps.length; i < ii; i++) {
                if (!ipps[i].equals("")) {
                    try {
                        URI cupsuri = new URI(ipps[i]);
                        ipplist.add(cupsuri.toString());
                    } catch (URISyntaxException e) {
                        if (verbose > 0) {
                            System.err.println("IPP url: " + ipps[i]);
                            e.printStackTrace();
                        } else {
                            // IGNORE bad URI exception
                        }
                    }
                }
            }
        }

        return (String[]) ipplist.toArray(new String[0]);
    }

    /*
     * @see javax.print.PrintServiceLookup#getDefaultPrintService()
     */
    public PrintService getDefaultPrintService() {
        synchronized (this) {
            String defaultService = findDefaultPrintService();

            if (defaultService != null) {
                PrintService service = getServiceStored(defaultService,
                        services);
                if (service != null) {
                    return service;
                }

                CUPSClient client;
                try {
                    client = new CUPSClient(defaultService);
                    service = new DefaultPrintService(defaultService, client);
                    services.add(service);
                    return service;
                } catch (PrintException e) {
                    // just ignore
                    e.printStackTrace();
                }
            }

            if (services.size() == 0) {
                getPrintServices();
            }
            if (services.size() > 0) {
                return (PrintService) services.get(0);
            }

        }
        return null;
    }

    /*
     * @see javax.print.PrintServiceLookup#getPrintServices()
     */
    public PrintService[] getPrintServices() {
        synchronized (this) {
            String[] serviceNames = findPrintServices();
            if (serviceNames == null || serviceNames.length == 0) {
                services.clear();
                return new PrintService[0];
            }

            ArrayList newServices = new ArrayList();
            for (int i = 0; i < serviceNames.length; i++) {
                PrintService service = getServiceStored(serviceNames[i],
                        services);
                if (service != null) {
                    newServices.add(service);
                } else if (getServiceStored(serviceNames[i], newServices) == null) {
                    try {
                        CUPSClient client = new CUPSClient(serviceNames[i]);

                        service = new DefaultPrintService(serviceNames[i],
                                client);
                        newServices.add(service);
                    } catch (PrintException e) {
                        // just ignore
                        e.printStackTrace();
                    }
                }
            }

            services.clear();
            services = newServices;
            return (services.size() == 0) ? new PrintService[0]
                    : (PrintService[]) services.toArray(new PrintService[0]);
        }
    }

    /*
     * find printers on particular CUPS server
     */
    private PrintService[] getCUPSPrintServices(String cups) {
        synchronized (this) {
            // just update static field 'services'
            findPrintServices();

            // next find services on server 'cups'
            String[] serviceNames = (String[]) findCUPSPrintServices(cups)
                    .toArray(new String[0]);
            if (serviceNames == null || serviceNames.length == 0) {
                return new PrintService[0];
            }

            // return only those are stored in field 'services'
            ArrayList newServices = new ArrayList();
            for (int i = 0; i < serviceNames.length; i++) {
                PrintService service = getServiceStored(serviceNames[i],
                        services);
                if (service != null) {
                    newServices.add(service);
                }
            }

            return (newServices.size() == 0) ? new PrintService[0]
                    : (PrintService[]) services.toArray(new PrintService[0]);
        }
    }

    /*
     * find printers on localhost only
     */
    public PrintService[] getPrintServicesOnLocalHost() {
        return getCUPSPrintServices(cupsdefault);
    }

    /*
     * find service which name is same as serviceName
     */
    private PrintService getServiceStored(String serviceName,
            ArrayList servicesList) {
        for (int i = 0; i < servicesList.size(); i++) {
            PrintService service = (PrintService) servicesList.get(i);
            if (service.getName().equals(serviceName)) {
                return service;
            }
        }
        return null;
    }

    /*
     * @see javax.print.PrintServiceLookup#getPrintServices(javax.print.DocFlavor
     *      , javax.print.attribute.AttributeSet)
     */
    public PrintService[] getPrintServices(DocFlavor flavor,
            AttributeSet attributes) {
        PrintService[] cupsservices = getPrintServices();
        if (flavor == null && attributes == null) {
            return cupsservices;
        }

        ArrayList requestedServices = new ArrayList();
        for (int i = 0; i < cupsservices.length; i++) {
            try {
                AttributeSet unsupportedSet = cupsservices[i]
                        .getUnsupportedAttributes(flavor, attributes);
                if (unsupportedSet == null) {
                    requestedServices.add(cupsservices[i]);
                }
            } catch (IllegalArgumentException iae) {
                // DocFlavor not supported by service, skiping.
            }
        }
        return (requestedServices.size() == 0) ? new PrintService[0]
                : (PrintService[]) requestedServices
                        .toArray(new PrintService[0]);
    }

    /*
     * @see javax.print.PrintServiceLookup#getMultiDocPrintServices(javax.print.DocFlavor[]
     *      , javax.print.attribute.AttributeSet)
     */
    public MultiDocPrintService[] getMultiDocPrintServices(DocFlavor[] flavors,
            AttributeSet attributes) {
        // No multidoc print services available, yet.
        return new MultiDocPrintService[0];
    }

    /*
     * find all printers
     */
    private static String[] findPrintServices() {
        ArrayList ippservices = new ArrayList();

        /*
         * First, find on localhost and servers from print.cups.servers property
         * and add them to full list
         */
        String[] cupses = CUPSPrintServiceProvider.getCUPSServersByProperty();
        for (int j = 0; j < cupses.length; j++) {
            ippservices.addAll(findCUPSPrintServices(cupses[j]));
        }

        /*
         * Then, check URLs from print.ipp.printers property and 
         * if is valid ipp printer add them to full list
         */
        String[] ippp = CUPSPrintServiceProvider.getIppPrintersByProperty();
        for (int j = 0; j < ippp.length; j++) {
            try {
                URI ippuri = new URI(ippp[j]);
                IppPrinter printer = new IppPrinter(ippuri);
                IppResponse response;

                response = printer.requestPrinterAttributes(
                        "printer-uri-supported", null);

                Vector gg = response
                        .getGroupVector(IppAttributeGroup.TAG_GET_PRINTER_ATTRIBUTES);
                if (gg != null) {
                    for (int i = 0, ii = gg.size(); i < ii; i++) {
                        IppAttributeGroup g = (IppAttributeGroup) gg.get(i);
                        int ai = g.findAttribute("printer-uri-supported");

                        if (ai >= 0) {
                            IppAttribute a = (IppAttribute) g.get(ai);
                            Vector v = a.getValue();
                            if (v.size() > 0) {
                                ippservices.add(new String((byte[]) v.get(0)));
                            }
                        }
                    }
                }
            } catch (Exception e) {
                if (verbose > 0) {
                    System.err.println("IPP url: " + ippp[j]);
                    e.printStackTrace();
                } else {
                    // IGNORE - connection refused due to no server, etc.
                }
            }
        }

        // return array of printers
        return (String[]) ippservices.toArray(new String[0]);
    }

    /*
     * find ipp printers on CUPS server 'cups'
     */
    public static ArrayList findCUPSPrintServices(String cups) {
        ArrayList ippservices = new ArrayList();

        URI cupsuri = null;
        IppClient c = null;
        IppRequest request;
        IppResponse response;
        IppAttributeGroup agroup;
        Vector va = new Vector();

        request = new IppRequest(1, 1, IppOperation.TAG_CUPS_GET_PRINTERS,
                "utf-8", "en-us");
        agroup = request.getGroup(IppAttributeGroup.TAG_OPERATION_ATTRIBUTES);
        va.add("printer-uri-supported".getBytes());
        agroup.add(new IppAttribute(IppAttribute.TAG_KEYWORD,
                "requested-attributes", va));

        try {
            cupsuri = new URI(cups);
            c = new IppClient(cupsuri);

            response = c.request(request.getBytes());

            Vector gg = response
                    .getGroupVector(IppAttributeGroup.TAG_GET_PRINTER_ATTRIBUTES);
            if (gg != null) {
                for (int i = 0, ii = gg.size(); i < ii; i++) {
                    IppAttributeGroup g = (IppAttributeGroup) gg.get(i);
                    int ai = g.findAttribute("printer-uri-supported");

                    if (ai >= 0) {
                        IppAttribute a = (IppAttribute) g.get(ai);
                        Vector v = a.getValue();
                        if (v.size() > 0) {
                            ippservices.add(new String((byte[]) v.get(0)));
                        }
                    }
                }
            }
        } catch (Exception e) {
            if (verbose > 0) {
                System.err.println("CUPS url: " + cups);
                System.err.println("CUPS uri: " + cupsuri);
                System.err.println("Ipp client: " + c);
                System.err.println(request.toString());
                e.printStackTrace();
            } else {
                // IGNORE - connection refused due to no server, etc.
            }
        }

        return ippservices;
    }

    /*
     * find default printer
     * At first, try to find default printer on CUPS servers and return first found 
     * If failed, return first found IPP printer
     * If failed return null
     */
    private static String findDefaultPrintService() {
        String serviceName = null;

        String[] cupses = CUPSPrintServiceProvider.getCUPSServersByProperty();
        for (int i = 0; i < cupses.length; i++) {
            try {
                URI cupsuri = new URI(cupses[i]);
                IppClient c = new IppClient(cupsuri);
                IppRequest request;
                IppResponse response;
                IppAttributeGroup agroup;
                Vector va = new Vector();

                request = new IppRequest(1, 1,
                        IppOperation.TAG_CUPS_GET_DEFAULT, "utf-8", "en-us");
                agroup = request
                        .getGroup(IppAttributeGroup.TAG_OPERATION_ATTRIBUTES);
                va.add("printer-uri-supported".getBytes());
                agroup.add(new IppAttribute(IppAttribute.TAG_KEYWORD,
                        "requested-attributes", va));

                response = c.request(request.getBytes());

                IppAttributeGroup g = response
                        .getGroup(IppAttributeGroup.TAG_GET_PRINTER_ATTRIBUTES);
                if (g != null) {
                    int ai = g.findAttribute("printer-uri-supported");

                    if (ai >= 0) {
                        IppAttribute a = (IppAttribute) g.get(ai);
                        Vector v = a.getValue();
                        if (v.size() > 0) {
                            serviceName = new String((byte[]) v.get(0));
                            break;
                        }
                    }
                }
            } catch (URISyntaxException e) {
                //e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }
        if (serviceName != null && !serviceName.equals("")) {
            return serviceName;
        }

        String[] ippp = CUPSPrintServiceProvider.getIppPrintersByProperty();
        for (int i = 0; i < ippp.length; i++) {
            try {
                URI ippuri = new URI(ippp[i]);
                IppClient c = new IppClient(ippuri);
                IppRequest request;
                IppResponse response;
                IppAttributeGroup agroup;
                Vector va = new Vector();

                request = new IppRequest(1, 1,
                        IppOperation.GET_PRINTER_ATTRIBUTES, "utf-8", "en-us");
                agroup = request
                        .getGroup(IppAttributeGroup.TAG_OPERATION_ATTRIBUTES);
                va.add("printer-uri-supported".getBytes());
                agroup.add(new IppAttribute(IppAttribute.TAG_KEYWORD,
                        "requested-attributes", va));

                response = c.request(request.getBytes());

                IppAttributeGroup g = response
                        .getGroup(IppAttributeGroup.TAG_GET_PRINTER_ATTRIBUTES);
                if (g != null) {
                    int ai = g.findAttribute("printer-uri-supported");

                    if (ai >= 0) {
                        IppAttribute a = (IppAttribute) g.get(ai);
                        Vector v = a.getValue();
                        if (v.size() > 0) {
                            serviceName = new String((byte[]) v.get(0));
                            break;
                        }
                    }
                }
            } catch (URISyntaxException e) {
                //e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }

        return serviceName;
    }

    public static int isVerbose() {
        return verbose;
    }

    public static void setVerbose(int newverbose) {
        CUPSPrintServiceProvider.verbose = newverbose;
        CUPSClient.setVerbose(newverbose);
    }
}
分享到:
评论

相关推荐

    电子商务之价格优化算法:梯度下降:机器学习在价格优化中的角色.docx

    电子商务之价格优化算法:梯度下降:机器学习在价格优化中的角色.docx

    ToadforOracle与Oracle数据库版本兼容性教程.docx

    ToadforOracle与Oracle数据库版本兼容性教程.docx

    browser360-cn-stable-13.3.1016.4-1-amd64.deb

    360浏览器银河麒麟版 for X86 适配兆芯 / 海光 / intel / AMD CPU

    基于React.js和Material-UI个人作品集网站模板(附源码+说明文档).zip

    使用React.js构建,提供多种主题可供选择,并且易于定制。该项目旨在帮助开发者和自由职业者创建自己的个性化投资组合。 主要功能点 多种主题可供选择,包括绿色、黑白、蓝色、红色、橙色、紫色、粉色和黄色 易于定制,可以在src/data文件夹中更新个人信息 包含主页、关于、简历、教育、技能、经验、项目、成就、服务、推荐信、博客和联系等多个部分 支持通过Google表单收集联系信息 提供SEO优化建议 支持多种部署方式,如Netlify、Firebase、Heroku和GitHub Pages 技术栈主要 React.js Material-UI Axios React-fast-marquee React-helmet React-icons React-reveal React-router-dom React-router-hash-link React-slick Slick-carousel Validator

    中小型企业财务管理系统 SSM毕业设计 附带论文.zip

    中小型企业财务管理系统 SSM毕业设计 附带论文 启动教程:https://www.bilibili.com/video/BV1GK1iYyE2B

    apsw-3.38.5.post1-cp39-cp39-win_amd64.whl.rar

    python whl离线安装包 pip安装失败可以尝试使用whl离线安装包安装 第一步 下载whl文件,注意需要与python版本配套 python版本号、32位64位、arm或amd64均有区别 第二步 使用pip install XXXXX.whl 命令安装,如果whl路径不在cmd窗口当前目录下,需要带上路径 WHL文件是以Wheel格式保存的Python安装包, Wheel是Python发行版的标准内置包格式。 在本质上是一个压缩包,WHL文件中包含了Python安装的py文件和元数据,以及经过编译的pyd文件, 这样就使得它可以在不具备编译环境的条件下,安装适合自己python版本的库文件。 如果要查看WHL文件的内容,可以把.whl后缀名改成.zip,使用解压软件(如WinRAR、WinZIP)解压打开即可查看。 为什么会用到whl文件来安装python库文件呢? 在python的使用过程中,我们免不了要经常通过pip来安装自己所需要的包, 大部分的包基本都能正常安装,但是总会遇到有那么一些包因为各种各样的问题导致安装不了的。 这时我们就可以通过尝试去Python安装包大全中(whl包下载)下载whl包来安装解决问题。

    电子商务之价格优化算法:线性回归:价格优化策略实施.docx

    电子商务之价格优化算法:线性回归:价格优化策略实施.docx

    工业数字化转型的关键技术及其应用场景解析

    内容概要:报告详细介绍了企业数字化转型的驱动因素、数字化转型方案分类及其应用场景,重点关注了云计算、超连接、数字孪生、人工智能、分布式账本、增材制造、人机接口、数据共享、工业物联网等关键技术。这些技术不仅支持了企业的运营效率提升和业务模式创新,也为实现更快、更开放、更高效的数字化转型提供了支撑。报告最后提出了企业实施数字化转型的六个步骤。 适合人群:企业高级管理人员、技术人员、咨询顾问,以及对工业数字化转型感兴趣的读者。 使用场景及目标:帮助企业制定和实施数字化转型策略,优化运营模式,提升业务效率,增强市场竞争力。同时,也可作为政府部门、研究机构和行业协会的参考文献。 其他说明:报告中提到的关键技术及其应用场景对企业数字化转型具有重要的指导意义,特别是对于那些希望通过数字化转型实现业务创新和升级的企业。

    基于java的线上选课系统的设计与实现答辩PPT.pptx

    基于java的线上选课系统的设计与实现答辩PPT.pptx

    原版aggdraw-1.3.15-cp311-cp311-win_arm64.whl-下载即用直接pip安装.zip

    安装前的准备 1、安装Python:确保你的计算机上已经安装了Python。你可以在命令行中输入python --version或python3 --version来检查是否已安装以及安装的版本。 个人建议:在anaconda中自建不同python版本的环境,方法如下(其他版本照葫芦画瓢): 比如创建python3.8环境,anaconda命令终端输入:conda create -n py38 python==3.8 2、安装pip:pip是Python的包管理工具,用于安装和管理Python包。你可以通过输入pip --version或pip3 --version来检查pip是否已安装。 安装WHL安装包 1、打开命令行(或打开anaconda命令行终端): 在Windows上,你可以搜索“cmd”或“命令提示符”并打开它。 在macOS或Linux上,你可以打开“终端”。 2、cd到whl文件所在目录安装: 使用cd命令导航到你下载的whl文件所在的文件夹。 终端输入:pip install xxx.whl安装即可(xxx.whl指的是csdn下载解压出来的whl) 3、等待安装完成: 命令行会显示安装进度,并在安装完成后返回提示符。 以上是简单安装介绍,小白也能会,简单好用,从此再也不怕下载安装超时问题。 使用过程遇到问题可以私信,我可以帮你解决! 收起

    电子商务之价格优化算法:贝叶斯定价:贝叶斯网络在电子商务定价中的应用.docx

    电子商务之价格优化算法:贝叶斯定价:贝叶斯网络在电子商务定价中的应用.docx

    IMG_20241105_235746.jpg

    IMG_20241105_235746.jpg

    基于java的毕业设计选题系统答辩PPT.pptx

    基于java的毕业设计选题系统答辩PPT.pptx

    专升本考试资料全套.7z

    专升本考试资料全套.7z

    Trustwave DbProtect:数据库活动监控策略制定.docx

    Trustwave DbProtect:数据库活动监控策略制定.docx

    VB程序实例-CD-ROM开关.zip

    基于VB的程序实例,可供参考学习使用

    课设毕设基于SpringBoot+Vue的教育资源共享平台源码可运行.zip

    本压缩包资源说明,你现在往下拉可以看到压缩包内容目录 我是批量上传的基于SpringBoot+Vue的项目,所以描述都一样;有源码有数据库脚本,系统都是测试过可运行的,看文件名即可区分项目~ |Java|SpringBoot|Vue|前后端分离| 开发语言:Java 框架:SpringBoot,Vue JDK版本:JDK1.8 数据库:MySQL 5.7+(推荐5.7,8.0也可以) 数据库工具:Navicat 开发软件: idea/eclipse(推荐idea) Maven包:Maven3.3.9+ 系统环境:Windows/Mac

    基于Thinkphp5框架的Java插件设计源码

    该源码项目是一款基于Thinkphp5框架的Java插件设计,包含114个文件,其中Java源文件60个,PNG图片32个,XML配置文件7个,GIF图片7个,Git忽略文件1个,LICENSE文件1个,Markdown文件1个,Xmind文件1个,Idea项目文件1个,以及JAR文件1个。

    数据库开发和管理最佳实践.pdf

    数据库开发和管理最佳实践.pdf

    课设毕设基于SpringBoot+Vue的农场投入品运营线上管理系统源码可运行.zip

    本压缩包资源说明,你现在往下拉可以看到压缩包内容目录 我是批量上传的基于SpringBoot+Vue的项目,所以描述都一样;有源码有数据库脚本,系统都是测试过可运行的,看文件名即可区分项目~ |Java|SpringBoot|Vue|前后端分离| 开发语言:Java 框架:SpringBoot,Vue JDK版本:JDK1.8 数据库:MySQL 5.7+(推荐5.7,8.0也可以) 数据库工具:Navicat 开发软件: idea/eclipse(推荐idea) Maven包:Maven3.3.9+ 系统环境:Windows/Mac

Global site tag (gtag.js) - Google Analytics