1 /*
   2  * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.print;
  27 
  28 import javax.print.attribute.*;
  29 import javax.print.attribute.standard.*;
  30 import javax.print.DocFlavor;
  31 import javax.print.DocPrintJob;
  32 import javax.print.PrintService;
  33 import javax.print.ServiceUIFactory;
  34 import java.util.ArrayList;
  35 import java.util.HashMap;
  36 import java.util.Locale;
  37 import java.util.Date;
  38 import java.util.Arrays;
  39 import java.security.AccessController;
  40 import java.security.PrivilegedActionException;
  41 import java.security.PrivilegedExceptionAction;
  42 import javax.print.event.PrintServiceAttributeListener;
  43 
  44 import java.net.URI;
  45 import java.net.URISyntaxException;
  46 import java.net.URL;
  47 import java.net.URLConnection;
  48 import java.net.HttpURLConnection;
  49 import java.io.File;
  50 import java.io.InputStream;
  51 import java.io.OutputStream;
  52 import java.io.OutputStreamWriter;
  53 import java.io.DataInputStream;
  54 import java.io.ByteArrayOutputStream;
  55 import java.io.ByteArrayInputStream;
  56 import java.io.BufferedReader;
  57 import java.io.InputStreamReader;
  58 import java.nio.charset.Charset;
  59 
  60 import java.util.Iterator;
  61 import java.util.HashSet;
  62 
  63 
  64 public class IPPPrintService implements PrintService, SunPrinterJobService {
  65 
  66     public static final boolean debugPrint;
  67     private static final String debugPrefix = "IPPPrintService>> ";
  68     protected static void debug_println(String str) {
  69         if (debugPrint) {
  70             System.out.println(str);
  71         }
  72     }
  73 
  74     private static final String FORCE_PIPE_PROP = "sun.print.ippdebug";
  75 
  76     static {
  77         String debugStr = java.security.AccessController.doPrivileged(
  78                   new sun.security.action.GetPropertyAction(FORCE_PIPE_PROP));
  79 
  80         debugPrint = "true".equalsIgnoreCase(debugStr);
  81     }
  82 
  83     private String printer;
  84     private URI    myURI;
  85     private URL    myURL;
  86     transient private ServiceNotifier notifier = null;
  87 
  88     private static int MAXCOPIES = 1000;
  89     private static short MAX_ATTRIBUTE_LENGTH = 255;
  90 
  91     private CUPSPrinter cps;
  92     private HttpURLConnection urlConnection = null;
  93     private DocFlavor[] supportedDocFlavors;
  94     private Class[] supportedCats;
  95     private MediaTray[] mediaTrays;
  96     private MediaSizeName[] mediaSizeNames;
  97     private CustomMediaSizeName[] customMediaSizeNames;
  98     private int defaultMediaIndex;
  99     private boolean isCupsPrinter;
 100     private boolean init;
 101     private Boolean isPS;
 102     private HashMap getAttMap;
 103     private boolean pngImagesAdded = false;
 104     private boolean gifImagesAdded = false;
 105     private boolean jpgImagesAdded = false;
 106 
 107 
 108     /**
 109      * IPP Status Codes
 110      */
 111     private static final byte STATUSCODE_SUCCESS = 0x00;
 112 
 113     /**
 114      * IPP Group Tags.  Each tag is used once before the first attribute
 115      * of that group.
 116      */
 117     // operation attributes group
 118     private static final byte GRPTAG_OP_ATTRIBUTES = 0x01;
 119     // job attributes group
 120     private static final byte GRPTAG_JOB_ATTRIBUTES = 0x02;
 121     // printer attributes group
 122     private static final byte GRPTAG_PRINTER_ATTRIBUTES = 0x04;
 123     // used as the last tag in an IPP message.
 124     private static final byte GRPTAG_END_ATTRIBUTES = 0x03;
 125 
 126     /**
 127      * IPP Operation codes
 128      */
 129     // gets the attributes for a printer
 130     public static final String OP_GET_ATTRIBUTES = "000B";
 131     // gets the default printer
 132     public static final String OP_CUPS_GET_DEFAULT = "4001";
 133     // gets the list of printers
 134     public static final String OP_CUPS_GET_PRINTERS = "4002";
 135 
 136 
 137     /**
 138      * List of all PrintRequestAttributes.  This is used
 139      * for looping through all the IPP attribute name.
 140      */
 141     private static Object[] printReqAttribDefault = {
 142         Chromaticity.COLOR,
 143         new Copies(1),
 144         Fidelity.FIDELITY_FALSE,
 145         Finishings.NONE,
 146         //new JobHoldUntil(new Date()),
 147         //new JobImpressions(0),
 148         //JobImpressions,
 149         //JobKOctets,
 150         //JobMediaSheets,
 151         new JobName("", Locale.getDefault()),
 152         //JobPriority,
 153         JobSheets.NONE,
 154         (Media)MediaSizeName.NA_LETTER,
 155         //MediaPrintableArea.class, // not an IPP attribute
 156         //MultipleDocumentHandling.SINGLE_DOCUMENT,
 157         new NumberUp(1),
 158         OrientationRequested.PORTRAIT,
 159         new PageRanges(1),
 160         //PresentationDirection,
 161                  // CUPS does not supply printer-resolution attribute
 162         //new PrinterResolution(300, 300, PrinterResolution.DPI),
 163         //PrintQuality.NORMAL,
 164         new RequestingUserName("", Locale.getDefault()),
 165         //SheetCollate.UNCOLLATED, //CUPS has no sheet collate?
 166         Sides.ONE_SIDED,
 167     };
 168 
 169 
 170     /**
 171      * List of all PrintServiceAttributes.  This is used
 172      * for looping through all the IPP attribute name.
 173      */
 174     private static Object[][] serviceAttributes = {
 175         {ColorSupported.class, "color-supported"},
 176         {PagesPerMinute.class,  "pages-per-minute"},
 177         {PagesPerMinuteColor.class, "pages-per-minute-color"},
 178         {PDLOverrideSupported.class, "pdl-override-supported"},
 179         {PrinterInfo.class, "printer-info"},
 180         {PrinterIsAcceptingJobs.class, "printer-is-accepting-jobs"},
 181         {PrinterLocation.class, "printer-location"},
 182         {PrinterMakeAndModel.class, "printer-make-and-model"},
 183         {PrinterMessageFromOperator.class, "printer-message-from-operator"},
 184         {PrinterMoreInfo.class, "printer-more-info"},
 185         {PrinterMoreInfoManufacturer.class, "printer-more-info-manufacturer"},
 186         {PrinterName.class, "printer-name"},
 187         {PrinterState.class, "printer-state"},
 188         {PrinterStateReasons.class, "printer-state-reasons"},
 189         {PrinterURI.class, "printer-uri"},
 190         {QueuedJobCount.class, "queued-job-count"}
 191     };
 192 
 193 
 194     /**
 195      * List of DocFlavors, grouped based on matching mime-type.
 196      * NOTE: For any change in the predefined DocFlavors, it must be reflected
 197      * here also.
 198      */
 199     // PDF DocFlavors
 200     private static DocFlavor[] appPDF = {
 201         DocFlavor.BYTE_ARRAY.PDF,
 202         DocFlavor.INPUT_STREAM.PDF,
 203         DocFlavor.URL.PDF
 204     };
 205 
 206     // Postscript DocFlavors
 207     private static DocFlavor[] appPostScript = {
 208         DocFlavor.BYTE_ARRAY.POSTSCRIPT,
 209         DocFlavor.INPUT_STREAM.POSTSCRIPT,
 210         DocFlavor.URL.POSTSCRIPT
 211     };
 212 
 213     // Autosense DocFlavors
 214     private static DocFlavor[] appOctetStream = {
 215         DocFlavor.BYTE_ARRAY.AUTOSENSE,
 216         DocFlavor.INPUT_STREAM.AUTOSENSE,
 217         DocFlavor.URL.AUTOSENSE
 218     };
 219 
 220     // Text DocFlavors
 221     private static DocFlavor[] textPlain = {
 222         DocFlavor.BYTE_ARRAY.TEXT_PLAIN_UTF_8,
 223         DocFlavor.BYTE_ARRAY.TEXT_PLAIN_UTF_16,
 224         DocFlavor.BYTE_ARRAY.TEXT_PLAIN_UTF_16BE,
 225         DocFlavor.BYTE_ARRAY.TEXT_PLAIN_UTF_16LE,
 226         DocFlavor.BYTE_ARRAY.TEXT_PLAIN_US_ASCII,
 227         DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_8,
 228         DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16,
 229         DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16BE,
 230         DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16LE,
 231         DocFlavor.INPUT_STREAM.TEXT_PLAIN_US_ASCII,
 232         DocFlavor.URL.TEXT_PLAIN_UTF_8,
 233         DocFlavor.URL.TEXT_PLAIN_UTF_16,
 234         DocFlavor.URL.TEXT_PLAIN_UTF_16BE,
 235         DocFlavor.URL.TEXT_PLAIN_UTF_16LE,
 236         DocFlavor.URL.TEXT_PLAIN_US_ASCII,
 237         DocFlavor.CHAR_ARRAY.TEXT_PLAIN,
 238         DocFlavor.STRING.TEXT_PLAIN,
 239         DocFlavor.READER.TEXT_PLAIN
 240     };
 241 
 242     private static DocFlavor[] textPlainHost = {
 243         DocFlavor.BYTE_ARRAY.TEXT_PLAIN_HOST,
 244         DocFlavor.INPUT_STREAM.TEXT_PLAIN_HOST,
 245         DocFlavor.URL.TEXT_PLAIN_HOST
 246     };
 247 
 248     // JPG DocFlavors
 249     private static DocFlavor[] imageJPG = {
 250         DocFlavor.BYTE_ARRAY.JPEG,
 251         DocFlavor.INPUT_STREAM.JPEG,
 252         DocFlavor.URL.JPEG
 253     };
 254 
 255     // GIF DocFlavors
 256     private static DocFlavor[] imageGIF = {
 257         DocFlavor.BYTE_ARRAY.GIF,
 258         DocFlavor.INPUT_STREAM.GIF,
 259         DocFlavor.URL.GIF
 260     };
 261 
 262     // PNG DocFlavors
 263     private static DocFlavor[] imagePNG = {
 264         DocFlavor.BYTE_ARRAY.PNG,
 265         DocFlavor.INPUT_STREAM.PNG,
 266         DocFlavor.URL.PNG
 267     };
 268 
 269     // HTML DocFlavors
 270     private  static DocFlavor[] textHtml = {
 271         DocFlavor.BYTE_ARRAY.TEXT_HTML_UTF_8,
 272         DocFlavor.BYTE_ARRAY.TEXT_HTML_UTF_16,
 273         DocFlavor.BYTE_ARRAY.TEXT_HTML_UTF_16BE,
 274         DocFlavor.BYTE_ARRAY.TEXT_HTML_UTF_16LE,
 275         DocFlavor.BYTE_ARRAY.TEXT_HTML_US_ASCII,
 276         DocFlavor.INPUT_STREAM.TEXT_HTML_UTF_8,
 277         DocFlavor.INPUT_STREAM.TEXT_HTML_UTF_16,
 278         DocFlavor.INPUT_STREAM.TEXT_HTML_UTF_16BE,
 279         DocFlavor.INPUT_STREAM.TEXT_HTML_UTF_16LE,
 280         DocFlavor.INPUT_STREAM.TEXT_HTML_US_ASCII,
 281         DocFlavor.URL.TEXT_HTML_UTF_8,
 282         DocFlavor.URL.TEXT_HTML_UTF_16,
 283         DocFlavor.URL.TEXT_HTML_UTF_16BE,
 284         DocFlavor.URL.TEXT_HTML_UTF_16LE,
 285         DocFlavor.URL.TEXT_HTML_US_ASCII,
 286         // These are not handled in UnixPrintJob so commenting these
 287         // for now.
 288         /*
 289         DocFlavor.CHAR_ARRAY.TEXT_HTML,
 290         DocFlavor.STRING.TEXT_HTML,
 291         DocFlavor.READER.TEXT_HTML,
 292         */
 293     };
 294 
 295     private  static DocFlavor[] textHtmlHost = {
 296         DocFlavor.BYTE_ARRAY.TEXT_HTML_HOST,
 297         DocFlavor.INPUT_STREAM.TEXT_HTML_HOST,
 298         DocFlavor.URL.TEXT_HTML_HOST,
 299     };
 300 
 301 
 302     // PCL DocFlavors
 303     private static DocFlavor[] appPCL = {
 304         DocFlavor.BYTE_ARRAY.PCL,
 305         DocFlavor.INPUT_STREAM.PCL,
 306         DocFlavor.URL.PCL
 307     };
 308 
 309     // List of all DocFlavors, used in looping
 310     // through all supported mime-types
 311     private static Object[] allDocFlavors = {
 312         appPDF, appPostScript, appOctetStream,
 313         textPlain, imageJPG, imageGIF, imagePNG,
 314         textHtml, appPCL,
 315     };
 316 
 317 
 318     IPPPrintService(String name, URL url) {
 319         if ((name == null) || (url == null)){
 320             throw new IllegalArgumentException("null uri or printer name");
 321         }
 322         printer = name;
 323         supportedDocFlavors = null;
 324         supportedCats = null;
 325         mediaSizeNames = null;
 326         customMediaSizeNames = null;
 327         mediaTrays = null;
 328         myURL = url;
 329         cps = null;
 330         isCupsPrinter = false;
 331         init = false;
 332         defaultMediaIndex = -1;
 333 
 334         String host = myURL.getHost();
 335         if (host!=null && host.equals(CUPSPrinter.getServer())) {
 336             isCupsPrinter = true;
 337             try {
 338                 myURI =  new URI("ipp://"+host+
 339                                  "/printers/"+printer);
 340                 debug_println(debugPrefix+"IPPPrintService myURI : "+myURI);
 341             } catch (java.net.URISyntaxException e) {
 342                 throw new IllegalArgumentException("invalid url");
 343             }
 344         }
 345     }
 346 
 347 
 348     IPPPrintService(String name, String uriStr, boolean isCups) {
 349         if ((name == null) || (uriStr == null)){
 350             throw new IllegalArgumentException("null uri or printer name");
 351         }
 352         printer = name;
 353         supportedDocFlavors = null;
 354         supportedCats = null;
 355         mediaSizeNames = null;
 356         customMediaSizeNames = null;
 357         mediaTrays = null;
 358         cps = null;
 359         init = false;
 360         defaultMediaIndex = -1;
 361         try {
 362             myURL =
 363                 new URL(uriStr.replaceFirst("ipp", "http"));
 364         } catch (Exception e) {
 365             IPPPrintService.debug_println(debugPrefix+
 366                                           " IPPPrintService, myURL="+
 367                                           myURL+" Exception= "+
 368                                           e);
 369             throw new IllegalArgumentException("invalid url");
 370         }
 371 
 372         isCupsPrinter = isCups;
 373         try {
 374             myURI =  new URI(uriStr);
 375             debug_println(debugPrefix+"IPPPrintService myURI : "+myURI);
 376         } catch (java.net.URISyntaxException e) {
 377             throw new IllegalArgumentException("invalid uri");
 378         }
 379     }
 380 
 381 
 382     /*
 383      * Initialize mediaSizeNames, mediaTrays and other attributes.
 384      * Media size/trays are initialized to non-null values, may be 0-length
 385      * array.
 386      * NOTE: Must be called from a synchronized block only.
 387      */
 388     private void initAttributes() {
 389         if (!init) {
 390             // init customMediaSizeNames
 391             customMediaSizeNames = new CustomMediaSizeName[0];
 392 
 393             if ((urlConnection = getIPPConnection(myURL)) == null) {
 394                 mediaSizeNames = new MediaSizeName[0];
 395                 mediaTrays = new MediaTray[0];
 396                 debug_println(debugPrefix+"initAttributes, NULL urlConnection ");
 397                 init = true;
 398                 return;
 399             }
 400 
 401             // get all supported attributes through IPP
 402             opGetAttributes();
 403 
 404             if (isCupsPrinter) {
 405                 // note, it is possible to query media in CUPS using IPP
 406                 // right now we always get it from PPD.
 407                 // maybe use "&& (usePPD)" later?
 408                 // Another reason why we use PPD is because
 409                 // IPP currently does not support it but PPD does.
 410 
 411                 try {
 412                     cps = new CUPSPrinter(printer);
 413                     mediaSizeNames = cps.getMediaSizeNames();
 414                     mediaTrays = cps.getMediaTrays();
 415                     customMediaSizeNames = cps.getCustomMediaSizeNames();
 416                     urlConnection.disconnect();
 417                     init = true;
 418                     return;
 419                 } catch (Exception e) {
 420                     IPPPrintService.debug_println(debugPrefix+
 421                                        "initAttributes, error creating CUPSPrinter e="+e);
 422                 }
 423             }
 424 
 425             // use IPP to get all media,
 426             Media[] allMedia = getSupportedMedia();
 427             ArrayList sizeList = new ArrayList();
 428             ArrayList trayList = new ArrayList();
 429             for (int i=0; i<allMedia.length; i++) {
 430                 if (allMedia[i] instanceof MediaSizeName) {
 431                     sizeList.add(allMedia[i]);
 432                 } else if (allMedia[i] instanceof MediaTray) {
 433                     trayList.add(allMedia[i]);
 434                 }
 435             }
 436 
 437             if (sizeList != null) {
 438                 mediaSizeNames = new MediaSizeName[sizeList.size()];
 439                 mediaSizeNames = (MediaSizeName[])sizeList.toArray(
 440                                                        mediaSizeNames);
 441             }
 442             if (trayList != null) {
 443                 mediaTrays = new MediaTray[trayList.size()];
 444                 mediaTrays = (MediaTray[])trayList.toArray(
 445                                                            mediaTrays);
 446             }
 447             urlConnection.disconnect();
 448 
 449             init = true;
 450         }
 451     }
 452 
 453 
 454     public DocPrintJob createPrintJob() {
 455         SecurityManager security = System.getSecurityManager();
 456         if (security != null) {
 457             security.checkPrintJobAccess();
 458         }
 459         // REMIND: create IPPPrintJob
 460         return new UnixPrintJob(this);
 461     }
 462 
 463 
 464     public synchronized Object
 465         getSupportedAttributeValues(Class<? extends Attribute> category,
 466                                     DocFlavor flavor,
 467                                     AttributeSet attributes)
 468     {
 469         if (category == null) {
 470             throw new NullPointerException("null category");
 471         }
 472         if (!Attribute.class.isAssignableFrom(category)) {
 473             throw new IllegalArgumentException(category +
 474                                  " does not implement Attribute");
 475         }
 476         if (flavor != null) {
 477             if (!isDocFlavorSupported(flavor)) {
 478                 throw new IllegalArgumentException(flavor +
 479                                                " is an unsupported flavor");
 480             } else if (isAutoSense(flavor)) {
 481                 return null;
 482             }
 483 
 484         }
 485 
 486         if (!isAttributeCategorySupported(category)) {
 487             return null;
 488         }
 489 
 490         /* Test if the flavor is compatible with the attributes */
 491         if (!isDestinationSupported(flavor, attributes)) {
 492             return null;
 493         }
 494 
 495         initAttributes();
 496 
 497         /* Test if the flavor is compatible with the category */
 498         if ((category == Copies.class) ||
 499             (category == CopiesSupported.class)) {
 500             if (flavor == null ||
 501                 !(flavor.equals(DocFlavor.INPUT_STREAM.POSTSCRIPT) ||
 502                   flavor.equals(DocFlavor.URL.POSTSCRIPT) ||
 503                   flavor.equals(DocFlavor.BYTE_ARRAY.POSTSCRIPT))) {
 504                 CopiesSupported cs = new CopiesSupported(1, MAXCOPIES);
 505                 AttributeClass attribClass = (getAttMap != null) ?
 506                     (AttributeClass)getAttMap.get(cs.getName()) : null;
 507                 if (attribClass != null) {
 508                     int[] range = attribClass.getIntRangeValue();
 509                     cs = new CopiesSupported(range[0], range[1]);
 510                 }
 511                 return cs;
 512             } else {
 513                 return null;
 514             }
 515         } else  if (category == Chromaticity.class) {
 516             if (flavor == null ||
 517                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
 518                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE) ||
 519                 !isIPPSupportedImages(flavor.getMimeType())) {
 520                 Chromaticity[]arr = new Chromaticity[1];
 521                 arr[0] = Chromaticity.COLOR;
 522                 return (arr);
 523             } else {
 524                 return null;
 525             }
 526         } else if (category == Destination.class) {
 527             if (flavor == null ||
 528                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
 529                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
 530                 try {
 531                     return new Destination((new File("out.ps")).toURI());
 532                 } catch (SecurityException se) {
 533                     try {
 534                         return new Destination(new URI("file:out.ps"));
 535                     } catch (URISyntaxException e) {
 536                         return null;
 537                     }
 538                 }
 539             }
 540             return null;
 541         } else if (category == Fidelity.class) {
 542             Fidelity []arr = new Fidelity[2];
 543             arr[0] = Fidelity.FIDELITY_FALSE;
 544             arr[1] = Fidelity.FIDELITY_TRUE;
 545             return arr;
 546         } else if (category == Finishings.class) {
 547             AttributeClass attribClass = (getAttMap != null) ?
 548                 (AttributeClass)getAttMap.get("finishings-supported")
 549                 : null;
 550             if (attribClass != null) {
 551                 int[] finArray = attribClass.getArrayOfIntValues();
 552                 if ((finArray != null) && (finArray.length > 0)) {
 553                     Finishings[] finSup = new Finishings[finArray.length];
 554                     for (int i=0; i<finArray.length; i++) {
 555                         finSup[i] = Finishings.NONE;
 556                         Finishings[] fAll = (Finishings[])
 557                             (new ExtFinishing(100)).getAll();
 558                         for (int j=0; j<fAll.length; j++) {
 559                             if (finArray[i] == fAll[j].getValue()) {
 560                                 finSup[i] = fAll[j];
 561                                 break;
 562                             }
 563                         }
 564                     }
 565                     return finSup;
 566                 }
 567             }
 568         } else if (category == JobName.class) {
 569             return new JobName("Java Printing", null);
 570         } else if (category == JobSheets.class) {
 571             JobSheets arr[] = new JobSheets[2];
 572             arr[0] = JobSheets.NONE;
 573             arr[1] = JobSheets.STANDARD;
 574             return arr;
 575 
 576         } else if (category == Media.class) {
 577             Media[] allMedia = new Media[mediaSizeNames.length+
 578                                         mediaTrays.length];
 579 
 580             for (int i=0; i<mediaSizeNames.length; i++) {
 581                 allMedia[i] = mediaSizeNames[i];
 582             }
 583 
 584             for (int i=0; i<mediaTrays.length; i++) {
 585                 allMedia[i+mediaSizeNames.length] = mediaTrays[i];
 586             }
 587 
 588             if (allMedia.length == 0) {
 589                 allMedia = new Media[1];
 590                 allMedia[0] = (Media)getDefaultAttributeValue(Media.class);
 591             }
 592 
 593             return allMedia;
 594         } else if (category == MediaPrintableArea.class) {
 595             MediaPrintableArea[] mpas = null;
 596             if (cps != null) {
 597                 mpas = cps.getMediaPrintableArea();
 598             }
 599 
 600             if (mpas == null) {
 601                 mpas = new MediaPrintableArea[1];
 602                 mpas[0] = (MediaPrintableArea)
 603                     getDefaultAttributeValue(MediaPrintableArea.class);
 604             }
 605 
 606             if ((attributes == null) || (attributes.size() == 0)) {
 607                 ArrayList<MediaPrintableArea> printableList =
 608                                        new ArrayList<MediaPrintableArea>();
 609 
 610                 for (int i=0; i<mpas.length; i++) {
 611                     if (mpas[i] != null) {
 612                         printableList.add(mpas[i]);
 613                     }
 614                 }
 615                 if (printableList.size() > 0) {
 616                     mpas  = new MediaPrintableArea[printableList.size()];
 617                     printableList.toArray(mpas);
 618                 }
 619                 return mpas;
 620             }
 621 
 622             int match = -1;
 623             Media media = (Media)attributes.get(Media.class);
 624             if (media != null && media instanceof MediaSizeName) {
 625                 MediaSizeName msn = (MediaSizeName)media;
 626 
 627                 // case when no supported mediasizenames are reported
 628                 // check given media against the default
 629                 if (mediaSizeNames.length == 0 &&
 630                     msn.equals(getDefaultAttributeValue(Media.class))) {
 631                     //default printable area is that of default mediasize
 632                     return mpas;
 633                 }
 634 
 635                 for (int i=0; i<mediaSizeNames.length; i++) {
 636                     if (msn.equals(mediaSizeNames[i])) {
 637                         match = i;
 638                     }
 639                 }
 640             }
 641 
 642             if (match == -1) {
 643                 return null;
 644             } else {
 645                 MediaPrintableArea []arr = new MediaPrintableArea[1];
 646                 arr[0] = mpas[match];
 647                 return arr;
 648             }
 649         } else if (category == NumberUp.class) {
 650             AttributeClass attribClass = (getAttMap != null) ?
 651                 (AttributeClass)getAttMap.get("number-up-supported") : null;
 652             if (attribClass != null) {
 653                 int[] values = attribClass.getArrayOfIntValues();
 654                 if (values != null) {
 655                     NumberUp[] nUp = new NumberUp[values.length];
 656                     for (int i=0; i<values.length; i++) {
 657                         nUp[i] = new NumberUp(values[i]);
 658                     }
 659                     return nUp;
 660                 } else {
 661                     return null;
 662                 }
 663             }
 664         } else if (category == OrientationRequested.class) {
 665             if ((flavor != null) &&
 666                 (flavor.equals(DocFlavor.INPUT_STREAM.POSTSCRIPT) ||
 667                  flavor.equals(DocFlavor.URL.POSTSCRIPT) ||
 668                  flavor.equals(DocFlavor.BYTE_ARRAY.POSTSCRIPT))) {
 669                 return null;
 670             }
 671 
 672             boolean revPort = false;
 673             OrientationRequested[] orientSup = null;
 674 
 675             AttributeClass attribClass = (getAttMap != null) ?
 676               (AttributeClass)getAttMap.get("orientation-requested-supported")
 677                 : null;
 678             if (attribClass != null) {
 679                 int[] orientArray = attribClass.getArrayOfIntValues();
 680                 if ((orientArray != null) && (orientArray.length > 0)) {
 681                     orientSup =
 682                         new OrientationRequested[orientArray.length];
 683                     for (int i=0; i<orientArray.length; i++) {
 684                         switch (orientArray[i]) {
 685                         default:
 686                         case 3 :
 687                             orientSup[i] = OrientationRequested.PORTRAIT;
 688                             break;
 689                         case 4:
 690                             orientSup[i] = OrientationRequested.LANDSCAPE;
 691                             break;
 692                         case 5:
 693                             orientSup[i] =
 694                                 OrientationRequested.REVERSE_LANDSCAPE;
 695                             break;
 696                         case 6:
 697                             orientSup[i] =
 698                                 OrientationRequested.REVERSE_PORTRAIT;
 699                             revPort = true;
 700                             break;
 701                         }
 702                     }
 703                 }
 704             }
 705             if (flavor == null ||
 706                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
 707                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
 708 
 709                 if (revPort && flavor == null) {
 710                     OrientationRequested []orSup = new OrientationRequested[4];
 711                     orSup[0] = OrientationRequested.PORTRAIT;
 712                     orSup[1] = OrientationRequested.LANDSCAPE;
 713                     orSup[2] = OrientationRequested.REVERSE_LANDSCAPE;
 714                     orSup[3] = OrientationRequested.REVERSE_PORTRAIT;
 715                     return orSup;
 716                 } else {
 717                     OrientationRequested []orSup = new OrientationRequested[3];
 718                     orSup[0] = OrientationRequested.PORTRAIT;
 719                     orSup[1] = OrientationRequested.LANDSCAPE;
 720                     orSup[2] = OrientationRequested.REVERSE_LANDSCAPE;
 721                     return orSup;
 722                 }
 723             } else {
 724                 return orientSup;
 725             }
 726         } else if (category == PageRanges.class) {
 727            if (flavor == null ||
 728                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
 729                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
 730                 PageRanges []arr = new PageRanges[1];
 731                 arr[0] = new PageRanges(1, Integer.MAX_VALUE);
 732                 return arr;
 733             } else {
 734                 // Returning null as this is not yet supported in UnixPrintJob.
 735                 return null;
 736             }
 737         } else if (category == RequestingUserName.class) {
 738             String userName = "";
 739             try {
 740               userName = System.getProperty("user.name", "");
 741             } catch (SecurityException se) {
 742             }
 743             return new RequestingUserName(userName, null);
 744         } else if (category == Sides.class) {
 745             // The printer takes care of Sides so if short-edge
 746             // is chosen in a job, the rotation is done by the printer.
 747             // Orientation is rotated by emulation if pageable
 748             // or printable so if the document is in Landscape, this may
 749             // result in double rotation.
 750             AttributeClass attribClass = (getAttMap != null) ?
 751                 (AttributeClass)getAttMap.get("sides-supported")
 752                 : null;
 753             if (attribClass != null) {
 754                 String[] sidesArray = attribClass.getArrayOfStringValues();
 755                 if ((sidesArray != null) && (sidesArray.length > 0)) {
 756                     Sides[] sidesSup = new Sides[sidesArray.length];
 757                     for (int i=0; i<sidesArray.length; i++) {
 758                         if (sidesArray[i].endsWith("long-edge")) {
 759                             sidesSup[i] = Sides.TWO_SIDED_LONG_EDGE;
 760                         } else if (sidesArray[i].endsWith("short-edge")) {
 761                             sidesSup[i] = Sides.TWO_SIDED_SHORT_EDGE;
 762                         } else {
 763                             sidesSup[i] = Sides.ONE_SIDED;
 764                         }
 765                     }
 766                     return sidesSup;
 767                 }
 768             }
 769         }
 770 
 771         return null;
 772     }
 773 
 774     //This class is for getting all pre-defined Finishings
 775     private class ExtFinishing extends Finishings {
 776         ExtFinishing(int value) {
 777             super(100); // 100 to avoid any conflicts with predefined values.
 778         }
 779 
 780         EnumSyntax[] getAll() {
 781             EnumSyntax[] es = super.getEnumValueTable();
 782             return es;
 783         }
 784     }
 785 
 786 
 787     public AttributeSet getUnsupportedAttributes(DocFlavor flavor,
 788                                                  AttributeSet attributes) {
 789         if (flavor != null && !isDocFlavorSupported(flavor)) {
 790             throw new IllegalArgumentException("flavor " + flavor +
 791                                                "is not supported");
 792         }
 793 
 794         if (attributes == null) {
 795             return null;
 796         }
 797 
 798         Attribute attr;
 799         AttributeSet unsupp = new HashAttributeSet();
 800         Attribute []attrs = attributes.toArray();
 801         for (int i=0; i<attrs.length; i++) {
 802             try {
 803                 attr = attrs[i];
 804                 if (!isAttributeCategorySupported(attr.getCategory())) {
 805                     unsupp.add(attr);
 806                 } else if (!isAttributeValueSupported(attr, flavor,
 807                                                       attributes)) {
 808                     unsupp.add(attr);
 809                 }
 810             } catch (ClassCastException e) {
 811             }
 812         }
 813         if (unsupp.isEmpty()) {
 814             return null;
 815         } else {
 816             return unsupp;
 817         }
 818     }
 819 
 820 
 821     public synchronized DocFlavor[] getSupportedDocFlavors() {
 822 
 823         if (supportedDocFlavors != null) {
 824             int len = supportedDocFlavors.length;
 825                 DocFlavor[] copyflavors = new DocFlavor[len];
 826                 System.arraycopy(supportedDocFlavors, 0, copyflavors, 0, len);
 827                 return copyflavors;
 828         }
 829         initAttributes();
 830 
 831         if ((getAttMap != null) &&
 832             getAttMap.containsKey("document-format-supported")) {
 833 
 834             AttributeClass attribClass =
 835                 (AttributeClass)getAttMap.get("document-format-supported");
 836             if (attribClass != null) {
 837                 String mimeType;
 838                 boolean psSupported = false;
 839                 String[] docFlavors = attribClass.getArrayOfStringValues();
 840                 DocFlavor[] flavors;
 841                 HashSet docList = new HashSet();
 842                 int j;
 843                 String hostEnc = DocFlavor.hostEncoding.
 844                     toLowerCase(Locale.ENGLISH);
 845                 boolean addHostEncoding = !hostEnc.equals("utf-8") &&
 846                     !hostEnc.equals("utf-16") && !hostEnc.equals("utf-16be") &&
 847                     !hostEnc.equals("utf-16le") && !hostEnc.equals("us-ascii");
 848 
 849                 for (int i = 0; i < docFlavors.length; i++) {
 850                     for (j=0; j<allDocFlavors.length; j++) {
 851                         flavors = (DocFlavor[])allDocFlavors[j];
 852 
 853                         mimeType = flavors[0].getMimeType();
 854                         if (mimeType.startsWith(docFlavors[i])) {
 855 
 856                             docList.addAll(Arrays.asList(flavors));
 857 
 858                             if (mimeType.equals("text/plain") &&
 859                                 addHostEncoding) {
 860                                 docList.add(Arrays.asList(textPlainHost));
 861                             } else if (mimeType.equals("text/html") &&
 862                                        addHostEncoding) {
 863                                 docList.add(Arrays.asList(textHtmlHost));
 864                             } else if (mimeType.equals("image/png")) {
 865                                 pngImagesAdded = true;
 866                             } else if (mimeType.equals("image/gif")) {
 867                                 gifImagesAdded = true;
 868                             } else if (mimeType.equals("image/jpeg")) {
 869                                 jpgImagesAdded = true;
 870                             } else if (mimeType.indexOf("postscript") != -1) {
 871                                 psSupported = true;
 872                             }
 873                             break;
 874                         }
 875                     }
 876 
 877                     // Not added? Create new DocFlavors
 878                     if (j == allDocFlavors.length) {
 879                         //  make new DocFlavors
 880                         docList.add(new DocFlavor.BYTE_ARRAY(docFlavors[i]));
 881                         docList.add(new DocFlavor.INPUT_STREAM(docFlavors[i]));
 882                         docList.add(new DocFlavor.URL(docFlavors[i]));
 883                     }
 884                 }
 885 
 886                 // check if we need to add image DocFlavors
 887                 // and Pageable/Printable flavors
 888                 if (psSupported || isCupsPrinter) {
 889                     /*
 890                      Always add Pageable and Printable for CUPS
 891                      since it uses Filters to convert from Postscript
 892                      to device printer language.
 893                     */
 894                     docList.add(DocFlavor.SERVICE_FORMATTED.PAGEABLE);
 895                     docList.add(DocFlavor.SERVICE_FORMATTED.PRINTABLE);
 896 
 897                     docList.addAll(Arrays.asList(imageJPG));
 898                     docList.addAll(Arrays.asList(imagePNG));
 899                     docList.addAll(Arrays.asList(imageGIF));
 900                 }
 901                 supportedDocFlavors = new DocFlavor[docList.size()];
 902                 docList.toArray(supportedDocFlavors);
 903                 int len = supportedDocFlavors.length;
 904                 DocFlavor[] copyflavors = new DocFlavor[len];
 905                 System.arraycopy(supportedDocFlavors, 0, copyflavors, 0, len);
 906                 return copyflavors;
 907             }
 908         }
 909         return null;
 910     }
 911 
 912 
 913     public boolean isDocFlavorSupported(DocFlavor flavor) {
 914         if (supportedDocFlavors == null) {
 915             getSupportedDocFlavors();
 916         }
 917         if (supportedDocFlavors != null) {
 918             for (int f=0; f<supportedDocFlavors.length; f++) {
 919                 if (flavor.equals(supportedDocFlavors[f])) {
 920                     return true;
 921                 }
 922             }
 923         }
 924         return false;
 925     }
 926 
 927 
 928     /**
 929      * Finds matching CustomMediaSizeName of given media.
 930      */
 931     public CustomMediaSizeName findCustomMedia(MediaSizeName media) {
 932         if (customMediaSizeNames == null) {
 933             return null;
 934         }
 935         for (int i=0; i< customMediaSizeNames.length; i++) {
 936             CustomMediaSizeName custom = customMediaSizeNames[i];
 937             MediaSizeName msn = custom.getStandardMedia();
 938             if (media.equals(msn)) {
 939                 return customMediaSizeNames[i];
 940             }
 941         }
 942         return null;
 943     }
 944 
 945 
 946     /**
 947      * Returns the matching standard Media using string comparison of names.
 948      */
 949     private Media getIPPMedia(String mediaName) {
 950         CustomMediaSizeName sampleSize = new CustomMediaSizeName("sample", "",
 951                                                                  0, 0);
 952         Media[] sizes = sampleSize.getSuperEnumTable();
 953         for (int i=0; i<sizes.length; i++) {
 954             if (mediaName.equals(""+sizes[i])) {
 955                 return sizes[i];
 956             }
 957         }
 958         CustomMediaTray sampleTray = new CustomMediaTray("sample", "");
 959         Media[] trays = sampleTray.getSuperEnumTable();
 960         for (int i=0; i<trays.length; i++) {
 961             if (mediaName.equals(""+trays[i])) {
 962                 return trays[i];
 963             }
 964         }
 965         return null;
 966     }
 967 
 968     private Media[] getSupportedMedia() {
 969         if ((getAttMap != null) &&
 970             getAttMap.containsKey("media-supported")) {
 971 
 972             AttributeClass attribClass =
 973                 (AttributeClass)getAttMap.get("media-supported");
 974 
 975             if (attribClass != null) {
 976                 String[] mediaVals = attribClass.getArrayOfStringValues();
 977                 Media msn;
 978                 Media[] mediaNames =
 979                     new Media[mediaVals.length];
 980                 for (int i=0; i<mediaVals.length; i++) {
 981                     msn = getIPPMedia(mediaVals[i]);
 982                     //REMIND: if null, create custom?
 983                     mediaNames[i] = msn;
 984                 }
 985                 return mediaNames;
 986             }
 987         }
 988         return new Media[0];
 989     }
 990 
 991 
 992     public synchronized Class[] getSupportedAttributeCategories() {
 993         if (supportedCats != null) {
 994             return supportedCats;
 995         }
 996 
 997         initAttributes();
 998 
 999         ArrayList catList = new ArrayList();
1000         Class cl;
1001 
1002         for (int i=0; i < printReqAttribDefault.length; i++) {
1003             PrintRequestAttribute pra =
1004                 (PrintRequestAttribute)printReqAttribDefault[i];
1005             if (getAttMap != null &&
1006                 getAttMap.containsKey(pra.getName()+"-supported")) {
1007                 cl = pra.getCategory();
1008                 catList.add(cl);
1009             }
1010         }
1011 
1012         // Some IPP printers like lexc710 do not have list of supported media
1013         // but CUPS can get the media from PPD, so we still report as
1014         // supported category.
1015         if (isCupsPrinter) {
1016             if (!catList.contains(Media.class)) {
1017                 catList.add(Media.class);
1018             }
1019 
1020             // Always add MediaPrintable for cups,
1021             // because we can get it from PPD.
1022             catList.add(MediaPrintableArea.class);
1023 
1024             // this is already supported in UnixPrintJob
1025             catList.add(Destination.class);
1026 
1027             // It is unfortunate that CUPS doesn't provide a way to query
1028             // if printer supports collation but since most printers
1029             // now supports collation and that most OS has a way
1030             // of setting it, it is a safe assumption to just always
1031             // include SheetCollate as supported attribute.
1032 
1033             /*
1034                In Linux, we use Postscript for rendering but Linux still
1035                has issues in propagating Postscript-embedded setpagedevice
1036                setting like collation.  Therefore, we temporarily exclude
1037                Linux.
1038             */
1039             if (!UnixPrintServiceLookup.isLinux()) {
1040                 catList.add(SheetCollate.class);
1041             }
1042         }
1043 
1044         // With the assumption that  Chromaticity is equivalent to
1045         // ColorSupported.
1046         if (getAttMap != null && getAttMap.containsKey("color-supported")) {
1047             catList.add(Chromaticity.class);
1048         }
1049         supportedCats = new Class[catList.size()];
1050         catList.toArray(supportedCats);
1051         return supportedCats;
1052     }
1053 
1054 
1055     public boolean
1056         isAttributeCategorySupported(Class<? extends Attribute> category)
1057     {
1058         if (category == null) {
1059             throw new NullPointerException("null category");
1060         }
1061         if (!(Attribute.class.isAssignableFrom(category))) {
1062             throw new IllegalArgumentException(category +
1063                                              " is not an Attribute");
1064         }
1065 
1066         if (supportedCats == null) {
1067             getSupportedAttributeCategories();
1068         }
1069 
1070         // It is safe to assume that Orientation is always supported
1071         // and even if CUPS or an IPP device reports it as not,
1072         // our renderer can do portrait, landscape and
1073         // reverse landscape.
1074         if (category == OrientationRequested.class) {
1075             return true;
1076         }
1077 
1078         for (int i=0;i<supportedCats.length;i++) {
1079             if (category == supportedCats[i]) {
1080                 return true;
1081             }
1082         }
1083 
1084         return false;
1085     }
1086 
1087 
1088     public synchronized <T extends PrintServiceAttribute>
1089         T getAttribute(Class<T> category)
1090     {
1091         if (category == null) {
1092             throw new NullPointerException("category");
1093         }
1094         if (!(PrintServiceAttribute.class.isAssignableFrom(category))) {
1095             throw new IllegalArgumentException("Not a PrintServiceAttribute");
1096         }
1097 
1098         initAttributes();
1099 
1100         if (category == PrinterName.class) {
1101             return (T)(new PrinterName(printer, null));
1102         } else if (category == PrinterInfo.class) {
1103             PrinterInfo pInfo = new PrinterInfo(printer, null);
1104             AttributeClass ac = (getAttMap != null) ?
1105                 (AttributeClass)getAttMap.get(pInfo.getName())
1106                 : null;
1107             if (ac != null) {
1108                 return (T)(new PrinterInfo(ac.getStringValue(), null));
1109             }
1110             return (T)pInfo;
1111         } else if (category == QueuedJobCount.class) {
1112             QueuedJobCount qjc = new QueuedJobCount(0);
1113             AttributeClass ac = (getAttMap != null) ?
1114                 (AttributeClass)getAttMap.get(qjc.getName())
1115                 : null;
1116             if (ac != null) {
1117                 qjc = new QueuedJobCount(ac.getIntValue());
1118             }
1119             return (T)qjc;
1120         } else if (category == PrinterIsAcceptingJobs.class) {
1121             PrinterIsAcceptingJobs accJob =
1122                 PrinterIsAcceptingJobs.ACCEPTING_JOBS;
1123             AttributeClass ac = (getAttMap != null) ?
1124                 (AttributeClass)getAttMap.get(accJob.getName())
1125                 : null;
1126             if ((ac != null) && (ac.getByteValue() == 0)) {
1127                 accJob = PrinterIsAcceptingJobs.NOT_ACCEPTING_JOBS;
1128             }
1129             return (T)accJob;
1130         } else if (category == ColorSupported.class) {
1131             ColorSupported cs = ColorSupported.SUPPORTED;
1132             AttributeClass ac = (getAttMap != null) ?
1133                 (AttributeClass)getAttMap.get(cs.getName())
1134                 : null;
1135             if ((ac != null) && (ac.getByteValue() == 0)) {
1136                 cs = ColorSupported.NOT_SUPPORTED;
1137             }
1138             return (T)cs;
1139         } else if (category == PDLOverrideSupported.class) {
1140 
1141             if (isCupsPrinter) {
1142                 // Documented: For CUPS this will always be false
1143                 return (T)PDLOverrideSupported.NOT_ATTEMPTED;
1144             } else {
1145                 // REMIND: check attribute values
1146                 return (T)PDLOverrideSupported.NOT_ATTEMPTED;
1147             }
1148         } else if (category == PrinterURI.class) {
1149             return (T)(new PrinterURI(myURI));
1150         } else {
1151             return null;
1152         }
1153     }
1154 
1155 
1156     public synchronized PrintServiceAttributeSet getAttributes() {
1157         // update getAttMap by sending again get-attributes IPP request
1158         init = false;
1159         initAttributes();
1160 
1161         HashPrintServiceAttributeSet attrs =
1162             new HashPrintServiceAttributeSet();
1163 
1164         for (int i=0; i < serviceAttributes.length; i++) {
1165             String name = (String)serviceAttributes[i][1];
1166             if (getAttMap != null && getAttMap.containsKey(name)) {
1167                 Class c = (Class)serviceAttributes[i][0];
1168                 PrintServiceAttribute psa = getAttribute(c);
1169                 if (psa != null) {
1170                     attrs.add(psa);
1171                 }
1172             }
1173         }
1174         return AttributeSetUtilities.unmodifiableView(attrs);
1175     }
1176 
1177     public boolean isIPPSupportedImages(String mimeType) {
1178         if (supportedDocFlavors == null) {
1179             getSupportedDocFlavors();
1180         }
1181 
1182         if (mimeType.equals("image/png") && pngImagesAdded) {
1183             return true;
1184         } else if (mimeType.equals("image/gif") && gifImagesAdded) {
1185             return true;
1186         } else if (mimeType.equals("image/jpeg") && jpgImagesAdded) {
1187             return true;
1188         }
1189 
1190         return false;
1191     }
1192 
1193 
1194     private boolean isSupportedCopies(Copies copies) {
1195         CopiesSupported cs = (CopiesSupported)
1196             getSupportedAttributeValues(Copies.class, null, null);
1197         int[][] members = cs.getMembers();
1198         int min, max;
1199         if ((members.length > 0) && (members[0].length > 0)) {
1200             min = members[0][0];
1201             max = members[0][1];
1202         } else {
1203             min = 1;
1204             max = MAXCOPIES;
1205         }
1206 
1207         int value = copies.getValue();
1208         return (value >= min && value <= max);
1209     }
1210 
1211     private boolean isAutoSense(DocFlavor flavor) {
1212         if (flavor.equals(DocFlavor.BYTE_ARRAY.AUTOSENSE) ||
1213             flavor.equals(DocFlavor.INPUT_STREAM.AUTOSENSE) ||
1214             flavor.equals(DocFlavor.URL.AUTOSENSE)) {
1215             return true;
1216         }
1217         else {
1218             return false;
1219         }
1220     }
1221 
1222     private synchronized boolean isSupportedMediaTray(MediaTray msn) {
1223         initAttributes();
1224 
1225         if (mediaTrays != null) {
1226             for (int i=0; i<mediaTrays.length; i++) {
1227                if (msn.equals(mediaTrays[i])) {
1228                     return true;
1229                 }
1230             }
1231         }
1232         return false;
1233     }
1234 
1235     private synchronized boolean isSupportedMedia(MediaSizeName msn) {
1236         initAttributes();
1237 
1238         if (msn.equals((Media)getDefaultAttributeValue(Media.class))) {
1239             return true;
1240         }
1241         for (int i=0; i<mediaSizeNames.length; i++) {
1242             debug_println(debugPrefix+"isSupportedMedia, mediaSizeNames[i] "+mediaSizeNames[i]);
1243             if (msn.equals(mediaSizeNames[i])) {
1244                 return true;
1245             }
1246         }
1247         return false;
1248     }
1249 
1250     /* Return false if flavor is not null, pageable, nor printable and
1251      * Destination is part of attributes.
1252      */
1253     private boolean
1254         isDestinationSupported(DocFlavor flavor, AttributeSet attributes) {
1255 
1256             if ((attributes != null) &&
1257                     (attributes.get(Destination.class) != null) &&
1258                     !(flavor == null ||
1259                       flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1260                       flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE))) {
1261                 return false;
1262             }
1263             return true;
1264     }
1265 
1266 
1267     public boolean isAttributeValueSupported(Attribute attr,
1268                                              DocFlavor flavor,
1269                                              AttributeSet attributes) {
1270         if (attr == null) {
1271             throw new NullPointerException("null attribute");
1272         }
1273         if (flavor != null) {
1274             if (!isDocFlavorSupported(flavor)) {
1275                 throw new IllegalArgumentException(flavor +
1276                                                " is an unsupported flavor");
1277             } else if (isAutoSense(flavor)) {
1278                 return false;
1279             }
1280         }
1281         Class category = attr.getCategory();
1282         if (!isAttributeCategorySupported(category)) {
1283             return false;
1284         }
1285 
1286         /* Test if the flavor is compatible with the attributes */
1287         if (!isDestinationSupported(flavor, attributes)) {
1288             return false;
1289         }
1290 
1291         /* Test if the flavor is compatible with the category */
1292         if (attr.getCategory() == Chromaticity.class) {
1293             if ((flavor == null) ||
1294                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1295                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE) ||
1296                 !isIPPSupportedImages(flavor.getMimeType())) {
1297                 return attr == Chromaticity.COLOR;
1298             } else {
1299                 return false;
1300             }
1301         } else if (attr.getCategory() == Copies.class) {
1302             return (flavor == null ||
1303                    !(flavor.equals(DocFlavor.INPUT_STREAM.POSTSCRIPT) ||
1304                    flavor.equals(DocFlavor.URL.POSTSCRIPT) ||
1305                    flavor.equals(DocFlavor.BYTE_ARRAY.POSTSCRIPT))) &&
1306                 isSupportedCopies((Copies)attr);
1307 
1308         } else if (attr.getCategory() == Destination.class) {
1309             if (flavor == null ||
1310                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1311                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
1312                 URI uri = ((Destination)attr).getURI();
1313                 if ("file".equals(uri.getScheme()) &&
1314                     !(uri.getSchemeSpecificPart().equals(""))) {
1315                     return true;
1316                 }
1317             }
1318             return false;
1319         } else if (attr.getCategory() == Media.class) {
1320             if (attr instanceof MediaSizeName) {
1321                 return isSupportedMedia((MediaSizeName)attr);
1322             }
1323             if (attr instanceof MediaTray) {
1324                 return isSupportedMediaTray((MediaTray)attr);
1325             }
1326         } else if (attr.getCategory() == PageRanges.class) {
1327             if (flavor != null &&
1328                 !(flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1329                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE))) {
1330                 return false;
1331             }
1332         } else if (attr.getCategory() == SheetCollate.class) {
1333             if (flavor != null &&
1334                 !(flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1335                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE))) {
1336                 return false;
1337             }
1338         } else if (attr.getCategory() == Sides.class) {
1339             Sides[] sidesArray = (Sides[])getSupportedAttributeValues(
1340                                           Sides.class,
1341                                           flavor,
1342                                           attributes);
1343 
1344             if (sidesArray != null) {
1345                 for (int i=0; i<sidesArray.length; i++) {
1346                     if (sidesArray[i] == (Sides)attr) {
1347                         return true;
1348                     }
1349                 }
1350             }
1351             return false;
1352         } else if (attr.getCategory() == OrientationRequested.class) {
1353             OrientationRequested[] orientArray =
1354                 (OrientationRequested[])getSupportedAttributeValues(
1355                                           OrientationRequested.class,
1356                                           flavor,
1357                                           attributes);
1358 
1359             if (orientArray != null) {
1360                 for (int i=0; i<orientArray.length; i++) {
1361                     if (orientArray[i] == (OrientationRequested)attr) {
1362                         return true;
1363                     }
1364                 }
1365             }
1366             return false;
1367         }
1368         return true;
1369     }
1370 
1371 
1372     public synchronized Object
1373         getDefaultAttributeValue(Class<? extends Attribute> category)
1374     {
1375         if (category == null) {
1376             throw new NullPointerException("null category");
1377         }
1378         if (!Attribute.class.isAssignableFrom(category)) {
1379             throw new IllegalArgumentException(category +
1380                                              " is not an Attribute");
1381         }
1382         if (!isAttributeCategorySupported(category)) {
1383             return null;
1384         }
1385 
1386         initAttributes();
1387 
1388         String catName = null;
1389         for (int i=0; i < printReqAttribDefault.length; i++) {
1390             PrintRequestAttribute pra =
1391                 (PrintRequestAttribute)printReqAttribDefault[i];
1392             if (pra.getCategory() == category) {
1393                 catName = pra.getName();
1394                 break;
1395             }
1396         }
1397         String attribName = catName+"-default";
1398         AttributeClass attribClass = (getAttMap != null) ?
1399                 (AttributeClass)getAttMap.get(attribName) : null;
1400 
1401         if (category == Copies.class) {
1402             if (attribClass != null) {
1403                 return new Copies(attribClass.getIntValue());
1404             } else {
1405                 return new Copies(1);
1406             }
1407         } else if (category == Chromaticity.class) {
1408             return Chromaticity.COLOR;
1409         } else if (category == Destination.class) {
1410             try {
1411                 return new Destination((new File("out.ps")).toURI());
1412             } catch (SecurityException se) {
1413                 try {
1414                     return new Destination(new URI("file:out.ps"));
1415                 } catch (URISyntaxException e) {
1416                     return null;
1417                 }
1418             }
1419         } else if (category == Fidelity.class) {
1420             return Fidelity.FIDELITY_FALSE;
1421         } else if (category == Finishings.class) {
1422             return Finishings.NONE;
1423         } else if (category == JobName.class) {
1424             return new JobName("Java Printing", null);
1425         } else if (category == JobSheets.class) {
1426             if (attribClass != null &&
1427                 attribClass.getStringValue().equals("none")) {
1428                 return JobSheets.NONE;
1429             } else {
1430                 return JobSheets.STANDARD;
1431             }
1432         } else if (category == Media.class) {
1433             defaultMediaIndex = 0;
1434             if (mediaSizeNames.length == 0) {
1435                 String defaultCountry = Locale.getDefault().getCountry();
1436                 if (defaultCountry != null &&
1437                     (defaultCountry.equals("") ||
1438                      defaultCountry.equals(Locale.US.getCountry()) ||
1439                      defaultCountry.equals(Locale.CANADA.getCountry()))) {
1440                     return MediaSizeName.NA_LETTER;
1441                 } else {
1442                     return MediaSizeName.ISO_A4;
1443                 }
1444             }
1445 
1446             if (attribClass != null) {
1447                 String name = attribClass.getStringValue();
1448                 if (isCupsPrinter) {
1449                     for (int i=0; i< customMediaSizeNames.length; i++) {
1450                         //REMIND:  get default from PPD. In native _getMedia,
1451                         // move default (ppd_option_t->defchoice) to index 0.
1452                         // In the meantime, use indexOf because PPD name
1453                         // may be different from the IPP attribute name.
1454                         if (customMediaSizeNames[i].toString().indexOf(name)
1455                             != -1) {
1456                             defaultMediaIndex = i;
1457                             return mediaSizeNames[defaultMediaIndex];
1458                         }
1459                     }
1460                 } else {
1461                     for (int i=0; i< mediaSizeNames.length; i++) {
1462                         if (mediaSizeNames[i].toString().indexOf(name) != -1) {
1463                             defaultMediaIndex = i;
1464                             return mediaSizeNames[defaultMediaIndex];
1465                         }
1466                     }
1467                 }
1468             }
1469             return mediaSizeNames[defaultMediaIndex];
1470 
1471         } else if (category == MediaPrintableArea.class) {
1472             MediaPrintableArea[] mpas;
1473              if ((cps != null)  &&
1474                  ((mpas = cps.getMediaPrintableArea()) != null)) {
1475                  if (defaultMediaIndex == -1) {
1476                      // initializes value of defaultMediaIndex
1477                      getDefaultAttributeValue(Media.class);
1478                  }
1479                  return mpas[defaultMediaIndex];
1480              } else {
1481                  String defaultCountry = Locale.getDefault().getCountry();
1482                  float iw, ih;
1483                  if (defaultCountry != null &&
1484                      (defaultCountry.equals("") ||
1485                       defaultCountry.equals(Locale.US.getCountry()) ||
1486                       defaultCountry.equals(Locale.CANADA.getCountry()))) {
1487                      iw = MediaSize.NA.LETTER.getX(Size2DSyntax.INCH) - 0.5f;
1488                      ih = MediaSize.NA.LETTER.getY(Size2DSyntax.INCH) - 0.5f;
1489                  } else {
1490                      iw = MediaSize.ISO.A4.getX(Size2DSyntax.INCH) - 0.5f;
1491                      ih = MediaSize.ISO.A4.getY(Size2DSyntax.INCH) - 0.5f;
1492                  }
1493                  return new MediaPrintableArea(0.25f, 0.25f, iw, ih,
1494                                                MediaPrintableArea.INCH);
1495              }
1496         } else if (category == NumberUp.class) {
1497             return new NumberUp(1); // for CUPS this is always 1
1498         } else if (category == OrientationRequested.class) {
1499             if (attribClass != null) {
1500                 switch (attribClass.getIntValue()) {
1501                 default:
1502                 case 3: return OrientationRequested.PORTRAIT;
1503                 case 4: return OrientationRequested.LANDSCAPE;
1504                 case 5: return OrientationRequested.REVERSE_LANDSCAPE;
1505                 case 6: return OrientationRequested.REVERSE_PORTRAIT;
1506                 }
1507             } else {
1508                 return OrientationRequested.PORTRAIT;
1509             }
1510         } else if (category == PageRanges.class) {
1511             if (attribClass != null) {
1512                 int[] range = attribClass.getIntRangeValue();
1513                 return new PageRanges(range[0], range[1]);
1514             } else {
1515                 return new PageRanges(1, Integer.MAX_VALUE);
1516             }
1517         } else if (category == RequestingUserName.class) {
1518             String userName = "";
1519             try {
1520               userName = System.getProperty("user.name", "");
1521             } catch (SecurityException se) {
1522             }
1523             return new RequestingUserName(userName, null);
1524         } else if (category == SheetCollate.class) {
1525             return SheetCollate.UNCOLLATED;
1526         } else if (category == Sides.class) {
1527             if (attribClass != null) {
1528                 if (attribClass.getStringValue().endsWith("long-edge")) {
1529                     return Sides.TWO_SIDED_LONG_EDGE;
1530                 } else if (attribClass.getStringValue().endsWith(
1531                                                            "short-edge")) {
1532                     return Sides.TWO_SIDED_SHORT_EDGE;
1533                 }
1534             }
1535             return Sides.ONE_SIDED;
1536         }
1537 
1538         return null;
1539     }
1540 
1541     public ServiceUIFactory getServiceUIFactory() {
1542         return null;
1543     }
1544 
1545     public void wakeNotifier() {
1546         synchronized (this) {
1547             if (notifier != null) {
1548                 notifier.wake();
1549             }
1550         }
1551     }
1552 
1553     public void addPrintServiceAttributeListener(
1554                                  PrintServiceAttributeListener listener) {
1555         synchronized (this) {
1556             if (listener == null) {
1557                 return;
1558             }
1559             if (notifier == null) {
1560                 notifier = new ServiceNotifier(this);
1561             }
1562             notifier.addListener(listener);
1563         }
1564     }
1565 
1566     public void removePrintServiceAttributeListener(
1567                                   PrintServiceAttributeListener listener) {
1568         synchronized (this) {
1569             if (listener == null || notifier == null ) {
1570                 return;
1571             }
1572             notifier.removeListener(listener);
1573             if (notifier.isEmpty()) {
1574                 notifier.stopNotifier();
1575                 notifier = null;
1576             }
1577         }
1578     }
1579 
1580     String getDest() {
1581         return printer;
1582     }
1583 
1584     public String getName() {
1585         /*
1586          * Mac is using printer-info IPP attribute for its human-readable printer
1587          * name and is also the identifier used in NSPrintInfo:setPrinter.
1588          */
1589         if (UnixPrintServiceLookup.isMac()) {
1590             PrintServiceAttributeSet psaSet = this.getAttributes();
1591             if (psaSet != null) {
1592                 PrinterInfo pName = (PrinterInfo)psaSet.get(PrinterInfo.class);
1593                 if (pName != null) {
1594                     return pName.toString();
1595                 }
1596             }
1597         }
1598         return printer;
1599     }
1600 
1601 
1602     public boolean usesClass(Class c) {
1603         return (c == sun.print.PSPrinterJob.class);
1604     }
1605 
1606 
1607     public static HttpURLConnection getIPPConnection(URL url) {
1608         HttpURLConnection connection;
1609         URLConnection urlc;
1610         try {
1611             urlc = url.openConnection();
1612         } catch (java.io.IOException ioe) {
1613             return null;
1614         }
1615         if (!(urlc instanceof HttpURLConnection)) {
1616             return null;
1617         }
1618         connection = (HttpURLConnection)urlc;
1619         connection.setUseCaches(false);
1620         connection.setDefaultUseCaches(false);
1621         connection.setDoInput(true);
1622         connection.setDoOutput(true);
1623         connection.setRequestProperty("Content-type", "application/ipp");
1624         return connection;
1625     }
1626 
1627 
1628     public synchronized boolean isPostscript() {
1629         if (isPS == null) {
1630            isPS = Boolean.TRUE;
1631             if (isCupsPrinter) {
1632                 try {
1633                     urlConnection = getIPPConnection(
1634                                              new URL(myURL+".ppd"));
1635 
1636                    InputStream is = urlConnection.getInputStream();
1637                    if (is != null) {
1638                        BufferedReader d =
1639                            new BufferedReader(new InputStreamReader(is,
1640                                                           Charset.forName("ISO-8859-1")));
1641                        String lineStr;
1642                        while ((lineStr = d.readLine()) != null) {
1643                            if (lineStr.startsWith("*cupsFilter:")) {
1644                                isPS = Boolean.FALSE;
1645                                break;
1646                            }
1647                        }
1648                     }
1649                 } catch (java.io.IOException e) {
1650                     debug_println(" isPostscript, e= "+e);
1651                     /* if PPD is not found, this may be a raw printer
1652                        and in this case it is assumed that it is a
1653                        Postscript printer */
1654                     // do nothing
1655                 }
1656             }
1657         }
1658         return isPS.booleanValue();
1659     }
1660 
1661 
1662     private void opGetAttributes() {
1663         try {
1664             debug_println(debugPrefix+"opGetAttributes myURI "+myURI+" myURL "+myURL);
1665 
1666             AttributeClass attClNoUri[] = {
1667                 AttributeClass.ATTRIBUTES_CHARSET,
1668                 AttributeClass.ATTRIBUTES_NATURAL_LANGUAGE};
1669 
1670             AttributeClass attCl[] = {
1671                 AttributeClass.ATTRIBUTES_CHARSET,
1672                 AttributeClass.ATTRIBUTES_NATURAL_LANGUAGE,
1673                 new AttributeClass("printer-uri",
1674                                    AttributeClass.TAG_URI,
1675                                    ""+myURI)};
1676 
1677             OutputStream os = (OutputStream)java.security.AccessController.
1678                 doPrivileged(new java.security.PrivilegedAction() {
1679                     public Object run() {
1680                         try {
1681                             return urlConnection.getOutputStream();
1682                         } catch (Exception e) {
1683                         }
1684                         return null;
1685                     }
1686                 });
1687 
1688             if (os == null) {
1689                 return;
1690             }
1691 
1692             boolean success = (myURI == null) ?
1693                 writeIPPRequest(os, OP_GET_ATTRIBUTES, attClNoUri) :
1694                 writeIPPRequest(os, OP_GET_ATTRIBUTES, attCl);
1695             if (success) {
1696                 InputStream is = null;
1697                 if ((is = urlConnection.getInputStream())!=null) {
1698                     HashMap[] responseMap = readIPPResponse(is);
1699 
1700                     if (responseMap != null && responseMap.length > 0) {
1701                         getAttMap = responseMap[0];
1702                     }
1703                 } else {
1704                     debug_println(debugPrefix+"opGetAttributes - null input stream");
1705                 }
1706                 is.close();
1707             }
1708             os.close();
1709         } catch (java.io.IOException e) {
1710             debug_println(debugPrefix+"opGetAttributes - input/output stream: "+e);
1711         }
1712     }
1713 
1714 
1715     public static boolean writeIPPRequest(OutputStream os,
1716                                            String operCode,
1717                                            AttributeClass[] attCl) {
1718         OutputStreamWriter osw;
1719         try {
1720             osw = new OutputStreamWriter(os, "UTF-8");
1721         } catch (java.io.UnsupportedEncodingException exc) {
1722             debug_println(debugPrefix+"writeIPPRequest, UTF-8 not supported? Exception: "+exc);
1723             return false;
1724         }
1725         debug_println(debugPrefix+"writeIPPRequest, op code= "+operCode);
1726         char[] opCode =  new char[2];
1727         opCode[0] =  (char)Byte.parseByte(operCode.substring(0,2), 16);
1728         opCode[1] =  (char)Byte.parseByte(operCode.substring(2,4), 16);
1729         char[] bytes = {0x01, 0x01, 0x00, 0x01};
1730         try {
1731             osw.write(bytes, 0, 2); // version number
1732             osw.write(opCode, 0, 2); // operation code
1733             bytes[0] = 0x00; bytes[1] = 0x00;
1734             osw.write(bytes, 0, 4); // request ID #1
1735 
1736             bytes[0] = 0x01; // operation-group-tag
1737             osw.write(bytes[0]);
1738 
1739             String valStr;
1740             char[] lenStr;
1741 
1742             AttributeClass ac;
1743             for (int i=0; i < attCl.length; i++) {
1744                 ac = attCl[i];
1745                 osw.write(ac.getType()); // value tag
1746 
1747                 lenStr = ac.getLenChars();
1748                 osw.write(lenStr, 0, 2); // length
1749                 osw.write(""+ac, 0, ac.getName().length());
1750 
1751                 // check if string range (0x35 -> 0x49)
1752                 if (ac.getType() >= AttributeClass.TAG_TEXT_LANGUAGE &&
1753                     ac.getType() <= AttributeClass.TAG_MIME_MEDIATYPE){
1754                     valStr = (String)ac.getObjectValue();
1755                     bytes[0] = 0; bytes[1] = (char)valStr.length();
1756                     osw.write(bytes, 0, 2);
1757                     osw.write(valStr, 0, valStr.length());
1758                 } // REMIND: need to support other value tags but for CUPS
1759                 // string is all we need.
1760             }
1761 
1762             osw.write(GRPTAG_END_ATTRIBUTES);
1763             osw.flush();
1764             osw.close();
1765         } catch (java.io.IOException ioe) {
1766             debug_println(debugPrefix+"writeIPPRequest, IPPPrintService Exception in writeIPPRequest: "+ioe);
1767             return false;
1768         }
1769         return true;
1770     }
1771 
1772 
1773     public static HashMap[] readIPPResponse(InputStream inputStream) {
1774 
1775         if (inputStream == null) {
1776             return null;
1777         }
1778 
1779         byte response[] = new byte[MAX_ATTRIBUTE_LENGTH];
1780         try {
1781 
1782             DataInputStream ois = new DataInputStream(inputStream);
1783 
1784             // read status and ID
1785             if ((ois.read(response, 0, 8) > -1) &&
1786                 (response[2] == STATUSCODE_SUCCESS)) {
1787 
1788                 ByteArrayOutputStream outObj;
1789                 int counter=0;
1790                 short len = 0;
1791                 String attribStr = null;
1792                 // assign default value
1793                 byte valTagByte = AttributeClass.TAG_KEYWORD;
1794                 ArrayList respList = new ArrayList();
1795                 HashMap responseMap = new HashMap();
1796 
1797                 response[0] = ois.readByte();
1798 
1799                 // check for group tags
1800                 while ((response[0] >= GRPTAG_OP_ATTRIBUTES) &&
1801                        (response[0] <= GRPTAG_PRINTER_ATTRIBUTES)
1802                           && (response[0] != GRPTAG_END_ATTRIBUTES)) {
1803                     debug_println(debugPrefix+"readIPPResponse, checking group tag,  response[0]= "+
1804                                   response[0]);
1805 
1806                     outObj = new ByteArrayOutputStream();
1807                     //make sure counter and attribStr are re-initialized
1808                     counter = 0;
1809                     attribStr = null;
1810 
1811                     // read value tag
1812                     response[0] = ois.readByte();
1813                     while (response[0] >= AttributeClass.TAG_UNSUPPORTED_VALUE &&
1814                            response[0] <= AttributeClass.TAG_MEMBER_ATTRNAME) {
1815                         // read name length
1816                         len  = ois.readShort();
1817 
1818                         // If current value is not part of previous attribute
1819                         // then close stream and add it to HashMap.
1820                         // It is part of previous attribute if name length=0.
1821                         if ((len != 0) && (attribStr != null)) {
1822                             //last byte is the total # of values
1823                             outObj.write(counter);
1824                             outObj.flush();
1825                             outObj.close();
1826                             byte outArray[] = outObj.toByteArray();
1827 
1828                             // if key exists, new HashMap
1829                             if (responseMap.containsKey(attribStr)) {
1830                                 respList.add(responseMap);
1831                                 responseMap = new HashMap();
1832                             }
1833 
1834                             // exclude those that are unknown
1835                             if (valTagByte >= AttributeClass.TAG_INT) {
1836                                 AttributeClass ac =
1837                                     new AttributeClass(attribStr,
1838                                                        valTagByte,
1839                                                        outArray);
1840 
1841                                 responseMap.put(ac.getName(), ac);
1842                                 debug_println(debugPrefix+ "readIPPResponse "+ac);
1843                             }
1844 
1845                             outObj = new ByteArrayOutputStream();
1846                             counter = 0; //reset counter
1847                         }
1848                         //check if this is new value tag
1849                         if (counter == 0) {
1850                             valTagByte = response[0];
1851                         }
1852                         // read attribute name
1853                         if (len != 0) {
1854                             // read "len" characters
1855                             // make sure it doesn't exceed the maximum
1856                             if (len > MAX_ATTRIBUTE_LENGTH) {
1857                                 response = new byte[len]; // expand as needed
1858                             }
1859                             ois.read(response, 0, len);
1860                             attribStr = new String(response, 0, len);
1861                         }
1862                         // read value length
1863                         len  = ois.readShort();
1864                         // write name length
1865                         outObj.write(len);
1866                         // read value, make sure it doesn't exceed the maximum
1867                         if (len > MAX_ATTRIBUTE_LENGTH) {
1868                             response = new byte[len]; // expand as needed
1869                         }
1870                         ois.read(response, 0, len);
1871                         // write value of "len" length
1872                         outObj.write(response, 0, len);
1873                         counter++;
1874                         // read next byte
1875                         response[0] = ois.readByte();
1876                     }
1877 
1878                     if (attribStr != null) {
1879                         outObj.write(counter);
1880                         outObj.flush();
1881                         outObj.close();
1882 
1883                         // if key exists in old HashMap, new HashMap
1884                         if ((counter != 0) &&
1885                             responseMap.containsKey(attribStr)) {
1886                             respList.add(responseMap);
1887                             responseMap = new HashMap();
1888                         }
1889 
1890                         byte outArray[] = outObj.toByteArray();
1891 
1892                         AttributeClass ac =
1893                             new AttributeClass(attribStr,
1894                                                valTagByte,
1895                                                outArray);
1896                         responseMap.put(ac.getName(), ac);
1897                     }
1898                 }
1899                 ois.close();
1900                 if ((responseMap != null) && (responseMap.size() > 0)) {
1901                     respList.add(responseMap);
1902                 }
1903                 return (HashMap[])respList.toArray(
1904                                   new HashMap[respList.size()]);
1905             } else {
1906                 debug_println(debugPrefix+
1907                           "readIPPResponse client error, IPP status code: 0x"+
1908                           toHex(response[2]) + toHex(response[3]));
1909                 return null;
1910             }
1911 
1912         } catch (java.io.IOException e) {
1913             debug_println(debugPrefix+"readIPPResponse: "+e);
1914             if (debugPrint) {
1915                 e.printStackTrace();
1916             }
1917             return null;
1918         }
1919     }
1920 
1921     private static String toHex(byte v) {
1922         String s = Integer.toHexString(v&0xff);
1923         return (s.length() == 2) ? s :  "0"+s;
1924     }
1925 
1926     public String toString() {
1927         return "IPP Printer : " + getName();
1928     }
1929 
1930     public boolean equals(Object obj) {
1931         return  (obj == this ||
1932                  (obj instanceof IPPPrintService &&
1933                   ((IPPPrintService)obj).getName().equals(getName())));
1934     }
1935 
1936     public int hashCode() {
1937         return this.getClass().hashCode()+getName().hashCode();
1938     }
1939 }