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