PrintServiceLookupProvider.java 17.8 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
 */

package sun.print;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import javax.print.DocFlavor;
import javax.print.MultiDocPrintService;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.Attribute;
import javax.print.attribute.AttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.HashPrintServiceAttributeSet;
import javax.print.attribute.PrintRequestAttribute;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.PrintServiceAttribute;
import javax.print.attribute.PrintServiceAttributeSet;
import javax.print.attribute.standard.PrinterName;

50
public class PrintServiceLookupProvider extends PrintServiceLookup {
D
duke 已提交
51 52 53 54 55

    private String defaultPrinter;
    private PrintService defaultPrintService;
    private String[] printers; /* excludes the default printer */
    private PrintService[] printServices; /* includes the default printer */
56 57 58
    private static boolean pollServices = true;
    private static final int DEFAULT_MINREFRESH = 240;  // 4 minutes
    private static int minRefreshTime = DEFAULT_MINREFRESH;
D
duke 已提交
59 60

    static {
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
        /* The system property "sun.java2d.print.polling"
         * can be used to force the printing code to poll or not poll
         * for PrintServices.
         */
        String pollStr = java.security.AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction("sun.java2d.print.polling"));

        if (pollStr != null) {
            if (pollStr.equalsIgnoreCase("false")) {
                pollServices = false;
            }
        }

        /* The system property "sun.java2d.print.minRefreshTime"
         * can be used to specify minimum refresh time (in seconds)
         * for polling PrintServices.  The default is 240.
         */
        String refreshTimeStr = java.security.AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction(
                "sun.java2d.print.minRefreshTime"));

        if (refreshTimeStr != null) {
            try {
                minRefreshTime = (Integer.valueOf(refreshTimeStr)).intValue();
            } catch (NumberFormatException e) {
            }
            if (minRefreshTime < DEFAULT_MINREFRESH) {
                minRefreshTime = DEFAULT_MINREFRESH;
            }
        }

D
duke 已提交
92
        java.security.AccessController.doPrivileged(
93 94 95 96 97 98
            new java.security.PrivilegedAction<Void>() {
                public Void run() {
                    System.loadLibrary("awt");
                    return null;
                }
            });
D
duke 已提交
99 100 101 102 103 104 105 106
    }

    /* The singleton win32 print lookup service.
     * Code that is aware of this field and wants to use it must first
     * see if its null, and if so instantiate it by calling a method such as
     * javax.print.PrintServiceLookup.defaultPrintService() so that the
     * same instance is stored there.
     */
107
    private static PrintServiceLookupProvider win32PrintLUS;
D
duke 已提交
108 109

    /* Think carefully before calling this. Preferably don't call it. */
110
    public static PrintServiceLookupProvider getWin32PrintLUS() {
D
duke 已提交
111 112 113 114 115 116 117 118 119 120
        if (win32PrintLUS == null) {
            /* This call is internally synchronized.
             * When it returns an instance of this class will have
             * been instantiated - else there's a JDK internal error.
             */
            PrintServiceLookup.lookupDefaultPrintService();
        }
        return win32PrintLUS;
    }

