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         return flavor;
 933     }
 934 
 935 
 936     public boolean isDocFlavorSupported(DocFlavor flavor) {
 937         if (supportedDocFlavors == null) {
 938             getSupportedDocFlavors();
 939         }
 940         if (supportedDocFlavors != null) {
 941             for (int f=0; f<supportedDocFlavors.length; f++) {
 942                 if (flavor.equals(supportedDocFlavors[f])) {
 943                     return true;
 944                 }
 945             }
 946         }
 947         return false;
 948     }
 949 
 950 
 951     /**
 952      * Finds matching CustomMediaSizeName of given media.
 953      */
 954     public CustomMediaSizeName findCustomMedia(MediaSizeName media) {
 955         if (customMediaSizeNames == null) {
 956             return null;
 957         }
 958         for (int i=0; i< customMediaSizeNames.length; i++) {
 959             CustomMediaSizeName custom = customMediaSizeNames[i];
 960             MediaSizeName msn = custom.getStandardMedia();
 961             if (media.equals(msn)) {
 962                 return customMediaSizeNames[i];
 963             }
 964         }
 965         return null;
 966     }
 967 
 968 
 969     /**
 970      * Returns the matching standard Media using string comparison of names.
 971      */
 972     private Media getIPPMedia(String mediaName) {
 973         CustomMediaSizeName sampleSize = new CustomMediaSizeName("sample", "",
 974                                                                  0, 0);
 975         Media[] sizes = sampleSize.getSuperEnumTable();
 976         for (int i=0; i<sizes.length; i++) {
 977             if (mediaName.equals(""+sizes[i])) {
 978                 return sizes[i];
 979             }
 980         }
 981         CustomMediaTray sampleTray = new CustomMediaTray("sample", "");
 982         Media[] trays = sampleTray.getSuperEnumTable();
 983         for (int i=0; i<trays.length; i++) {
 984             if (mediaName.equals(""+trays[i])) {
 985                 return trays[i];
 986             }
 987         }
 988         return null;
 989     }
 990 
 991     private Media[] getSupportedMedia() {
 992         if ((getAttMap != null) &&
 993             getAttMap.containsKey("media-supported")) {
 994 
 995             AttributeClass attribClass = getAttMap.get("media-supported");
 996 
 997             if (attribClass != null) {
 998                 String[] mediaVals = attribClass.getArrayOfStringValues();
 999                 Media msn;
1000                 Media[] mediaNames =
1001                     new Media[mediaVals.length];
1002                 for (int i=0; i<mediaVals.length; i++) {
1003                     msn = getIPPMedia(mediaVals[i]);
1004                     //REMIND: if null, create custom?
1005                     mediaNames[i] = msn;
1006                 }
1007                 return mediaNames;
1008             }
1009         }
1010         return new Media[0];
1011     }
1012 
1013 
1014     public synchronized Class<?>[] getSupportedAttributeCategories() {
1015         if (supportedCats != null) {
1016             Class<?> [] copyCats = new Class<?>[supportedCats.length];
1017             System.arraycopy(supportedCats, 0, copyCats, 0, copyCats.length);
1018             return copyCats;
1019         }
1020 
1021         initAttributes();
1022 
1023         ArrayList<Class<?>> catList = new ArrayList<>();
1024 
1025         for (int i=0; i < printReqAttribDefault.length; i++) {
1026             PrintRequestAttribute pra =
1027                 (PrintRequestAttribute)printReqAttribDefault[i];
1028             if (getAttMap != null &&
1029                 getAttMap.containsKey(pra.getName()+"-supported")) {
1030                 catList.add(pra.getCategory());
1031             }
1032         }
1033 
1034         // Some IPP printers like lexc710 do not have list of supported media
1035         // but CUPS can get the media from PPD, so we still report as
1036         // supported category.
1037         if (isCupsPrinter) {
1038             if (!catList.contains(Media.class)) {
1039                 catList.add(Media.class);
1040             }
1041 
1042             // Always add MediaPrintable for cups,
1043             // because we can get it from PPD.
1044             catList.add(MediaPrintableArea.class);
1045 
1046             // this is already supported in UnixPrintJob
1047             catList.add(Destination.class);
1048 
1049             // It is unfortunate that CUPS doesn't provide a way to query
1050             // if printer supports collation but since most printers
1051             // now supports collation and that most OS has a way
1052             // of setting it, it is a safe assumption to just always
1053             // include SheetCollate as supported attribute.
1054 
1055             /*
1056                In Linux, we use Postscript for rendering but Linux still
1057                has issues in propagating Postscript-embedded setpagedevice
1058                setting like collation.  Therefore, we temporarily exclude
1059                Linux.
1060             */
1061             if (!PrintServiceLookupProvider.isLinux()) {
1062                 catList.add(SheetCollate.class);
1063             }
1064         }
1065 
1066         // With the assumption that  Chromaticity is equivalent to
1067         // ColorSupported.
1068         if (getAttMap != null && getAttMap.containsKey("color-supported")) {
1069             catList.add(Chromaticity.class);
1070         }
1071 
1072         // CUPS does not report printer resolution via IPP but it
1073         // may be gleaned from the PPD.
1074         PrinterResolution[] supportedRes = getPrintResolutions();
1075         if (supportedRes != null && (supportedRes.length > 0)) {
1076             catList.add(PrinterResolution.class);
1077         }
1078 
1079         supportedCats = new Class<?>[catList.size()];
1080         catList.toArray(supportedCats);
1081         Class<?>[] copyCats = new Class<?>[supportedCats.length];
1082         System.arraycopy(supportedCats, 0, copyCats, 0, copyCats.length);
1083         return copyCats;
1084     }
1085 
1086 
1087     public boolean
1088         isAttributeCategorySupported(Class<? extends Attribute> category)
1089     {
1090         if (category == null) {
1091             throw new NullPointerException("null category");
1092         }
1093         if (!(Attribute.class.isAssignableFrom(category))) {
1094             throw new IllegalArgumentException(category +
1095                                              " is not an Attribute");
1096         }
1097 
1098         if (supportedCats == null) {
1099             getSupportedAttributeCategories();
1100         }
1101 
1102         // It is safe to assume that Orientation is always supported
1103         // and even if CUPS or an IPP device reports it as not,
1104         // our renderer can do portrait, landscape and
1105         // reverse landscape.
1106         if (category == OrientationRequested.class) {
1107             return true;
1108         }
1109 
1110         for (int i=0;i<supportedCats.length;i++) {
1111             if (category == supportedCats[i]) {
1112                 return true;
1113             }
1114         }
1115 
1116         return false;
1117     }
1118 
1119     @SuppressWarnings("unchecked")
1120     public synchronized <T extends PrintServiceAttribute>
1121         T getAttribute(Class<T> category)
1122     {
1123         if (category == null) {
1124             throw new NullPointerException("category");
1125         }
1126         if (!(PrintServiceAttribute.class.isAssignableFrom(category))) {
1127             throw new IllegalArgumentException("Not a PrintServiceAttribute");
1128         }
1129 
1130         initAttributes();
1131 
1132         if (category == PrinterName.class) {
1133             return (T)(new PrinterName(printer, null));
1134         } else if (category == PrinterInfo.class) {
1135             PrinterInfo pInfo = new PrinterInfo(printer, null);
1136             AttributeClass ac = (getAttMap != null) ?
1137                 getAttMap.get(pInfo.getName())
1138                 : null;
1139             if (ac != null) {
1140                 return (T)(new PrinterInfo(ac.getStringValue(), null));
1141             }
1142             return (T)pInfo;
1143         } else if (category == QueuedJobCount.class) {
1144             QueuedJobCount qjc = new QueuedJobCount(0);
1145             AttributeClass ac = (getAttMap != null) ?
1146                 getAttMap.get(qjc.getName())
1147                 : null;
1148             if (ac != null) {
1149                 qjc = new QueuedJobCount(ac.getIntValue());
1150             }
1151             return (T)qjc;
1152         } else if (category == PrinterIsAcceptingJobs.class) {
1153             PrinterIsAcceptingJobs accJob =
1154                 PrinterIsAcceptingJobs.ACCEPTING_JOBS;
1155             AttributeClass ac = (getAttMap != null) ?
1156                 getAttMap.get(accJob.getName())
1157                 : null;
1158             if ((ac != null) && (ac.getByteValue() == 0)) {
1159                 accJob = PrinterIsAcceptingJobs.NOT_ACCEPTING_JOBS;
1160             }
1161             return (T)accJob;
1162         } else if (category == ColorSupported.class) {
1163             ColorSupported cs = ColorSupported.SUPPORTED;
1164             AttributeClass ac = (getAttMap != null) ?
1165                 getAttMap.get(cs.getName())
1166                 : null;
1167             if ((ac != null) && (ac.getByteValue() == 0)) {
1168                 cs = ColorSupported.NOT_SUPPORTED;
1169             }
1170             return (T)cs;
1171         } else if (category == PDLOverrideSupported.class) {
1172 
1173             if (isCupsPrinter) {
1174                 // Documented: For CUPS this will always be false
1175                 return (T)PDLOverrideSupported.NOT_ATTEMPTED;
1176             } else {
1177                 // REMIND: check attribute values
1178                 return (T)PDLOverrideSupported.NOT_ATTEMPTED;
1179             }
1180         } else if (category == PrinterURI.class) {
1181             return (T)(new PrinterURI(myURI));
1182         } else {
1183             return null;
1184         }
1185     }
1186 
1187 
1188     public synchronized PrintServiceAttributeSet getAttributes() {
1189         // update getAttMap by sending again get-attributes IPP request
1190         init = false;
1191         initAttributes();
1192 
1193         HashPrintServiceAttributeSet attrs =
1194             new HashPrintServiceAttributeSet();
1195 
1196         for (int i=0; i < serviceAttributes.length; i++) {
1197             String name = (String)serviceAttributes[i][1];
1198             if (getAttMap != null && getAttMap.containsKey(name)) {
1199                 @SuppressWarnings("unchecked")
1200                 Class<PrintServiceAttribute> c = (Class<PrintServiceAttribute>)serviceAttributes[i][0];
1201                 PrintServiceAttribute psa = getAttribute(c);
1202                 if (psa != null) {
1203                     attrs.add(psa);
1204                 }
1205             }
1206         }
1207         return AttributeSetUtilities.unmodifiableView(attrs);
1208     }
1209 
1210     public boolean isIPPSupportedImages(String mimeType) {
1211         if (supportedDocFlavors == null) {
1212             getSupportedDocFlavors();
1213         }
1214 
1215         if (mimeType.equals("image/png") && pngImagesAdded) {
1216             return true;
1217         } else if (mimeType.equals("image/gif") && gifImagesAdded) {
1218             return true;
1219         } else if (mimeType.equals("image/jpeg") && jpgImagesAdded) {
1220             return true;
1221         }
1222 
1223         return false;
1224     }
1225 
1226 
1227     private boolean isSupportedCopies(Copies copies) {
1228         CopiesSupported cs = (CopiesSupported)
1229             getSupportedAttributeValues(Copies.class, null, null);
1230         int[][] members = cs.getMembers();
1231         int min, max;
1232         if ((members.length > 0) && (members[0].length > 0)) {
1233             min = members[0][0];
1234             max = members[0][1];
1235         } else {
1236             min = 1;
1237             max = MAXCOPIES;
1238         }
1239 
1240         int value = copies.getValue();
1241         return (value >= min && value <= max);
1242     }
1243 
1244     private boolean isAutoSense(DocFlavor flavor) {
1245         if (flavor.equals(DocFlavor.BYTE_ARRAY.AUTOSENSE) ||
1246             flavor.equals(DocFlavor.INPUT_STREAM.AUTOSENSE) ||
1247             flavor.equals(DocFlavor.URL.AUTOSENSE)) {
1248             return true;
1249         }
1250         else {
1251             return false;
1252         }
1253     }
1254 
1255     private synchronized boolean isSupportedMediaTray(MediaTray msn) {
1256         initAttributes();
1257 
1258         if (mediaTrays != null) {
1259             for (int i=0; i<mediaTrays.length; i++) {
1260                if (msn.equals(mediaTrays[i])) {
1261                     return true;
1262                 }
1263             }
1264         }
1265         return false;
1266     }
1267 
1268     private synchronized boolean isSupportedMedia(MediaSizeName msn) {
1269         initAttributes();
1270 
1271         if (msn.equals((Media)getDefaultAttributeValue(Media.class))) {
1272             return true;
1273         }
1274         for (int i=0; i<mediaSizeNames.length; i++) {
1275             debug_println(debugPrefix+"isSupportedMedia, mediaSizeNames[i] "+mediaSizeNames[i]);
1276             if (msn.equals(mediaSizeNames[i])) {
1277                 return true;
1278             }
1279         }
1280         return false;
1281     }
1282 
1283     /* Return false if flavor is not null, pageable, nor printable and
1284      * Destination is part of attributes.
1285      */
1286     private boolean
1287         isDestinationSupported(DocFlavor flavor, AttributeSet attributes) {
1288 
1289             if ((attributes != null) &&
1290                     (attributes.get(Destination.class) != null) &&
1291                     !(flavor == null ||
1292                       flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1293                       flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE))) {
1294                 return false;
1295             }
1296             return true;
1297     }
1298 
1299 
1300     public boolean isAttributeValueSupported(Attribute attr,
1301                                              DocFlavor flavor,
1302                                              AttributeSet attributes) {
1303         if (attr == null) {
1304             throw new NullPointerException("null attribute");
1305         }
1306         if (flavor != null) {
1307             if (!isDocFlavorSupported(flavor)) {
1308                 throw new IllegalArgumentException(flavor +
1309                                                " is an unsupported flavor");
1310             } else if (isAutoSense(flavor)) {
1311                 return false;
1312             }
1313         }
1314         Class<? extends Attribute> category = attr.getCategory();
1315         if (!isAttributeCategorySupported(category)) {
1316             return false;
1317         }
1318 
1319         /* Test if the flavor is compatible with the attributes */
1320         if (!isDestinationSupported(flavor, attributes)) {
1321             return false;
1322         }
1323 
1324         /* Test if the flavor is compatible with the category */
1325         if (attr.getCategory() == Chromaticity.class) {
1326             if ((flavor == null) ||
1327                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1328                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE) ||
1329                 !isIPPSupportedImages(flavor.getMimeType())) {
1330                 return attr == Chromaticity.COLOR;
1331             } else {
1332                 return false;
1333             }
1334         } else if (attr.getCategory() == Copies.class) {
1335             return (flavor == null ||
1336                    !(flavor.equals(DocFlavor.INPUT_STREAM.POSTSCRIPT) ||
1337                    flavor.equals(DocFlavor.URL.POSTSCRIPT) ||
1338                    flavor.equals(DocFlavor.BYTE_ARRAY.POSTSCRIPT))) &&
1339                 isSupportedCopies((Copies)attr);
1340 
1341         } else if (attr.getCategory() == Destination.class) {
1342             if (flavor == null ||
1343                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1344                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
1345                 URI uri = ((Destination)attr).getURI();
1346                 if ("file".equals(uri.getScheme()) &&
1347                     !(uri.getSchemeSpecificPart().equals(""))) {
1348                     return true;
1349                 }
1350             }
1351             return false;
1352         } else if (attr.getCategory() == Media.class) {
1353             if (attr instanceof MediaSizeName) {
1354                 return isSupportedMedia((MediaSizeName)attr);
1355             }
1356             if (attr instanceof MediaTray) {
1357                 return isSupportedMediaTray((MediaTray)attr);
1358             }
1359         } else if (attr.getCategory() == PageRanges.class) {
1360             if (flavor != null &&
1361                 !(flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1362                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE))) {
1363                 return false;
1364             }
1365         } else if (attr.getCategory() == SheetCollate.class) {
1366             if (flavor != null &&
1367                 !(flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1368                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE))) {
1369                 return false;
1370             }
1371         } else if (attr.getCategory() == Sides.class) {
1372             Sides[] sidesArray = (Sides[])getSupportedAttributeValues(
1373                                           Sides.class,
1374                                           flavor,
1375                                           attributes);
1376 
1377             if (sidesArray != null) {
1378                 for (int i=0; i<sidesArray.length; i++) {
1379                     if (sidesArray[i] == (Sides)attr) {
1380                         return true;
1381                     }
1382                 }
1383             }
1384             return false;
1385         } else if (attr.getCategory() == OrientationRequested.class) {
1386             OrientationRequested[] orientArray =
1387                 (OrientationRequested[])getSupportedAttributeValues(
1388                                           OrientationRequested.class,
1389                                           flavor,
1390                                           attributes);
1391 
1392             if (orientArray != null) {
1393                 for (int i=0; i<orientArray.length; i++) {
1394                     if (orientArray[i] == (OrientationRequested)attr) {
1395                         return true;
1396                     }
1397                 }
1398             }
1399             return false;
1400         } if (attr.getCategory() == PrinterResolution.class) {
1401             if (attr instanceof PrinterResolution) {
1402                 return isSupportedResolution((PrinterResolution)attr);
1403             }
1404         }
1405         return true;
1406     }
1407 
1408 
1409     public synchronized Object
1410         getDefaultAttributeValue(Class<? extends Attribute> category)
1411     {
1412         if (category == null) {
1413             throw new NullPointerException("null category");
1414         }
1415         if (!Attribute.class.isAssignableFrom(category)) {
1416             throw new IllegalArgumentException(category +
1417                                              " is not an Attribute");
1418         }
1419         if (!isAttributeCategorySupported(category)) {
1420             return null;
1421         }
1422 
1423         initAttributes();
1424 
1425         String catName = null;
1426         for (int i=0; i < printReqAttribDefault.length; i++) {
1427             PrintRequestAttribute pra =
1428                 (PrintRequestAttribute)printReqAttribDefault[i];
1429             if (pra.getCategory() == category) {
1430                 catName = pra.getName();
1431                 break;
1432             }
1433         }
1434         String attribName = catName+"-default";
1435         AttributeClass attribClass = (getAttMap != null) ?
1436                 getAttMap.get(attribName) : null;
1437 
1438         if (category == Copies.class) {
1439             if (attribClass != null) {
1440                 return new Copies(attribClass.getIntValue());
1441             } else {
1442                 return new Copies(1);
1443             }
1444         } else if (category == Chromaticity.class) {
1445             return Chromaticity.COLOR;
1446         } else if (category == Destination.class) {
1447             try {
1448                 return new Destination((new File("out.ps")).toURI());
1449             } catch (SecurityException se) {
1450                 try {
1451                     return new Destination(new URI("file:out.ps"));
1452                 } catch (URISyntaxException e) {
1453                     return null;
1454                 }
1455             }
1456         } else if (category == Fidelity.class) {
1457             return Fidelity.FIDELITY_FALSE;
1458         } else if (category == Finishings.class) {
1459             return Finishings.NONE;
1460         } else if (category == JobName.class) {
1461             return new JobName("Java Printing", null);
1462         } else if (category == JobSheets.class) {
1463             if (attribClass != null &&
1464                 attribClass.getStringValue().equals("none")) {
1465                 return JobSheets.NONE;
1466             } else {
1467                 return JobSheets.STANDARD;
1468             }
1469         } else if (category == Media.class) {
1470             if (defaultMediaIndex == -1) {
1471                 defaultMediaIndex = 0;
1472             }
1473             if (mediaSizeNames.length == 0) {
1474                 String defaultCountry = Locale.getDefault().getCountry();
1475                 if (defaultCountry != null &&
1476                     (defaultCountry.equals("") ||
1477                      defaultCountry.equals(Locale.US.getCountry()) ||
1478                      defaultCountry.equals(Locale.CANADA.getCountry()))) {
1479                     return MediaSizeName.NA_LETTER;
1480                 } else {
1481                     return MediaSizeName.ISO_A4;
1482                 }
1483             }
1484 
1485             if (attribClass != null) {
1486                 String name = attribClass.getStringValue();
1487                 if (isCupsPrinter) {
1488                     return mediaSizeNames[defaultMediaIndex];
1489                 } else {
1490                     for (int i=0; i< mediaSizeNames.length; i++) {
1491                         if (mediaSizeNames[i].toString().indexOf(name) != -1) {
1492                             defaultMediaIndex = i;
1493                             return mediaSizeNames[defaultMediaIndex];
1494                         }
1495                     }
1496                 }
1497             }
1498             return mediaSizeNames[defaultMediaIndex];
1499 
1500         } else if (category == MediaPrintableArea.class) {
1501             MediaPrintableArea[] mpas;
1502              if ((cps != null)  &&
1503                  ((mpas = cps.getMediaPrintableArea()) != null)) {
1504                  if (defaultMediaIndex == -1) {
1505                      // initializes value of defaultMediaIndex
1506                      getDefaultAttributeValue(Media.class);
1507                  }
1508                  return mpas[defaultMediaIndex];
1509              } else {
1510                  String defaultCountry = Locale.getDefault().getCountry();
1511                  float iw, ih;
1512                  if (defaultCountry != null &&
1513                      (defaultCountry.equals("") ||
1514                       defaultCountry.equals(Locale.US.getCountry()) ||
1515                       defaultCountry.equals(Locale.CANADA.getCountry()))) {
1516                      iw = MediaSize.NA.LETTER.getX(Size2DSyntax.INCH) - 0.5f;
1517                      ih = MediaSize.NA.LETTER.getY(Size2DSyntax.INCH) - 0.5f;
1518                  } else {
1519                      iw = MediaSize.ISO.A4.getX(Size2DSyntax.INCH) - 0.5f;
1520                      ih = MediaSize.ISO.A4.getY(Size2DSyntax.INCH) - 0.5f;
1521                  }
1522                  return new MediaPrintableArea(0.25f, 0.25f, iw, ih,
1523                                                MediaPrintableArea.INCH);
1524              }
1525         } else if (category == NumberUp.class) {
1526             return new NumberUp(1); // for CUPS this is always 1
1527         } else if (category == OrientationRequested.class) {
1528             if (attribClass != null) {
1529                 switch (attribClass.getIntValue()) {
1530                 default:
1531                 case 3: return OrientationRequested.PORTRAIT;
1532                 case 4: return OrientationRequested.LANDSCAPE;
1533                 case 5: return OrientationRequested.REVERSE_LANDSCAPE;
1534                 case 6: return OrientationRequested.REVERSE_PORTRAIT;
1535                 }
1536             } else {
1537                 return OrientationRequested.PORTRAIT;
1538             }
1539         } else if (category == PageRanges.class) {
1540             if (attribClass != null) {
1541                 int[] range = attribClass.getIntRangeValue();
1542                 return new PageRanges(range[0], range[1]);
1543             } else {
1544                 return new PageRanges(1, Integer.MAX_VALUE);
1545             }
1546         } else if (category == RequestingUserName.class) {
1547             String userName = "";
1548             try {
1549               userName = System.getProperty("user.name", "");
1550             } catch (SecurityException se) {
1551             }
1552             return new RequestingUserName(userName, null);
1553         } else if (category == SheetCollate.class) {
1554             return SheetCollate.UNCOLLATED;
1555         } else if (category == Sides.class) {
1556             if (attribClass != null) {
1557                 if (attribClass.getStringValue().endsWith("long-edge")) {
1558                     return Sides.TWO_SIDED_LONG_EDGE;
1559                 } else if (attribClass.getStringValue().endsWith(
1560                                                            "short-edge")) {
1561                     return Sides.TWO_SIDED_SHORT_EDGE;
1562                 }
1563             }
1564             return Sides.ONE_SIDED;
1565         } else if (category == PrinterResolution.class) {
1566              PrinterResolution[] supportedRes = getPrintResolutions();
1567              if ((supportedRes != null) && (supportedRes.length > 0)) {
1568                 return supportedRes[0];
1569              } else {
1570                  return new PrinterResolution(300, 300, PrinterResolution.DPI);
1571              }
1572         }
1573 
1574         return null;
1575     }
1576 
1577     private PrinterResolution[] getPrintResolutions() {
1578         if (printerResolutions == null) {
1579             if (rawResolutions == null) {
1580               printerResolutions = new PrinterResolution[0];
1581             } else {
1582                 int numRes = rawResolutions.length / 2;
1583                 PrinterResolution[] pres = new PrinterResolution[numRes];
1584                 for (int i=0; i < numRes; i++) {
1585                     pres[i] =  new PrinterResolution(rawResolutions[i*2],
1586                                                      rawResolutions[i*2+1],
1587                                                      PrinterResolution.DPI);
1588                 }
1589                 printerResolutions = pres;
1590             }
1591         }
1592         return printerResolutions;
1593     }
1594 
1595     private boolean isSupportedResolution(PrinterResolution res) {
1596         PrinterResolution[] supportedRes = getPrintResolutions();
1597         if (supportedRes != null) {
1598             for (int i=0; i<supportedRes.length; i++) {
1599                 if (res.equals(supportedRes[i])) {
1600                     return true;
1601                 }
1602             }
1603         }
1604         return false;
1605     }
1606 
1607     public ServiceUIFactory getServiceUIFactory() {
1608         return null;
1609     }
1610 
1611     public void wakeNotifier() {
1612         synchronized (this) {
1613             if (notifier != null) {
1614                 notifier.wake();
1615             }
1616         }
1617     }
1618 
1619     public void addPrintServiceAttributeListener(
1620                                  PrintServiceAttributeListener listener) {
1621         synchronized (this) {
1622             if (listener == null) {
1623                 return;
1624             }
1625             if (notifier == null) {
1626                 notifier = new ServiceNotifier(this);
1627             }
1628             notifier.addListener(listener);
1629         }
1630     }
1631 
1632     public void removePrintServiceAttributeListener(
1633                                   PrintServiceAttributeListener listener) {
1634         synchronized (this) {
1635             if (listener == null || notifier == null ) {
1636                 return;
1637             }
1638             notifier.removeListener(listener);
1639             if (notifier.isEmpty()) {
1640                 notifier.stopNotifier();
1641                 notifier = null;
1642             }
1643         }
1644     }
1645 
1646     String getDest() {
1647         return printer;
1648     }
1649 
1650     public String getName() {
1651         /*
1652          * Mac is using printer-info IPP attribute for its human-readable printer
1653          * name and is also the identifier used in NSPrintInfo:setPrinter.
1654          */
1655         if (PrintServiceLookupProvider.isMac()) {
1656             PrintServiceAttributeSet psaSet = this.getAttributes();
1657             if (psaSet != null) {
1658                 PrinterInfo pName = (PrinterInfo)psaSet.get(PrinterInfo.class);
1659                 if (pName != null) {
1660                     return pName.toString();
1661                 }
1662             }
1663         }
1664         return printer;
1665     }
1666 
1667 
1668     public boolean usesClass(Class<?> c) {
1669         return (c == sun.print.PSPrinterJob.class);
1670     }
1671 
1672 
1673     public static HttpURLConnection getIPPConnection(URL url) {
1674         HttpURLConnection connection;
1675         URLConnection urlc;
1676         try {
1677             urlc = url.openConnection();
1678         } catch (java.io.IOException ioe) {
1679             return null;
1680         }
1681         if (!(urlc instanceof HttpURLConnection)) {
1682             return null;
1683         }
1684         connection = (HttpURLConnection)urlc;
1685         connection.setUseCaches(false);
1686         connection.setDefaultUseCaches(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 }