1 /*
   2  * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.print;
  27 
  28 import javax.print.attribute.*;
  29 import javax.print.attribute.standard.*;
  30 import javax.print.DocFlavor;
  31 import javax.print.DocPrintJob;
  32 import javax.print.PrintService;
  33 import javax.print.ServiceUIFactory;
  34 import java.util.ArrayList;
  35 import java.util.HashMap;
  36 import java.util.Locale;
  37 import java.util.Date;
  38 import java.util.Arrays;
  39 import java.security.AccessController;
  40 import java.security.PrivilegedActionException;
  41 import java.security.PrivilegedExceptionAction;
  42 import javax.print.event.PrintServiceAttributeListener;
  43 
  44 import java.net.URI;
  45 import java.net.URISyntaxException;
  46 import java.net.URL;
  47 import java.net.URLConnection;
  48 import java.net.HttpURLConnection;
  49 import java.io.File;
  50 import java.io.InputStream;
  51 import java.io.OutputStream;
  52 import java.io.OutputStreamWriter;
  53 import java.io.DataInputStream;
  54 import java.io.ByteArrayOutputStream;
  55 import java.io.ByteArrayInputStream;
  56 import java.io.BufferedReader;
  57 import java.io.InputStreamReader;
  58 import java.nio.charset.Charset;
  59 
  60 import java.util.Iterator;
  61 import java.util.HashSet;
  62 
  63 
  64 public class IPPPrintService implements PrintService, SunPrinterJobService {
  65 
  66     public static final boolean debugPrint;
  67     private static final String debugPrefix = "IPPPrintService>> ";
  68     protected static void debug_println(String str) {
  69         if (debugPrint) {
  70             System.out.println(str);
  71         }
  72     }
  73 
  74     private static final String FORCE_PIPE_PROP = "sun.print.ippdebug";
  75 
  76     static {
  77         String debugStr = java.security.AccessController.doPrivileged(
  78                   new sun.security.action.GetPropertyAction(FORCE_PIPE_PROP));
  79 
  80         debugPrint = "true".equalsIgnoreCase(debugStr);
  81     }
  82 
  83     private String printer;
  84     private URI    myURI;
  85     private URL    myURL;
  86     transient private ServiceNotifier notifier = null;
  87 
  88     private static int MAXCOPIES = 1000;
  89     private static short MAX_ATTRIBUTE_LENGTH = 255;
  90 
  91     private CUPSPrinter cps;
  92     private HttpURLConnection urlConnection = null;
  93     private DocFlavor[] supportedDocFlavors;
  94     private Class<?>[] supportedCats;
  95     private MediaTray[] mediaTrays;
  96     private MediaSizeName[] mediaSizeNames;
  97     private CustomMediaSizeName[] customMediaSizeNames;
  98     private int defaultMediaIndex;
  99     private 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         return null;
 930     }
 931 
 932 
 933     public boolean isDocFlavorSupported(DocFlavor flavor) {
 934         if (supportedDocFlavors == null) {
 935             getSupportedDocFlavors();
 936         }
 937         if (supportedDocFlavors != null) {
 938             for (int f=0; f<supportedDocFlavors.length; f++) {
 939                 if (flavor.equals(supportedDocFlavors[f])) {
 940                     return true;
 941                 }
 942             }
 943         }
 944         return false;
 945     }
 946 
 947 
 948     /**
 949      * Finds matching CustomMediaSizeName of given media.
 950      */
 951     public CustomMediaSizeName findCustomMedia(MediaSizeName media) {
 952         if (customMediaSizeNames == null) {
 953             return null;
 954         }
 955         for (int i=0; i< customMediaSizeNames.length; i++) {
 956             CustomMediaSizeName custom = customMediaSizeNames[i];
 957             MediaSizeName msn = custom.getStandardMedia();
 958             if (media.equals(msn)) {
 959                 return customMediaSizeNames[i];
 960             }
 961         }
 962         return null;
 963     }
 964 
 965 
 966     /**
 967      * Returns the matching standard Media using string comparison of names.
 968      */
 969     private Media getIPPMedia(String mediaName) {
 970         CustomMediaSizeName sampleSize = new CustomMediaSizeName("sample", "",
 971                                                                  0, 0);
 972         Media[] sizes = sampleSize.getSuperEnumTable();
 973         for (int i=0; i<sizes.length; i++) {
 974             if (mediaName.equals(""+sizes[i])) {
 975                 return sizes[i];
 976             }
 977         }
 978         CustomMediaTray sampleTray = new CustomMediaTray("sample", "");
 979         Media[] trays = sampleTray.getSuperEnumTable();
 980         for (int i=0; i<trays.length; i++) {
 981             if (mediaName.equals(""+trays[i])) {
 982                 return trays[i];
 983             }
 984         }
 985         return null;
 986     }
 987 
 988     private Media[] getSupportedMedia() {
 989         if ((getAttMap != null) &&
 990             getAttMap.containsKey("media-supported")) {
 991 
 992             AttributeClass attribClass = getAttMap.get("media-supported");
 993 
 994             if (attribClass != null) {
 995                 String[] mediaVals = attribClass.getArrayOfStringValues();
 996                 Media msn;
 997                 Media[] mediaNames =
 998                     new Media[mediaVals.length];
 999                 for (int i=0; i<mediaVals.length; i++) {
1000                     msn = getIPPMedia(mediaVals[i]);
1001                     //REMIND: if null, create custom?
1002                     mediaNames[i] = msn;
1003                 }
1004                 return mediaNames;
1005             }
1006         }
1007         return new Media[0];
1008     }
1009 
1010 
1011     public synchronized Class<?>[] getSupportedAttributeCategories() {
1012         if (supportedCats != null) {
1013             Class<?> [] copyCats = new Class<?>[supportedCats.length];
1014             System.arraycopy(supportedCats, 0, copyCats, 0, copyCats.length);
1015             return copyCats;
1016         }
1017 
1018         initAttributes();
1019 
1020         ArrayList<Class<?>> catList = new ArrayList<>();
1021 
1022         for (int i=0; i < printReqAttribDefault.length; i++) {
1023             PrintRequestAttribute pra =
1024                 (PrintRequestAttribute)printReqAttribDefault[i];
1025             if (getAttMap != null &&
1026                 getAttMap.containsKey(pra.getName()+"-supported")) {
1027                 catList.add(pra.getCategory());
1028             }
1029         }
1030 
1031         // Some IPP printers like lexc710 do not have list of supported media
1032         // but CUPS can get the media from PPD, so we still report as
1033         // supported category.
1034         if (isCupsPrinter) {
1035             if (!catList.contains(Media.class)) {
1036                 catList.add(Media.class);
1037             }
1038 
1039             // Always add MediaPrintable for cups,
1040             // because we can get it from PPD.
1041             catList.add(MediaPrintableArea.class);
1042 
1043             // this is already supported in UnixPrintJob
1044             catList.add(Destination.class);
1045 
1046             // It is unfortunate that CUPS doesn't provide a way to query
1047             // if printer supports collation but since most printers
1048             // now supports collation and that most OS has a way
1049             // of setting it, it is a safe assumption to just always
1050             // include SheetCollate as supported attribute.
1051 
1052             /*
1053                In Linux, we use Postscript for rendering but Linux still
1054                has issues in propagating Postscript-embedded setpagedevice
1055                setting like collation.  Therefore, we temporarily exclude
1056                Linux.
1057             */
1058             if (!PrintServiceLookupProvider.isLinux()) {
1059                 catList.add(SheetCollate.class);
1060             }
1061         }
1062 
1063         // With the assumption that  Chromaticity is equivalent to
1064         // ColorSupported.
1065         if (getAttMap != null && getAttMap.containsKey("color-supported")) {
1066             catList.add(Chromaticity.class);
1067         }
1068 
1069         // CUPS does not report printer resolution via IPP but it
1070         // may be gleaned from the PPD.
1071         PrinterResolution[] supportedRes = getPrintResolutions();
1072         if (supportedRes != null && (supportedRes.length > 0)) {
1073             catList.add(PrinterResolution.class);
1074         }
1075 
1076         supportedCats = new Class<?>[catList.size()];
1077         catList.toArray(supportedCats);
1078         Class<?>[] copyCats = new Class<?>[supportedCats.length];
1079         System.arraycopy(supportedCats, 0, copyCats, 0, copyCats.length);
1080         return copyCats;
1081     }
1082 
1083 
1084     public boolean
1085         isAttributeCategorySupported(Class<? extends Attribute> category)
1086     {
1087         if (category == null) {
1088             throw new NullPointerException("null category");
1089         }
1090         if (!(Attribute.class.isAssignableFrom(category))) {
1091             throw new IllegalArgumentException(category +
1092                                              " is not an Attribute");
1093         }
1094 
1095         if (supportedCats == null) {
1096             getSupportedAttributeCategories();
1097         }
1098 
1099         // It is safe to assume that Orientation is always supported
1100         // and even if CUPS or an IPP device reports it as not,
1101         // our renderer can do portrait, landscape and
1102         // reverse landscape.
1103         if (category == OrientationRequested.class) {
1104             return true;
1105         }
1106 
1107         for (int i=0;i<supportedCats.length;i++) {
1108             if (category == supportedCats[i]) {
1109                 return true;
1110             }
1111         }
1112 
1113         return false;
1114     }
1115 
1116     @SuppressWarnings("unchecked")
1117     public synchronized <T extends PrintServiceAttribute>
1118         T getAttribute(Class<T> category)
1119     {
1120         if (category == null) {
1121             throw new NullPointerException("category");
1122         }
1123         if (!(PrintServiceAttribute.class.isAssignableFrom(category))) {
1124             throw new IllegalArgumentException("Not a PrintServiceAttribute");
1125         }
1126 
1127         initAttributes();
1128 
1129         if (category == PrinterName.class) {
1130             return (T)(new PrinterName(printer, null));
1131         } else if (category == PrinterInfo.class) {
1132             PrinterInfo pInfo = new PrinterInfo(printer, null);
1133             AttributeClass ac = (getAttMap != null) ?
1134                 getAttMap.get(pInfo.getName())
1135                 : null;
1136             if (ac != null) {
1137                 return (T)(new PrinterInfo(ac.getStringValue(), null));
1138             }
1139             return (T)pInfo;
1140         } else if (category == QueuedJobCount.class) {
1141             QueuedJobCount qjc = new QueuedJobCount(0);
1142             AttributeClass ac = (getAttMap != null) ?
1143                 getAttMap.get(qjc.getName())
1144                 : null;
1145             if (ac != null) {
1146                 qjc = new QueuedJobCount(ac.getIntValue());
1147             }
1148             return (T)qjc;
1149         } else if (category == PrinterIsAcceptingJobs.class) {
1150             PrinterIsAcceptingJobs accJob =
1151                 PrinterIsAcceptingJobs.ACCEPTING_JOBS;
1152             AttributeClass ac = (getAttMap != null) ?
1153                 getAttMap.get(accJob.getName())
1154                 : null;
1155             if ((ac != null) && (ac.getByteValue() == 0)) {
1156                 accJob = PrinterIsAcceptingJobs.NOT_ACCEPTING_JOBS;
1157             }
1158             return (T)accJob;
1159         } else if (category == ColorSupported.class) {
1160             ColorSupported cs = ColorSupported.SUPPORTED;
1161             AttributeClass ac = (getAttMap != null) ?
1162                 getAttMap.get(cs.getName())
1163                 : null;
1164             if ((ac != null) && (ac.getByteValue() == 0)) {
1165                 cs = ColorSupported.NOT_SUPPORTED;
1166             }
1167             return (T)cs;
1168         } else if (category == PDLOverrideSupported.class) {
1169 
1170             if (isCupsPrinter) {
1171                 // Documented: For CUPS this will always be false
1172                 return (T)PDLOverrideSupported.NOT_ATTEMPTED;
1173             } else {
1174                 // REMIND: check attribute values
1175                 return (T)PDLOverrideSupported.NOT_ATTEMPTED;
1176             }
1177         } else if (category == PrinterURI.class) {
1178             return (T)(new PrinterURI(myURI));
1179         } else {
1180             return null;
1181         }
1182     }
1183 
1184 
1185     public synchronized PrintServiceAttributeSet getAttributes() {
1186         // update getAttMap by sending again get-attributes IPP request
1187         init = false;
1188         initAttributes();
1189 
1190         HashPrintServiceAttributeSet attrs =
1191             new HashPrintServiceAttributeSet();
1192 
1193         for (int i=0; i < serviceAttributes.length; i++) {
1194             String name = (String)serviceAttributes[i][1];
1195             if (getAttMap != null && getAttMap.containsKey(name)) {
1196                 @SuppressWarnings("unchecked")
1197                 Class<PrintServiceAttribute> c = (Class<PrintServiceAttribute>)serviceAttributes[i][0];
1198                 PrintServiceAttribute psa = getAttribute(c);
1199                 if (psa != null) {
1200                     attrs.add(psa);
1201                 }
1202             }
1203         }
1204         return AttributeSetUtilities.unmodifiableView(attrs);
1205     }
1206 
1207     public boolean isIPPSupportedImages(String mimeType) {
1208         if (supportedDocFlavors == null) {
1209             getSupportedDocFlavors();
1210         }
1211 
1212         if (mimeType.equals("image/png") && pngImagesAdded) {
1213             return true;
1214         } else if (mimeType.equals("image/gif") && gifImagesAdded) {
1215             return true;
1216         } else if (mimeType.equals("image/jpeg") && jpgImagesAdded) {
1217             return true;
1218         }
1219 
1220         return false;
1221     }
1222 
1223 
1224     private boolean isSupportedCopies(Copies copies) {
1225         CopiesSupported cs = (CopiesSupported)
1226             getSupportedAttributeValues(Copies.class, null, null);
1227         int[][] members = cs.getMembers();
1228         int min, max;
1229         if ((members.length > 0) && (members[0].length > 0)) {
1230             min = members[0][0];
1231             max = members[0][1];
1232         } else {
1233             min = 1;
1234             max = MAXCOPIES;
1235         }
1236 
1237         int value = copies.getValue();
1238         return (value >= min && value <= max);
1239     }
1240 
1241     private boolean isAutoSense(DocFlavor flavor) {
1242         if (flavor.equals(DocFlavor.BYTE_ARRAY.AUTOSENSE) ||
1243             flavor.equals(DocFlavor.INPUT_STREAM.AUTOSENSE) ||
1244             flavor.equals(DocFlavor.URL.AUTOSENSE)) {
1245             return true;
1246         }
1247         else {
1248             return false;
1249         }
1250     }
1251 
1252     private synchronized boolean isSupportedMediaTray(MediaTray msn) {
1253         initAttributes();
1254 
1255         if (mediaTrays != null) {
1256             for (int i=0; i<mediaTrays.length; i++) {
1257                if (msn.equals(mediaTrays[i])) {
1258                     return true;
1259                 }
1260             }
1261         }
1262         return false;
1263     }
1264 
1265     private synchronized boolean isSupportedMedia(MediaSizeName msn) {
1266         initAttributes();
1267 
1268         if (msn.equals((Media)getDefaultAttributeValue(Media.class))) {
1269             return true;
1270         }
1271         for (int i=0; i<mediaSizeNames.length; i++) {
1272             debug_println(debugPrefix+"isSupportedMedia, mediaSizeNames[i] "+mediaSizeNames[i]);
1273             if (msn.equals(mediaSizeNames[i])) {
1274                 return true;
1275             }
1276         }
1277         return false;
1278     }
1279 
1280     /* Return false if flavor is not null, pageable, nor printable and
1281      * Destination is part of attributes.
1282      */
1283     private boolean
1284         isDestinationSupported(DocFlavor flavor, AttributeSet attributes) {
1285 
1286             if ((attributes != null) &&
1287                     (attributes.get(Destination.class) != null) &&
1288                     !(flavor == null ||
1289                       flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1290                       flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE))) {
1291                 return false;
1292             }
1293             return true;
1294     }
1295 
1296 
1297     public boolean isAttributeValueSupported(Attribute attr,
1298                                              DocFlavor flavor,
1299                                              AttributeSet attributes) {
1300         if (attr == null) {
1301             throw new NullPointerException("null attribute");
1302         }
1303         if (flavor != null) {
1304             if (!isDocFlavorSupported(flavor)) {
1305                 throw new IllegalArgumentException(flavor +
1306                                                " is an unsupported flavor");
1307             } else if (isAutoSense(flavor)) {
1308                 return false;
1309             }
1310         }
1311         Class<? extends Attribute> category = attr.getCategory();
1312         if (!isAttributeCategorySupported(category)) {
1313             return false;
1314         }
1315 
1316         /* Test if the flavor is compatible with the attributes */
1317         if (!isDestinationSupported(flavor, attributes)) {
1318             return false;
1319         }
1320 
1321         /* Test if the flavor is compatible with the category */
1322         if (attr.getCategory() == Chromaticity.class) {
1323             if ((flavor == null) ||
1324                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1325                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE) ||
1326                 !isIPPSupportedImages(flavor.getMimeType())) {
1327                 return attr == Chromaticity.COLOR;
1328             } else {
1329                 return false;
1330             }
1331         } else if (attr.getCategory() == Copies.class) {
1332             return (flavor == null ||
1333                    !(flavor.equals(DocFlavor.INPUT_STREAM.POSTSCRIPT) ||
1334                    flavor.equals(DocFlavor.URL.POSTSCRIPT) ||
1335                    flavor.equals(DocFlavor.BYTE_ARRAY.POSTSCRIPT))) &&
1336                 isSupportedCopies((Copies)attr);
1337 
1338         } else if (attr.getCategory() == Destination.class) {
1339             if (flavor == null ||
1340                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1341                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
1342                 URI uri = ((Destination)attr).getURI();
1343                 if ("file".equals(uri.getScheme()) &&
1344                     !(uri.getSchemeSpecificPart().equals(""))) {
1345                     return true;
1346                 }
1347             }
1348             return false;
1349         } else if (attr.getCategory() == Media.class) {
1350             if (attr instanceof MediaSizeName) {
1351                 return isSupportedMedia((MediaSizeName)attr);
1352             }
1353             if (attr instanceof MediaTray) {
1354                 return isSupportedMediaTray((MediaTray)attr);
1355             }
1356         } else if (attr.getCategory() == PageRanges.class) {
1357             if (flavor != null &&
1358                 !(flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1359                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE))) {
1360                 return false;
1361             }
1362         } else if (attr.getCategory() == SheetCollate.class) {
1363             if (flavor != null &&
1364                 !(flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) ||
1365                 flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE))) {
1366                 return false;
1367             }
1368         } else if (attr.getCategory() == Sides.class) {
1369             Sides[] sidesArray = (Sides[])getSupportedAttributeValues(
1370                                           Sides.class,
1371                                           flavor,
1372                                           attributes);
1373 
1374             if (sidesArray != null) {
1375                 for (int i=0; i<sidesArray.length; i++) {
1376                     if (sidesArray[i] == (Sides)attr) {
1377                         return true;
1378                     }
1379                 }
1380             }
1381             return false;
1382         } else if (attr.getCategory() == OrientationRequested.class) {
1383             OrientationRequested[] orientArray =
1384                 (OrientationRequested[])getSupportedAttributeValues(
1385                                           OrientationRequested.class,
1386                                           flavor,
1387                                           attributes);
1388 
1389             if (orientArray != null) {
1390                 for (int i=0; i<orientArray.length; i++) {
1391                     if (orientArray[i] == (OrientationRequested)attr) {
1392                         return true;
1393                     }
1394                 }
1395             }
1396             return false;
1397         } if (attr.getCategory() == PrinterResolution.class) {
1398             if (attr instanceof PrinterResolution) {
1399                 return isSupportedResolution((PrinterResolution)attr);
1400             }
1401         }
1402         return true;
1403     }
1404 
1405 
1406     public synchronized Object
1407         getDefaultAttributeValue(Class<? extends Attribute> category)
1408     {
1409         if (category == null) {
1410             throw new NullPointerException("null category");
1411         }
1412         if (!Attribute.class.isAssignableFrom(category)) {
1413             throw new IllegalArgumentException(category +
1414                                              " is not an Attribute");
1415         }
1416         if (!isAttributeCategorySupported(category)) {
1417             return null;
1418         }
1419 
1420         initAttributes();
1421 
1422         String catName = null;
1423         for (int i=0; i < printReqAttribDefault.length; i++) {
1424             PrintRequestAttribute pra =
1425                 (PrintRequestAttribute)printReqAttribDefault[i];
1426             if (pra.getCategory() == category) {
1427                 catName = pra.getName();
1428                 break;
1429             }
1430         }
1431         String attribName = catName+"-default";
1432         AttributeClass attribClass = (getAttMap != null) ?
1433                 getAttMap.get(attribName) : null;
1434 
1435         if (category == Copies.class) {
1436             if (attribClass != null) {
1437                 return new Copies(attribClass.getIntValue());
1438             } else {
1439                 return new Copies(1);
1440             }
1441         } else if (category == Chromaticity.class) {
1442             return Chromaticity.COLOR;
1443         } else if (category == Destination.class) {
1444             try {
1445                 return new Destination((new File("out.ps")).toURI());
1446             } catch (SecurityException se) {
1447                 try {
1448                     return new Destination(new URI("file:out.ps"));
1449                 } catch (URISyntaxException e) {
1450                     return null;
1451                 }
1452             }
1453         } else if (category == Fidelity.class) {
1454             return Fidelity.FIDELITY_FALSE;
1455         } else if (category == Finishings.class) {
1456             return Finishings.NONE;
1457         } else if (category == JobName.class) {
1458             return new JobName("Java Printing", null);
1459         } else if (category == JobSheets.class) {
1460             if (attribClass != null &&
1461                 attribClass.getStringValue().equals("none")) {
1462                 return JobSheets.NONE;
1463             } else {
1464                 return JobSheets.STANDARD;
1465             }
1466         } else if (category == Media.class) {
1467             if (defaultMediaIndex == -1) {
1468                 defaultMediaIndex = 0;
1469             }
1470             if (mediaSizeNames.length == 0) {
1471                 String defaultCountry = Locale.getDefault().getCountry();
1472                 if (defaultCountry != null &&
1473                     (defaultCountry.equals("") ||
1474                      defaultCountry.equals(Locale.US.getCountry()) ||
1475                      defaultCountry.equals(Locale.CANADA.getCountry()))) {
1476                     return MediaSizeName.NA_LETTER;
1477                 } else {
1478                     return MediaSizeName.ISO_A4;
1479                 }
1480             }
1481 
1482             if (attribClass != null) {
1483                 String name = attribClass.getStringValue();
1484                 if (isCupsPrinter) {
1485                     return mediaSizeNames[defaultMediaIndex];
1486                 } else {
1487                     for (int i=0; i< mediaSizeNames.length; i++) {
1488                         if (mediaSizeNames[i].toString().indexOf(name) != -1) {
1489                             defaultMediaIndex = i;
1490                             return mediaSizeNames[defaultMediaIndex];
1491                         }
1492                     }
1493                 }
1494             }
1495             return mediaSizeNames[defaultMediaIndex];
1496 
1497         } else if (category == MediaPrintableArea.class) {
1498             MediaPrintableArea[] mpas;
1499              if ((cps != null)  &&
1500                  ((mpas = cps.getMediaPrintableArea()) != null)) {
1501                  if (defaultMediaIndex == -1) {
1502                      // initializes value of defaultMediaIndex
1503                      getDefaultAttributeValue(Media.class);
1504                  }
1505                  return mpas[defaultMediaIndex];
1506              } else {
1507                  String defaultCountry = Locale.getDefault().getCountry();
1508                  float iw, ih;
1509                  if (defaultCountry != null &&
1510                      (defaultCountry.equals("") ||
1511                       defaultCountry.equals(Locale.US.getCountry()) ||
1512                       defaultCountry.equals(Locale.CANADA.getCountry()))) {
1513                      iw = MediaSize.NA.LETTER.getX(Size2DSyntax.INCH) - 0.5f;
1514                      ih = MediaSize.NA.LETTER.getY(Size2DSyntax.INCH) - 0.5f;
1515                  } else {
1516                      iw = MediaSize.ISO.A4.getX(Size2DSyntax.INCH) - 0.5f;
1517                      ih = MediaSize.ISO.A4.getY(Size2DSyntax.INCH) - 0.5f;
1518                  }
1519                  return new MediaPrintableArea(0.25f, 0.25f, iw, ih,
1520                                                MediaPrintableArea.INCH);
1521              }
1522         } else if (category == NumberUp.class) {
1523             return new NumberUp(1); // for CUPS this is always 1
1524         } else if (category == OrientationRequested.class) {
1525             if (attribClass != null) {
1526                 switch (attribClass.getIntValue()) {
1527                 default:
1528                 case 3: return OrientationRequested.PORTRAIT;
1529                 case 4: return OrientationRequested.LANDSCAPE;
1530                 case 5: return OrientationRequested.REVERSE_LANDSCAPE;
1531                 case 6: return OrientationRequested.REVERSE_PORTRAIT;
1532                 }
1533             } else {
1534                 return OrientationRequested.PORTRAIT;
1535             }
1536         } else if (category == PageRanges.class) {
1537             if (attribClass != null) {
1538                 int[] range = attribClass.getIntRangeValue();
1539                 return new PageRanges(range[0], range[1]);
1540             } else {
1541                 return new PageRanges(1, Integer.MAX_VALUE);
1542             }
1543         } else if (category == RequestingUserName.class) {
1544             String userName = "";
1545             try {
1546               userName = System.getProperty("user.name", "");
1547             } catch (SecurityException se) {
1548             }
1549             return new RequestingUserName(userName, null);
1550         } else if (category == SheetCollate.class) {
1551             return SheetCollate.UNCOLLATED;
1552         } else if (category == Sides.class) {
1553             if (attribClass != null) {
1554                 if (attribClass.getStringValue().endsWith("long-edge")) {
1555                     return Sides.TWO_SIDED_LONG_EDGE;
1556                 } else if (attribClass.getStringValue().endsWith(
1557                                                            "short-edge")) {
1558                     return Sides.TWO_SIDED_SHORT_EDGE;
1559                 }
1560             }
1561             return Sides.ONE_SIDED;
1562         } else if (category == PrinterResolution.class) {
1563              PrinterResolution[] supportedRes = getPrintResolutions();
1564              if ((supportedRes != null) && (supportedRes.length > 0)) {
1565                 return supportedRes[0];
1566              } else {
1567                  return new PrinterResolution(300, 300, PrinterResolution.DPI);
1568              }
1569         }
1570 
1571         return null;
1572     }
1573 
1574     private PrinterResolution[] getPrintResolutions() {
1575         if (printerResolutions == null) {
1576             if (rawResolutions == null) {
1577               printerResolutions = new PrinterResolution[0];
1578             } else {
1579                 int numRes = rawResolutions.length / 2;
1580                 PrinterResolution[] pres = new PrinterResolution[numRes];
1581                 for (int i=0; i < numRes; i++) {
1582                     pres[i] =  new PrinterResolution(rawResolutions[i*2],
1583                                                      rawResolutions[i*2+1],
1584                                                      PrinterResolution.DPI);
1585                 }
1586                 printerResolutions = pres;
1587             }
1588         }
1589         return printerResolutions;
1590     }
1591 
1592     private boolean isSupportedResolution(PrinterResolution res) {
1593         PrinterResolution[] supportedRes = getPrintResolutions();
1594         if (supportedRes != null) {
1595             for (int i=0; i<supportedRes.length; i++) {
1596                 if (res.equals(supportedRes[i])) {
1597                     return true;
1598                 }
1599             }
1600         }
1601         return false;
1602     }
1603 
1604     public ServiceUIFactory getServiceUIFactory() {
1605         return null;
1606     }
1607 
1608     public void wakeNotifier() {
1609         synchronized (this) {
1610             if (notifier != null) {
1611                 notifier.wake();
1612             }
1613         }
1614     }
1615 
1616     public void addPrintServiceAttributeListener(
1617                                  PrintServiceAttributeListener listener) {
1618         synchronized (this) {
1619             if (listener == null) {
1620                 return;
1621             }
1622             if (notifier == null) {
1623                 notifier = new ServiceNotifier(this);
1624             }
1625             notifier.addListener(listener);
1626         }
1627     }
1628 
1629     public void removePrintServiceAttributeListener(
1630                                   PrintServiceAttributeListener listener) {
1631         synchronized (this) {
1632             if (listener == null || notifier == null ) {
1633                 return;
1634             }
1635             notifier.removeListener(listener);
1636             if (notifier.isEmpty()) {
1637                 notifier.stopNotifier();
1638                 notifier = null;
1639             }
1640         }
1641     }
1642 
1643     String getDest() {
1644         return printer;
1645     }
1646 
1647     public String getName() {
1648         /*
1649          * Mac is using printer-info IPP attribute for its human-readable printer
1650          * name and is also the identifier used in NSPrintInfo:setPrinter.
1651          */
1652         if (PrintServiceLookupProvider.isMac()) {
1653             PrintServiceAttributeSet psaSet = this.getAttributes();
1654             if (psaSet != null) {
1655                 PrinterInfo pName = (PrinterInfo)psaSet.get(PrinterInfo.class);
1656                 if (pName != null) {
1657                     return pName.toString();
1658                 }
1659             }
1660         }
1661         return printer;
1662     }
1663 
1664 
1665     public boolean usesClass(Class<?> c) {
1666         return (c == sun.print.PSPrinterJob.class);
1667     }
1668 
1669 
1670     public static HttpURLConnection getIPPConnection(URL url) {
1671         HttpURLConnection connection;
1672         URLConnection urlc;
1673         try {
1674             urlc = url.openConnection();
1675         } catch (java.io.IOException ioe) {
1676             return null;
1677         }
1678         if (!(urlc instanceof HttpURLConnection)) {
1679             return null;
1680         }
1681         connection = (HttpURLConnection)urlc;
1682         connection.setUseCaches(false);
1683         connection.setDefaultUseCaches(false);
1684         connection.setDoInput(true);
1685         connection.setDoOutput(true);
1686         connection.setRequestProperty("Content-type", "application/ipp");
1687         return connection;
1688     }
1689 
1690 
1691     public synchronized boolean isPostscript() {
1692         if (isPS == null) {
1693            isPS = Boolean.TRUE;
1694             if (isCupsPrinter) {
1695                 try {
1696                     urlConnection = getIPPConnection(
1697                                              new URL(myURL+".ppd"));
1698 
1699                    InputStream is = urlConnection.getInputStream();
1700                    if (is != null) {
1701                        BufferedReader d =
1702                            new BufferedReader(new InputStreamReader(is,
1703                                                           Charset.forName("ISO-8859-1")));
1704                        String lineStr;
1705                        while ((lineStr = d.readLine()) != null) {
1706                            if (lineStr.startsWith("*cupsFilter:")) {
1707                                isPS = Boolean.FALSE;
1708                                break;
1709                            }
1710                        }
1711                     }
1712                 } catch (java.io.IOException e) {
1713                     debug_println(" isPostscript, e= "+e);
1714                     /* if PPD is not found, this may be a raw printer
1715                        and in this case it is assumed that it is a
1716                        Postscript printer */
1717                     // do nothing
1718                 }
1719             }
1720         }
1721         return isPS.booleanValue();
1722     }
1723 
1724 
1725     private void opGetAttributes() {
1726         try {
1727             debug_println(debugPrefix+"opGetAttributes myURI "+myURI+" myURL "+myURL);
1728 
1729             AttributeClass attClNoUri[] = {
1730                 AttributeClass.ATTRIBUTES_CHARSET,
1731                 AttributeClass.ATTRIBUTES_NATURAL_LANGUAGE};
1732 
1733             AttributeClass attCl[] = {
1734                 AttributeClass.ATTRIBUTES_CHARSET,
1735                 AttributeClass.ATTRIBUTES_NATURAL_LANGUAGE,
1736                 new AttributeClass("printer-uri",
1737                                    AttributeClass.TAG_URI,
1738                                    ""+myURI)};
1739 
1740             OutputStream os = java.security.AccessController.
1741                 doPrivileged(new java.security.PrivilegedAction<OutputStream>() {
1742                     public OutputStream run() {
1743                         try {
1744                             return urlConnection.getOutputStream();
1745                         } catch (Exception e) {
1746                         }
1747                         return null;
1748                     }
1749                 });
1750 
1751             if (os == null) {
1752                 return;
1753             }
1754 
1755             boolean success = (myURI == null) ?
1756                 writeIPPRequest(os, OP_GET_ATTRIBUTES, attClNoUri) :
1757                 writeIPPRequest(os, OP_GET_ATTRIBUTES, attCl);
1758             if (success) {
1759                 InputStream is = null;                
1760                 if ((is = urlConnection.getInputStream())!=null) {
1761                     HashMap<String, AttributeClass>[] responseMap = readIPPResponse(is);
1762 
1763                     if (responseMap != null && responseMap.length > 0) {
1764                         getAttMap = responseMap[0];
1765                     }
1766                 } else {
1767                     debug_println(debugPrefix+"opGetAttributes - null input stream");
1768                 }
1769                 is.close();
1770             }
1771             os.close();
1772         } catch (java.io.IOException e) {
1773             debug_println(debugPrefix+"opGetAttributes - input/output stream: "+e);
1774         }
1775     }
1776 
1777 
1778     public static boolean writeIPPRequest(OutputStream os,
1779                                            String operCode,
1780                                            AttributeClass[] attCl) {
1781         OutputStreamWriter osw;
1782         try {
1783             osw = new OutputStreamWriter(os, "UTF-8");
1784         } catch (java.io.UnsupportedEncodingException exc) {
1785             debug_println(debugPrefix+"writeIPPRequest, UTF-8 not supported? Exception: "+exc);
1786             return false;
1787         }
1788         debug_println(debugPrefix+"writeIPPRequest, op code= "+operCode);
1789         char[] opCode =  new char[2];
1790         opCode[0] =  (char)Byte.parseByte(operCode.substring(0,2), 16);
1791         opCode[1] =  (char)Byte.parseByte(operCode.substring(2,4), 16);
1792         char[] bytes = {0x01, 0x01, 0x00, 0x01};
1793         try {
1794             osw.write(bytes, 0, 2); // version number
1795             osw.write(opCode, 0, 2); // operation code
1796             bytes[0] = 0x00; bytes[1] = 0x00;
1797             osw.write(bytes, 0, 4); // request ID #1
1798 
1799             bytes[0] = 0x01; // operation-group-tag
1800             osw.write(bytes[0]);
1801 
1802             String valStr;
1803             char[] lenStr;
1804 
1805             AttributeClass ac;
1806             for (int i=0; i < attCl.length; i++) {
1807                 ac = attCl[i];
1808                 osw.write(ac.getType()); // value tag
1809 
1810                 lenStr = ac.getLenChars();
1811                 osw.write(lenStr, 0, 2); // length
1812                 osw.write(""+ac, 0, ac.getName().length());
1813 
1814                 // check if string range (0x35 -> 0x49)
1815                 if (ac.getType() >= AttributeClass.TAG_TEXT_LANGUAGE &&
1816                     ac.getType() <= AttributeClass.TAG_MIME_MEDIATYPE){
1817                     valStr = (String)ac.getObjectValue();
1818                     bytes[0] = 0; bytes[1] = (char)valStr.length();
1819                     osw.write(bytes, 0, 2);
1820                     osw.write(valStr, 0, valStr.length());
1821                 } // REMIND: need to support other value tags but for CUPS
1822                 // string is all we need.
1823             }
1824 
1825             osw.write(GRPTAG_END_ATTRIBUTES);
1826             osw.flush();
1827             osw.close();
1828         } catch (java.io.IOException ioe) {
1829             debug_println(debugPrefix+"writeIPPRequest, IPPPrintService Exception in writeIPPRequest: "+ioe);
1830             return false;
1831         }
1832         return true;
1833     }
1834 
1835 
1836     public static HashMap<String, AttributeClass>[] readIPPResponse(InputStream inputStream) {
1837 
1838         if (inputStream == null) {
1839             return null;
1840         }
1841 
1842         byte response[] = new byte[MAX_ATTRIBUTE_LENGTH];
1843         try {
1844 
1845             DataInputStream ois = new DataInputStream(inputStream);
1846 
1847             // read status and ID
1848             if ((ois.read(response, 0, 8) > -1) &&
1849                 (response[2] == STATUSCODE_SUCCESS)) {
1850 
1851                 ByteArrayOutputStream outObj;
1852                 int counter=0;
1853                 short len = 0;
1854                 String attribStr = null;
1855                 // assign default value
1856                 byte valTagByte = AttributeClass.TAG_KEYWORD;
1857                 ArrayList<HashMap<String, AttributeClass>> respList = new ArrayList<>();
1858                 HashMap<String, AttributeClass> responseMap = new HashMap<>();
1859 
1860                 response[0] = ois.readByte();
1861 
1862                 // check for group tags
1863                 while ((response[0] >= GRPTAG_OP_ATTRIBUTES) &&
1864                        (response[0] <= GRPTAG_PRINTER_ATTRIBUTES)
1865                           && (response[0] != GRPTAG_END_ATTRIBUTES)) {
1866                     debug_println(debugPrefix+"readIPPResponse, checking group tag,  response[0]= "+
1867                                   response[0]);
1868 
1869                     outObj = new ByteArrayOutputStream();
1870                     //make sure counter and attribStr are re-initialized
1871                     counter = 0;
1872                     attribStr = null;
1873 
1874                     // read value tag
1875                     response[0] = ois.readByte();
1876                     while (response[0] >= AttributeClass.TAG_UNSUPPORTED_VALUE &&
1877                            response[0] <= AttributeClass.TAG_MEMBER_ATTRNAME) {
1878                         // read name length
1879                         len  = ois.readShort();
1880 
1881                         // If current value is not part of previous attribute
1882                         // then close stream and add it to HashMap.
1883                         // It is part of previous attribute if name length=0.
1884                         if ((len != 0) && (attribStr != null)) {
1885                             //last byte is the total # of values
1886                             outObj.write(counter);
1887                             outObj.flush();
1888                             outObj.close();
1889                             byte outArray[] = outObj.toByteArray();
1890 
1891                             // if key exists, new HashMap
1892                             if (responseMap.containsKey(attribStr)) {
1893                                 respList.add(responseMap);
1894                                 responseMap = new HashMap<>();
1895                             }
1896 
1897                             // exclude those that are unknown
1898                             if (valTagByte >= AttributeClass.TAG_INT) {
1899                                 AttributeClass ac =
1900                                     new AttributeClass(attribStr,
1901                                                        valTagByte,
1902                                                        outArray);
1903 
1904                                 responseMap.put(ac.getName(), ac);
1905                                 debug_println(debugPrefix+ "readIPPResponse "+ac);
1906                             }
1907 
1908                             outObj = new ByteArrayOutputStream();
1909                             counter = 0; //reset counter
1910                         }
1911                         //check if this is new value tag
1912                         if (counter == 0) {
1913                             valTagByte = response[0];
1914                         }
1915                         // read attribute name
1916                         if (len != 0) {
1917                             // read "len" characters
1918                             // make sure it doesn't exceed the maximum
1919                             if (len > MAX_ATTRIBUTE_LENGTH) {
1920                                 response = new byte[len]; // expand as needed
1921                             }
1922                             ois.read(response, 0, len);
1923                             attribStr = new String(response, 0, len);
1924                         }
1925                         // read value length
1926                         len  = ois.readShort();
1927                         // write name length
1928                         outObj.write(len);
1929                         // read value, make sure it doesn't exceed the maximum
1930                         if (len > MAX_ATTRIBUTE_LENGTH) {
1931                             response = new byte[len]; // expand as needed
1932                         }
1933                         ois.read(response, 0, len);
1934                         // write value of "len" length
1935                         outObj.write(response, 0, len);
1936                         counter++;
1937                         // read next byte
1938                         response[0] = ois.readByte();
1939                     }
1940 
1941                     if (attribStr != null) {
1942                         outObj.write(counter);
1943                         outObj.flush();
1944                         outObj.close();
1945 
1946                         // if key exists in old HashMap, new HashMap
1947                         if ((counter != 0) &&
1948                             responseMap.containsKey(attribStr)) {
1949                             respList.add(responseMap);
1950                             responseMap = new HashMap<>();
1951                         }
1952 
1953                         byte outArray[] = outObj.toByteArray();
1954 
1955                         AttributeClass ac =
1956                             new AttributeClass(attribStr,
1957                                                valTagByte,
1958                                                outArray);
1959                         responseMap.put(ac.getName(), ac);
1960                     }
1961                 }
1962                 ois.close();
1963                 if ((responseMap != null) && (responseMap.size() > 0)) {
1964                     respList.add(responseMap);
1965                 }
1966                 @SuppressWarnings({"unchecked", "rawtypes"})
1967                 HashMap<String, AttributeClass>[] tmp  =
1968                     respList.toArray((HashMap<String, AttributeClass>[])new HashMap[respList.size()]);
1969                 return tmp;
1970             } else {
1971                 debug_println(debugPrefix+
1972                           "readIPPResponse client error, IPP status code: 0x"+
1973                           toHex(response[2]) + toHex(response[3]));
1974                 return null;
1975             }
1976 
1977         } catch (java.io.IOException e) {
1978             debug_println(debugPrefix+"readIPPResponse: "+e);
1979             if (debugPrint) {
1980                 e.printStackTrace();
1981             }
1982             return null;
1983         }
1984     }
1985 
1986     private static String toHex(byte v) {
1987         String s = Integer.toHexString(v&0xff);
1988         return (s.length() == 2) ? s :  "0"+s;
1989     }
1990 
1991     public String toString() {
1992         return "IPP Printer : " + getName();
1993     }
1994 
1995     public boolean equals(Object obj) {
1996         return  (obj == this ||
1997                  (obj instanceof IPPPrintService &&
1998                   ((IPPPrintService)obj).getName().equals(getName())));
1999     }
2000 
2001     public int hashCode() {
2002         return this.getClass().hashCode()+getName().hashCode();
2003     }
2004 }