121
    public PrintServiceLookupProvider() {
D
duke 已提交
122 123 124 125 126 127 128 129 130 131 132

        if (win32PrintLUS == null) {
            win32PrintLUS = this;

            String osName = AccessController.doPrivileged(
                new sun.security.action.GetPropertyAction("os.name"));
            // There's no capability for Win98 to refresh printers.
            // See "OpenPrinter" for more info.
            if (osName != null && osName.startsWith("Windows 98")) {
                return;
            }
133 134
            // start the local printer listener thread
            Thread thr = new PrinterChangeListener();
D
duke 已提交
135 136
            thr.setDaemon(true);
            thr.start();
137 138 139 140 141 142 143

            if (pollServices) {
                // start the remote printer listener thread
                Thread remThr = new RemotePrinterChangeListener();
                remThr.setDaemon(true);
                remThr.start();
            }
D
duke 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
        } /* else condition ought to never happen! */
    }

    /* Want the PrintService which is default print service to have
     * equality of reference with the equivalent in list of print services
     * This isn't required by the API and there's a risk doing this will
     * lead people to assume its guaranteed.
     */
    public synchronized PrintService[] getPrintServices() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkPrintJobAccess();
        }
        if (printServices == null) {
            refreshServices();
        }
        return printServices;
    }

    private synchronized void refreshServices() {
        printers = getAllPrinterNames();
        if (printers == null) {
            // In Windows it is safe to assume no default if printers == null so we
            // don't get the default.
            printServices = new PrintService[0];
            return;
        }

        PrintService[] newServices = new PrintService[printers.length];
        PrintService defService = getDefaultPrintService();
        for (int p = 0; p < printers.length; p++) {
            if (defService != null &&
                printers[p].equals(defService.getName())) {
                newServices[p] = defService;
            } else {
                if (printServices == null) {
                    newServices[p] = new Win32PrintService(printers[p]);
                } else {
                    int j;
                    for (j = 0; j < printServices.length; j++) {
                        if ((printServices[j]!= null) &&
                            (printers[p].equals(printServices[j].getName()))) {
                            newServices[p] = printServices[j];
                            printServices[j] = null;
                            break;
                        }
                    }
                    if (j == printServices.length) {
                        newServices[p] = new Win32PrintService(printers[p]);
                    }
                }
            }
        }

        // Look for deleted services and invalidate these
        if (printServices != null) {
            for (int j=0; j < printServices.length; j++) {
                if ((printServices[j] instanceof Win32PrintService) &&
                    (!printServices[j].equals(defaultPrintService))) {
                    ((Win32PrintService)printServices[j]).invalidateService();
                }
            }
        }
        printServices = newServices;
    }


    public synchronized PrintService getPrintServiceByName(String name) {

        if (name == null || name.equals("")) {
            return null;
        } else {
            /* getPrintServices() is now very fast. */
            PrintService[] printServices = getPrintServices();
            for (int i=0; i<printServices.length; i++) {
                if (printServices[i].getName().equals(name)) {
                    return printServices[i];
                }
            }
            return null;
        }
    }

    boolean matchingService(PrintService service,
                            PrintServiceAttributeSet serviceSet) {
        if (serviceSet != null) {
            Attribute [] attrs =  serviceSet.toArray();
            Attribute serviceAttr;
            for (int i=0; i<attrs.length; i++) {
                serviceAttr
                    = service.getAttribute((Class<PrintServiceAttribute>)attrs[i].getCategory());
                if (serviceAttr == null || !serviceAttr.equals(attrs[i])) {
                    return false;
                }
            }
        }
        return true;
    }

    public PrintService[] getPrintServices(DocFlavor flavor,
                                           AttributeSet attributes) {

        SecurityManager security = System.getSecurityManager();
        if (security != null) {
          security.checkPrintJobAccess();
        }
        PrintRequestAttributeSet requestSet = null;
        PrintServiceAttributeSet serviceSet = null;

        if (attributes != null && !attributes.isEmpty()) {

            requestSet = new HashPrintRequestAttributeSet();
            serviceSet = new HashPrintServiceAttributeSet();

            Attribute[] attrs = attributes.toArray();
            for (int i=0; i<attrs.length; i++) {
                if (attrs[i] instanceof PrintRequestAttribute) {
                    requestSet.add(attrs[i]);
                } else if (attrs[i] instanceof PrintServiceAttribute) {
                    serviceSet.add(attrs[i]);
                }
            }
        }

        /*
         * Special case: If client is asking for a particular printer
         * (by name) then we can save time by getting just that service
         * to check against the rest of the specified attributes.
         */
        PrintService[] services = null;
        if (serviceSet != null && serviceSet.get(PrinterName.class) != null) {
            PrinterName name = (PrinterName)serviceSet.get(PrinterName.class);
            PrintService service = getPrintServiceByName(name.getValue());
            if (service == null || !matchingService(service, serviceSet)) {
                services = new PrintService[0];
            } else {
                services = new PrintService[1];
                services[0] = service;
            }
        } else {
            services = getPrintServices();
        }

        if (services.length == 0) {
            return services;
        } else {
            ArrayList matchingServices = new ArrayList();
            for (int i=0; i<services.length; i++) {
                try {
                    if (services[i].
                        getUnsupportedAttributes(flavor, requestSet) == null) {
                        matchingServices.add(services[i]);
                    }
                } catch (IllegalArgumentException e) {
                }
            }
            services = new PrintService[matchingServices.size()];
            return (PrintService[])matchingServices.toArray(services);
        }
    }

    /*
     * return empty array as don't support multi docs
     */
    public MultiDocPrintService[]
        getMultiDocPrintServices(DocFlavor[] flavors,
                                 AttributeSet attributes) {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
          security.checkPrintJobAccess();
        }
        return new MultiDocPrintService[0];
    }


    public synchronized PrintService getDefaultPrintService() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
          security.checkPrintJobAccess();
        }


        // Windows does not have notification for a change in default
        // so we always get the latest.
        defaultPrinter = getDefaultPrinterName();
        if (defaultPrinter == null) {
            return null;
        }

        if ((defaultPrintService != null) &&
            defaultPrintService.getName().equals(defaultPrinter)) {

            return defaultPrintService;
        }

         // Not the same as default so proceed to get new PrintService.

        // clear defaultPrintService
        defaultPrintService = null;

        if (printServices != null) {
            for (int j=0; j<printServices.length; j++) {
                if (defaultPrinter.equals(printServices[j].getName())) {
                    defaultPrintService = printServices[j];
                    break;
                }
            }
        }

        if (defaultPrintService == null) {
            defaultPrintService = new Win32PrintService(defaultPrinter);
        }
        return defaultPrintService;
    }

    class PrinterChangeListener extends Thread {
        long chgObj;
        PrinterChangeListener() {
            chgObj = notifyFirstPrinterChange(null);
        }

        public void run() {
            if (chgObj != -1) {
                while (true) {
                    // wait for configuration to change
                    if (notifyPrinterChange(chgObj) != 0) {
                        try {
                            refreshServices();
                        } catch (SecurityException se) {
                            break;
                        }
                    } else {
                        notifyClosePrinterChange(chgObj);
                        break;
                    }
                }
            }
        }
    }

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    /* Windows provides *PrinterChangeNotification* functions that provides
       information about printer status changes of the local printers but not
       network printers.
       Alternatively, Windows provides a way thro' which one can get the
       network printer status changes by using WMI, RegistryKeyChange combination,
       which is a slightly complex mechanism.
       The Windows WMI offers an async and sync method to read thro' registry
       via the WQL query. The async method is considered dangerous as it leaves
       open a channel until we close it. But the async method has the advantage of
       being notified of a change in registry by calling callback without polling for it.
       The sync method uses the polling mechanism to notify.
       RegistryValueChange cannot be used in combination with WMI to get registry
       value change notification because of an error that may be generated because the
       scope of the query would be too big to handle(at times).
       Hence an alternative mechanism is choosen via the EnumPrinters by polling for the
       count of printer status changes(add\remove) and based on it update the printers
       list.
    */
    class RemotePrinterChangeListener extends Thread {
403
        private String[] prevRemotePrinters = null;
404 405 406 407 408 409

        RemotePrinterChangeListener() {
            prevRemotePrinters = getRemotePrintersNames();
        }

        boolean doCompare(String[] str1, String[] str2) {
410 411 412 413 414 415
            if (str1 == null && str2 == null) {
                return false;
            } else if (str1 == null || str2 == null) {
                return true;
            }

416 417 418 419 420
            if (str1.length != str2.length) {
                return true;
            } else {
                for (int i = 0;i < str1.length;i++) {
                    for (int j = 0;j < str2.length;j++) {
421 422 423 424 425 426 427 428 429 430 431 432
                        // skip if both are nulls
                        if (str1[i] == null && str2[j] == null) {
                            continue;
                        }

                        // return true if there is a 'difference' but
                        // no need to access the individual string
                        if (str1[i] == null || str2[j] == null) {
                            return true;
                        }

                        // do comparison only if they are non-nulls
433 434 435 436 437 438 439 440 441 442 443 444 445
                        if (!str1[i].equals(str2[j])) {
                            return true;
                        }
                    }
                }
            }

            return false;
        }

        @Override
        public void run() {
            while (true) {
446 447 448
                if (prevRemotePrinters != null && prevRemotePrinters.length > 0) {
                    String[] currentRemotePrinters = getRemotePrintersNames();
                    if (doCompare(prevRemotePrinters, currentRemotePrinters)) {
449

450 451 452
                        // updated the printers data
                        // printers list now contains both local and network printer data
                        refreshServices();
453

454 455 456 457 458
                        // store the current data for next comparison
                        prevRemotePrinters = currentRemotePrinters;
                    }
                } else {
                    prevRemotePrinters = getRemotePrintersNames();
459 460 461 462 463 464 465 466 467 468 469
                }

                try {
                    Thread.sleep(minRefreshTime * 1000);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }
    }

D
duke 已提交
470 471 472 473 474
    private native String getDefaultPrinterName();
    private native String[] getAllPrinterNames();
    private native long notifyFirstPrinterChange(String printer);
    private native void notifyClosePrinterChange(long chgObj);
    private native int notifyPrinterChange(long chgObj);
475
    private native String[] getRemotePrintersNames();
D
duke 已提交
476
}