1 /*
   2  * Copyright (c) 2003, 2017, 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 package java.util.jar;
  26 
  27 import java.util.SortedMap;
  28 import java.io.InputStream;
  29 import java.io.OutputStream;
  30 import java.io.File;
  31 import java.io.IOException;
  32 import sun.security.action.GetPropertyAction;
  33 
  34 
  35 /**
  36  * Transforms a JAR file to or from a packed stream in Pack200 format.
  37  * Please refer to <a href="{@docRoot}/../specs/pack-spec.html">Network Transfer Format JSR 200 Specification</a>
  38  * <p>
  39  * Typically the packer engine is used by application developers
  40  * to deploy or host JAR files on a website.
  41  * The unpacker  engine is used by deployment applications to
  42  * transform the byte-stream back to JAR format.
  43  * <p>
  44  * Here is an example using  packer and unpacker:
  45  * <pre>{@code
  46  *    import java.util.jar.Pack200;
  47  *    import java.util.jar.Pack200.*;
  48  *    ...
  49  *    // Create the Packer object
  50  *    Packer packer = Pack200.newPacker();
  51  *
  52  *    // Initialize the state by setting the desired properties
  53  *    Map p = packer.properties();
  54  *    // take more time choosing codings for better compression
  55  *    p.put(Packer.EFFORT, "7");  // default is "5"
  56  *    // use largest-possible archive segments (>10% better compression).
  57  *    p.put(Packer.SEGMENT_LIMIT, "-1");
  58  *    // reorder files for better compression.
  59  *    p.put(Packer.KEEP_FILE_ORDER, Packer.FALSE);
  60  *    // smear modification times to a single value.
  61  *    p.put(Packer.MODIFICATION_TIME, Packer.LATEST);
  62  *    // ignore all JAR deflation requests,
  63  *    // transmitting a single request to use "store" mode.
  64  *    p.put(Packer.DEFLATE_HINT, Packer.FALSE);
  65  *    // discard debug attributes
  66  *    p.put(Packer.CODE_ATTRIBUTE_PFX+"LineNumberTable", Packer.STRIP);
  67  *    // throw an error if an attribute is unrecognized
  68  *    p.put(Packer.UNKNOWN_ATTRIBUTE, Packer.ERROR);
  69  *    // pass one class file uncompressed:
  70  *    p.put(Packer.PASS_FILE_PFX+0, "mutants/Rogue.class");
  71  *    try {
  72  *        JarFile jarFile = new JarFile("/tmp/testref.jar");
  73  *        FileOutputStream fos = new FileOutputStream("/tmp/test.pack");
  74  *        // Call the packer
  75  *        packer.pack(jarFile, fos);
  76  *        jarFile.close();
  77  *        fos.close();
  78  *
  79  *        File f = new File("/tmp/test.pack");
  80  *        FileOutputStream fostream = new FileOutputStream("/tmp/test.jar");
  81  *        JarOutputStream jostream = new JarOutputStream(fostream);
  82  *        Unpacker unpacker = Pack200.newUnpacker();
  83  *        // Call the unpacker
  84  *        unpacker.unpack(f, jostream);
  85  *        // Must explicitly close the output.
  86  *        jostream.close();
  87  *    } catch (IOException ioe) {
  88  *        ioe.printStackTrace();
  89  *    }
  90  * }</pre>
  91  * <p>
  92  * A Pack200 file compressed with gzip can be hosted on HTTP/1.1 web servers.
  93  * The deployment applications can use "Accept-Encoding=pack200-gzip". This
  94  * indicates to the server that the client application desires a version of
  95  * the file encoded with Pack200 and further compressed with gzip. Please
  96  * refer to the Java Deployment Guide for techniques and details.
  97  * <p>
  98  * Unless otherwise noted, passing a {@code null} argument to a constructor or
  99  * method in this class will cause a {@link NullPointerException} to be thrown.
 100  *
 101  * @author John Rose
 102  * @author Kumar Srinivasan
 103  * @since 1.5
 104  */
 105 public abstract class Pack200 {
 106     private Pack200() {} //prevent instantiation
 107 
 108     // Static methods of the Pack200 class.
 109     /**
 110      * Obtain new instance of a class that implements Packer.
 111      * <ul>
 112      * <li><p>If the system property {@code java.util.jar.Pack200.Packer}
 113      * is defined, then the value is taken to be the fully-qualified name
 114      * of a concrete implementation class, which must implement Packer.
 115      * This class is loaded and instantiated.  If this process fails
 116      * then an unspecified error is thrown.</p></li>
 117      *
 118      * <li><p>If an implementation has not been specified with the system
 119      * property, then the system-default implementation class is instantiated,
 120      * and the result is returned.</p></li>
 121      * </ul>
 122      *
 123      * <p>Note:  The returned object is not guaranteed to operate
 124      * correctly if multiple threads use it at the same time.
 125      * A multi-threaded application should either allocate multiple
 126      * packer engines, or else serialize use of one engine with a lock.
 127      *
 128      * @return  A newly allocated Packer engine.
 129      */
 130     public static synchronized Packer newPacker() {
 131         return (Packer) newInstance(PACK_PROVIDER);
 132     }
 133 
 134 
 135     /**
 136      * Obtain new instance of a class that implements Unpacker.
 137      * <ul>
 138      * <li><p>If the system property {@code java.util.jar.Pack200.Unpacker}
 139      * is defined, then the value is taken to be the fully-qualified
 140      * name of a concrete implementation class, which must implement Unpacker.
 141      * The class is loaded and instantiated.  If this process fails
 142      * then an unspecified error is thrown.</p></li>
 143      *
 144      * <li><p>If an implementation has not been specified with the
 145      * system property, then the system-default implementation class
 146      * is instantiated, and the result is returned.</p></li>
 147      * </ul>
 148      *
 149      * <p>Note:  The returned object is not guaranteed to operate
 150      * correctly if multiple threads use it at the same time.
 151      * A multi-threaded application should either allocate multiple
 152      * unpacker engines, or else serialize use of one engine with a lock.
 153      *
 154      * @return  A newly allocated Unpacker engine.
 155      */
 156 
 157     public static Unpacker newUnpacker() {
 158         return (Unpacker) newInstance(UNPACK_PROVIDER);
 159     }
 160 
 161     // Interfaces
 162     /**
 163      * The packer engine applies various transformations to the input JAR file,
 164      * making the pack stream highly compressible by a compressor such as
 165      * gzip or zip. An instance of the engine can be obtained
 166      * using {@link #newPacker}.
 167 
 168      * The high degree of compression is achieved
 169      * by using a number of techniques described in the JSR 200 specification.
 170      * Some of the techniques are sorting, re-ordering and co-location of the
 171      * constant pool.
 172      * <p>
 173      * The pack engine is initialized to an initial state as described
 174      * by their properties below.
 175      * The initial state can be manipulated by getting the
 176      * engine properties (using {@link #properties}) and storing
 177      * the modified properties on the map.
 178      * The resource files will be passed through with no changes at all.
 179      * The class files will not contain identical bytes, since the unpacker
 180      * is free to change minor class file features such as constant pool order.
 181      * However, the class files will be semantically identical,
 182      * as specified in
 183      * <cite>The Java&trade; Virtual Machine Specification</cite>.
 184      * <p>
 185      * By default, the packer does not change the order of JAR elements.
 186      * Also, the modification time and deflation hint of each
 187      * JAR element is passed unchanged.
 188      * (Any other ZIP-archive information, such as extra attributes
 189      * giving Unix file permissions, are lost.)
 190      * <p>
 191      * Note that packing and unpacking a JAR will in general alter the
 192      * bytewise contents of classfiles in the JAR.  This means that packing
 193      * and unpacking will in general invalidate any digital signatures
 194      * which rely on bytewise images of JAR elements.  In order both to sign
 195      * and to pack a JAR, you must first pack and unpack the JAR to
 196      * "normalize" it, then compute signatures on the unpacked JAR elements,
 197      * and finally repack the signed JAR.
 198      * Both packing steps should
 199      * use precisely the same options, and the segment limit may also
 200      * need to be set to "-1", to prevent accidental variation of segment
 201      * boundaries as class file sizes change slightly.
 202      * <p>
 203      * (Here's why this works:  Any reordering the packer does
 204      * of any classfile structures is idempotent, so the second packing
 205      * does not change the orderings produced by the first packing.
 206      * Also, the unpacker is guaranteed by the JSR 200 specification
 207      * to produce a specific bytewise image for any given transmission
 208      * ordering of archive elements.)
 209      * <p>
 210      * In order to maintain backward compatibility, the pack file's version is
 211      * set to accommodate the class files present in the input JAR file. In
 212      * other words, the pack file version will be the latest, if the class files
 213      * are the latest and conversely the pack file version will be the oldest
 214      * if the class file versions are also the oldest. For intermediate class
 215      * file versions the corresponding pack file version will be used.
 216      * For example:
 217      *    If the input JAR-files are solely comprised of 1.5  (or  lesser)
 218      * class files, a 1.5 compatible pack file is  produced. This will also be
 219      * the case for archives that have no class files.
 220      *    If the input JAR-files contains a 1.6 class file, then the pack file
 221      * version will be set to 1.6.
 222      * <p>
 223      * Note: Unless otherwise noted, passing a {@code null} argument to a
 224      * constructor or method in this class will cause a {@link NullPointerException}
 225      * to be thrown.
 226      *
 227      * @since 1.5
 228      */
 229     public interface Packer {
 230         /**
 231          * This property is a numeral giving the estimated target size N
 232          * (in bytes) of each archive segment.
 233          * If a single input file requires more than N bytes,
 234          * it will be given its own archive segment.
 235          * <p>
 236          * As a special case, a value of -1 will produce a single large
 237          * segment with all input files, while a value of 0 will
 238          * produce one segment for each class.
 239          * Larger archive segments result in less fragmentation and
 240          * better compression, but processing them requires more memory.
 241          * <p>
 242          * The size of each segment is estimated by counting the size of each
 243          * input file to be transmitted in the segment, along with the size
 244          * of its name and other transmitted properties.
 245          * <p>
 246          * The default is -1, which means the packer will always create a single
 247          * segment output file. In cases where extremely large output files are
 248          * generated, users are strongly encouraged to use segmenting or break
 249          * up the input file into smaller JARs.
 250          * <p>
 251          * A 10Mb JAR packed without this limit will
 252          * typically pack about 10% smaller, but the packer may require
 253          * a larger Java heap (about ten times the segment limit).
 254          */
 255         String SEGMENT_LIMIT    = "pack.segment.limit";
 256 
 257         /**
 258          * If this property is set to {@link #TRUE}, the packer will transmit
 259          * all elements in their original order within the source archive.
 260          * <p>
 261          * If it is set to {@link #FALSE}, the packer may reorder elements,
 262          * and also remove JAR directory entries, which carry no useful
 263          * information for Java applications.
 264          * (Typically this enables better compression.)
 265          * <p>
 266          * The default is {@link #TRUE}, which preserves the input information,
 267          * but may cause the transmitted archive to be larger than necessary.
 268          */
 269         String KEEP_FILE_ORDER = "pack.keep.file.order";
 270 
 271 
 272         /**
 273          * If this property is set to a single decimal digit, the packer will
 274          * use the indicated amount of effort in compressing the archive.
 275          * Level 1 may produce somewhat larger size and faster compression speed,
 276          * while level 9 will take much longer but may produce better compression.
 277          * <p>
 278          * The special value 0 instructs the packer to copy through the
 279          * original JAR file directly, with no compression.  The JSR 200
 280          * standard requires any unpacker to understand this special case
 281          * as a pass-through of the entire archive.
 282          * <p>
 283          * The default is 5, investing a modest amount of time to
 284          * produce reasonable compression.
 285          */
 286         String EFFORT           = "pack.effort";
 287 
 288         /**
 289          * If this property is set to {@link #TRUE} or {@link #FALSE}, the packer
 290          * will set the deflation hint accordingly in the output archive, and
 291          * will not transmit the individual deflation hints of archive elements.
 292          * <p>
 293          * If this property is set to the special string {@link #KEEP}, the packer
 294          * will attempt to determine an independent deflation hint for each
 295          * available element of the input archive, and transmit this hint separately.
 296          * <p>
 297          * The default is {@link #KEEP}, which preserves the input information,
 298          * but may cause the transmitted archive to be larger than necessary.
 299          * <p>
 300          * It is up to the unpacker implementation
 301          * to take action upon the hint to suitably compress the elements of
 302          * the resulting unpacked jar.
 303          * <p>
 304          * The deflation hint of a ZIP or JAR element indicates
 305          * whether the element was deflated or stored directly.
 306          */
 307         String DEFLATE_HINT     = "pack.deflate.hint";
 308 
 309         /**
 310          * If this property is set to the special string {@link #LATEST},
 311          * the packer will attempt to determine the latest modification time,
 312          * among all the available entries in the original archive or the latest
 313          * modification time of all the available entries in each segment.
 314          * This single value will be transmitted as part of the segment and applied
 315          * to all the entries in each segment, {@link #SEGMENT_LIMIT}.
 316          * <p>
 317          * This can marginally decrease the transmitted size of the
 318          * archive, at the expense of setting all installed files to a single
 319          * date.
 320          * <p>
 321          * If this property is set to the special string {@link #KEEP},
 322          * the packer transmits a separate modification time for each input
 323          * element.
 324          * <p>
 325          * The default is {@link #KEEP}, which preserves the input information,
 326          * but may cause the transmitted archive to be larger than necessary.
 327          * <p>
 328          * It is up to the unpacker implementation to take action to suitably
 329          * set the modification time of each element of its output file.
 330          * @see #SEGMENT_LIMIT
 331          */
 332         String MODIFICATION_TIME        = "pack.modification.time";
 333 
 334         /**
 335          * Indicates that a file should be passed through bytewise, with no
 336          * compression.  Multiple files may be specified by specifying
 337          * additional properties with distinct strings appended, to
 338          * make a family of properties with the common prefix.
 339          * <p>
 340          * There is no pathname transformation, except
 341          * that the system file separator is replaced by the JAR file
 342          * separator '/'.
 343          * <p>
 344          * The resulting file names must match exactly as strings with their
 345          * occurrences in the JAR file.
 346          * <p>
 347          * If a property value is a directory name, all files under that
 348          * directory will be passed also.
 349          * <p>
 350          * Examples:
 351          * <pre>{@code
 352          *     Map p = packer.properties();
 353          *     p.put(PASS_FILE_PFX+0, "mutants/Rogue.class");
 354          *     p.put(PASS_FILE_PFX+1, "mutants/Wolverine.class");
 355          *     p.put(PASS_FILE_PFX+2, "mutants/Storm.class");
 356          *     # Pass all files in an entire directory hierarchy:
 357          *     p.put(PASS_FILE_PFX+3, "police/");
 358          * }</pre>
 359          */
 360         String PASS_FILE_PFX            = "pack.pass.file.";
 361 
 362         /// Attribute control.
 363 
 364         /**
 365          * Indicates the action to take when a class-file containing an unknown
 366          * attribute is encountered.  Possible values are the strings {@link #ERROR},
 367          * {@link #STRIP}, and {@link #PASS}.
 368          * <p>
 369          * The string {@link #ERROR} means that the pack operation
 370          * as a whole will fail, with an exception of type {@code IOException}.
 371          * The string
 372          * {@link #STRIP} means that the attribute will be dropped.
 373          * The string
 374          * {@link #PASS} means that the whole class-file will be passed through
 375          * (as if it were a resource file) without compression, with  a suitable warning.
 376          * This is the default value for this property.
 377          * <p>
 378          * Examples:
 379          * <pre>{@code
 380          *     Map p = pack200.getProperties();
 381          *     p.put(UNKNOWN_ATTRIBUTE, ERROR);
 382          *     p.put(UNKNOWN_ATTRIBUTE, STRIP);
 383          *     p.put(UNKNOWN_ATTRIBUTE, PASS);
 384          * }</pre>
 385          */
 386         String UNKNOWN_ATTRIBUTE        = "pack.unknown.attribute";
 387 
 388         /**
 389          * When concatenated with a class attribute name,
 390          * indicates the format of that attribute,
 391          * using the layout language specified in the JSR 200 specification.
 392          * <p>
 393          * For example, the effect of this option is built in:
 394          * {@code pack.class.attribute.SourceFile=RUH}.
 395          * <p>
 396          * The special strings {@link #ERROR}, {@link #STRIP}, and {@link #PASS} are
 397          * also allowed, with the same meaning as {@link #UNKNOWN_ATTRIBUTE}.
 398          * This provides a way for users to request that specific attributes be
 399          * refused, stripped, or passed bitwise (with no class compression).
 400          * <p>
 401          * Code like this might be used to support attributes for JCOV:
 402          * <pre>{@code
 403          *     Map p = packer.properties();
 404          *     p.put(CODE_ATTRIBUTE_PFX+"CoverageTable",       "NH[PHHII]");
 405          *     p.put(CODE_ATTRIBUTE_PFX+"CharacterRangeTable", "NH[PHPOHIIH]");
 406          *     p.put(CLASS_ATTRIBUTE_PFX+"SourceID",           "RUH");
 407          *     p.put(CLASS_ATTRIBUTE_PFX+"CompilationID",      "RUH");
 408          * }</pre>
 409          * <p>
 410          * Code like this might be used to strip debugging attributes:
 411          * <pre>{@code
 412          *     Map p = packer.properties();
 413          *     p.put(CODE_ATTRIBUTE_PFX+"LineNumberTable",    STRIP);
 414          *     p.put(CODE_ATTRIBUTE_PFX+"LocalVariableTable", STRIP);
 415          *     p.put(CLASS_ATTRIBUTE_PFX+"SourceFile",        STRIP);
 416          * }</pre>
 417          */
 418         String CLASS_ATTRIBUTE_PFX      = "pack.class.attribute.";
 419 
 420         /**
 421          * When concatenated with a field attribute name,
 422          * indicates the format of that attribute.
 423          * For example, the effect of this option is built in:
 424          * {@code pack.field.attribute.Deprecated=}.
 425          * The special strings {@link #ERROR}, {@link #STRIP}, and
 426          * {@link #PASS} are also allowed.
 427          * @see #CLASS_ATTRIBUTE_PFX
 428          */
 429         String FIELD_ATTRIBUTE_PFX      = "pack.field.attribute.";
 430 
 431         /**
 432          * When concatenated with a method attribute name,
 433          * indicates the format of that attribute.
 434          * For example, the effect of this option is built in:
 435          * {@code pack.method.attribute.Exceptions=NH[RCH]}.
 436          * The special strings {@link #ERROR}, {@link #STRIP}, and {@link #PASS}
 437          * are also allowed.
 438          * @see #CLASS_ATTRIBUTE_PFX
 439          */
 440         String METHOD_ATTRIBUTE_PFX     = "pack.method.attribute.";
 441 
 442         /**
 443          * When concatenated with a code attribute name,
 444          * indicates the format of that attribute.
 445          * For example, the effect of this option is built in:
 446          * {@code pack.code.attribute.LocalVariableTable=NH[PHOHRUHRSHH]}.
 447          * The special strings {@link #ERROR}, {@link #STRIP}, and {@link #PASS}
 448          * are also allowed.
 449          * @see #CLASS_ATTRIBUTE_PFX
 450          */
 451         String CODE_ATTRIBUTE_PFX       = "pack.code.attribute.";
 452 
 453         /**
 454          * The packer's progress as a percentage, as periodically
 455          * updated by the packer.
 456          * Values of 0 - 100 are normal, and -1 indicates a stall.
 457          * Progress can be monitored by polling the value of this
 458          * property.
 459          * <p>
 460          * At a minimum, the packer must set progress to 0
 461          * at the beginning of a packing operation, and to 100
 462          * at the end.
 463          */
 464         String PROGRESS                 = "pack.progress";
 465 
 466         /** The string "keep", a possible value for certain properties.
 467          * @see #DEFLATE_HINT
 468          * @see #MODIFICATION_TIME
 469          */
 470         String KEEP  = "keep";
 471 
 472         /** The string "pass", a possible value for certain properties.
 473          * @see #UNKNOWN_ATTRIBUTE
 474          * @see #CLASS_ATTRIBUTE_PFX
 475          * @see #FIELD_ATTRIBUTE_PFX
 476          * @see #METHOD_ATTRIBUTE_PFX
 477          * @see #CODE_ATTRIBUTE_PFX
 478          */
 479         String PASS  = "pass";
 480 
 481         /** The string "strip", a possible value for certain properties.
 482          * @see #UNKNOWN_ATTRIBUTE
 483          * @see #CLASS_ATTRIBUTE_PFX
 484          * @see #FIELD_ATTRIBUTE_PFX
 485          * @see #METHOD_ATTRIBUTE_PFX
 486          * @see #CODE_ATTRIBUTE_PFX
 487          */
 488         String STRIP = "strip";
 489 
 490         /** The string "error", a possible value for certain properties.
 491          * @see #UNKNOWN_ATTRIBUTE
 492          * @see #CLASS_ATTRIBUTE_PFX
 493          * @see #FIELD_ATTRIBUTE_PFX
 494          * @see #METHOD_ATTRIBUTE_PFX
 495          * @see #CODE_ATTRIBUTE_PFX
 496          */
 497         String ERROR = "error";
 498 
 499         /** The string "true", a possible value for certain properties.
 500          * @see #KEEP_FILE_ORDER
 501          * @see #DEFLATE_HINT
 502          */
 503         String TRUE = "true";
 504 
 505         /** The string "false", a possible value for certain properties.
 506          * @see #KEEP_FILE_ORDER
 507          * @see #DEFLATE_HINT
 508          */
 509         String FALSE = "false";
 510 
 511         /** The string "latest", a possible value for certain properties.
 512          * @see #MODIFICATION_TIME
 513          */
 514         String LATEST = "latest";
 515 
 516         /**
 517          * Get the set of this engine's properties.
 518          * This set is a "live view", so that changing its
 519          * contents immediately affects the Packer engine, and
 520          * changes from the engine (such as progress indications)
 521          * are immediately visible in the map.
 522          *
 523          * <p>The property map may contain pre-defined implementation
 524          * specific and default properties.  Users are encouraged to
 525          * read the information and fully understand the implications,
 526          * before modifying pre-existing properties.
 527          * <p>
 528          * Implementation specific properties are prefixed with a
 529          * package name associated with the implementor, beginning
 530          * with {@code com.} or a similar prefix.
 531          * All property names beginning with {@code pack.} and
 532          * {@code unpack.} are reserved for use by this API.
 533          * <p>
 534          * Unknown properties may be ignored or rejected with an
 535          * unspecified error, and invalid entries may cause an
 536          * unspecified error to be thrown.
 537          *
 538          * <p>
 539          * The returned map implements all optional {@link SortedMap} operations
 540          * @return A sorted association of property key strings to property
 541          * values.
 542          */
 543         SortedMap<String,String> properties();
 544 
 545         /**
 546          * Takes a JarFile and converts it into a Pack200 archive.
 547          * <p>
 548          * Closes its input but not its output.  (Pack200 archives are appendable.)
 549          * @param in a JarFile
 550          * @param out an OutputStream
 551          * @exception IOException if an error is encountered.
 552          */
 553         void pack(JarFile in, OutputStream out) throws IOException ;
 554 
 555         /**
 556          * Takes a JarInputStream and converts it into a Pack200 archive.
 557          * <p>
 558          * Closes its input but not its output.  (Pack200 archives are appendable.)
 559          * <p>
 560          * The modification time and deflation hint attributes are not available,
 561          * for the JAR manifest file and its containing directory.
 562          *
 563          * @see #MODIFICATION_TIME
 564          * @see #DEFLATE_HINT
 565          * @param in a JarInputStream
 566          * @param out an OutputStream
 567          * @exception IOException if an error is encountered.
 568          */
 569         void pack(JarInputStream in, OutputStream out) throws IOException ;
 570     }
 571 
 572     /**
 573      * The unpacker engine converts the packed stream to a JAR file.
 574      * An instance of the engine can be obtained
 575      * using {@link #newUnpacker}.
 576      * <p>
 577      * Every JAR file produced by this engine will include the string
 578      * "{@code PACK200}" as a zip file comment.
 579      * This allows a deployer to detect if a JAR archive was packed and unpacked.
 580      * <p>
 581      * Note: Unless otherwise noted, passing a {@code null} argument to a
 582      * constructor or method in this class will cause a {@link NullPointerException}
 583      * to be thrown.
 584      * <p>
 585      * This version of the unpacker is compatible with all previous versions.
 586      * @since 1.5
 587      */
 588     public interface Unpacker {
 589 
 590         /** The string "keep", a possible value for certain properties.
 591          * @see #DEFLATE_HINT
 592          */
 593         String KEEP  = "keep";
 594 
 595         /** The string "true", a possible value for certain properties.
 596          * @see #DEFLATE_HINT
 597          */
 598         String TRUE = "true";
 599 
 600         /** The string "false", a possible value for certain properties.
 601          * @see #DEFLATE_HINT
 602          */
 603         String FALSE = "false";
 604 
 605         /**
 606          * Property indicating that the unpacker should
 607          * ignore all transmitted values for DEFLATE_HINT,
 608          * replacing them by the given value, {@link #TRUE} or {@link #FALSE}.
 609          * The default value is the special string {@link #KEEP},
 610          * which asks the unpacker to preserve all transmitted
 611          * deflation hints.
 612          */
 613         String DEFLATE_HINT      = "unpack.deflate.hint";
 614 
 615 
 616 
 617         /**
 618          * The unpacker's progress as a percentage, as periodically
 619          * updated by the unpacker.
 620          * Values of 0 - 100 are normal, and -1 indicates a stall.
 621          * Progress can be monitored by polling the value of this
 622          * property.
 623          * <p>
 624          * At a minimum, the unpacker must set progress to 0
 625          * at the beginning of an unpacking operation, and to 100
 626          * at the end.
 627          */
 628         String PROGRESS         = "unpack.progress";
 629 
 630         /**
 631          * Get the set of this engine's properties. This set is
 632          * a "live view", so that changing its
 633          * contents immediately affects the Unpacker engine, and
 634          * changes from the engine (such as progress indications)
 635          * are immediately visible in the map.
 636          *
 637          * <p>The property map may contain pre-defined implementation
 638          * specific and default properties.  Users are encouraged to
 639          * read the information and fully understand the implications,
 640          * before modifying pre-existing properties.
 641          * <p>
 642          * Implementation specific properties are prefixed with a
 643          * package name associated with the implementor, beginning
 644          * with {@code com.} or a similar prefix.
 645          * All property names beginning with {@code pack.} and
 646          * {@code unpack.} are reserved for use by this API.
 647          * <p>
 648          * Unknown properties may be ignored or rejected with an
 649          * unspecified error, and invalid entries may cause an
 650          * unspecified error to be thrown.
 651          *
 652          * @return A sorted association of option key strings to option values.
 653          */
 654         SortedMap<String,String> properties();
 655 
 656         /**
 657          * Read a Pack200 archive, and write the encoded JAR to
 658          * a JarOutputStream.
 659          * The entire contents of the input stream will be read.
 660          * It may be more efficient to read the Pack200 archive
 661          * to a file and pass the File object, using the alternate
 662          * method described below.
 663          * <p>
 664          * Closes its input but not its output.  (The output can accumulate more elements.)
 665          * @param in an InputStream.
 666          * @param out a JarOutputStream.
 667          * @exception IOException if an error is encountered.
 668          */
 669         void unpack(InputStream in, JarOutputStream out) throws IOException;
 670 
 671         /**
 672          * Read a Pack200 archive, and write the encoded JAR to
 673          * a JarOutputStream.
 674          * <p>
 675          * Does not close its output.  (The output can accumulate more elements.)
 676          * @param in a File.
 677          * @param out a JarOutputStream.
 678          * @exception IOException if an error is encountered.
 679          */
 680         void unpack(File in, JarOutputStream out) throws IOException;
 681     }
 682 
 683     // Private stuff....
 684 
 685     private static final String PACK_PROVIDER = "java.util.jar.Pack200.Packer";
 686     private static final String UNPACK_PROVIDER = "java.util.jar.Pack200.Unpacker";
 687 
 688     private static Class<?> packerImpl;
 689     private static Class<?> unpackerImpl;
 690 
 691     private static synchronized Object newInstance(String prop) {
 692         String implName = "(unknown)";
 693         try {
 694             Class<?> impl = (PACK_PROVIDER.equals(prop))? packerImpl: unpackerImpl;
 695             if (impl == null) {
 696                 // The first time, we must decide which class to use.
 697                 implName = GetPropertyAction.privilegedGetProperty(prop,"");
 698                 if (implName != null && !implName.equals(""))
 699                     impl = Class.forName(implName);
 700                 else if (PACK_PROVIDER.equals(prop))
 701                     impl = com.sun.java.util.jar.pack.PackerImpl.class;
 702                 else
 703                     impl = com.sun.java.util.jar.pack.UnpackerImpl.class;
 704             }
 705             // We have a class.  Now instantiate it.
 706             @SuppressWarnings("deprecation")
 707             Object result = impl.newInstance();
 708             return result;
 709         } catch (ClassNotFoundException e) {
 710             throw new Error("Class not found: " + implName +
 711                                 ":\ncheck property " + prop +
 712                                 " in your properties file.", e);
 713         } catch (InstantiationException e) {
 714             throw new Error("Could not instantiate: " + implName +
 715                                 ":\ncheck property " + prop +
 716                                 " in your properties file.", e);
 717         } catch (IllegalAccessException e) {
 718             throw new Error("Cannot access class: " + implName +
 719                                 ":\ncheck property " + prop +
 720                                 " in your properties file.", e);
 721         }
 722     }
 723 
 724 }