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