Ejemplo n.º 1
0
  public DictionaryFile(File file) {
    super(file.getPath());
    type = DictionaryType.parse(file.getName());
    affName = type.isArchive() ? ZipUtil.containsFile(getPath(), ".aff") : getPath();
    if (affName != null) affName = new File(affName).getName();

    FileUtil.createFolder(getTempFolder());

    affFile = extractAffFile();
    if (affFile != null) {
      // Detect charset
      affReader.setChartSetReader(true);
      affReader.readFile(affFile, Charset.forName("UTF-8"));
      affReader.setChartSetReader(false);
    }

    dicName = type.isArchive() ? ZipUtil.containsFile(getPath(), ".dic") : getPath();
    if (dicName != null) dicName = new File(dicName).getName();
    dicFile = extractDicFile();
    dicReader.setAffReader(affReader);

    if (dicFile != null) {
      // Detect words count
      dicReader.setWordReader(true);
      dicReader.readFile(dicFile, getCharset());
      dicReader.setWordReader(false);
    }

    if (isValid()) laguageID = FileUtil.changeFileExt(dicName, "");
  }
Ejemplo n.º 2
0
 private void resolveLocalFileHeaderData(
     final Map<ZipEntry, NameAndComment> entriesWithoutUTF8Flag) throws IOException {
   for (final Entry ze : this.entries) {
     final OffsetEntry offsetEntry = ze.getOffsetEntry();
     final long offset = offsetEntry.headerOffset;
     this.archive.seek(offset + 26L);
     this.archive.readFully(this.SHORT_BUF);
     final int fileNameLen = ZipShort.getValue(this.SHORT_BUF);
     this.archive.readFully(this.SHORT_BUF);
     final int extraFieldLen = ZipShort.getValue(this.SHORT_BUF);
     int skipped;
     for (int lenToSkip = fileNameLen; lenToSkip > 0; lenToSkip -= skipped) {
       skipped = this.archive.skipBytes(lenToSkip);
       if (skipped <= 0) {
         throw new IOException("failed to skip file name in local file header");
       }
     }
     final byte[] localExtraData = new byte[extraFieldLen];
     this.archive.readFully(localExtraData);
     ze.setExtra(localExtraData);
     offsetEntry.dataOffset = offset + 26L + 2L + 2L + fileNameLen + extraFieldLen;
     if (entriesWithoutUTF8Flag.containsKey(ze)) {
       final NameAndComment nc = entriesWithoutUTF8Flag.get(ze);
       ZipUtil.setNameAndCommentFromExtraFields(ze, nc.name, nc.comment);
     }
     final String name = ze.getName();
     LinkedList<ZipEntry> entriesOfThatName = this.nameMap.get(name);
     if (entriesOfThatName == null) {
       entriesOfThatName = new LinkedList<ZipEntry>();
       this.nameMap.put(name, entriesOfThatName);
     }
     entriesOfThatName.addLast(ze);
   }
 }
Ejemplo n.º 3
0
 public InputStream getInputStream(final ZipEntry ze) throws IOException, ZipException {
   if (!(ze instanceof Entry)) {
     return null;
   }
   final OffsetEntry offsetEntry = ((Entry) ze).getOffsetEntry();
   ZipUtil.checkRequestedFeatures(ze);
   final long start = offsetEntry.dataOffset;
   final BoundedInputStream bis = new BoundedInputStream(start, ze.getCompressedSize());
   switch (ze.getMethod()) {
     case 0:
       {
         return bis;
       }
     case 8:
       {
         bis.addDummy();
         final Inflater inflater = new Inflater(true);
         return new InflaterInputStream(bis, inflater) {
           public void close() throws IOException {
             super.close();
             inflater.end();
           }
         };
       }
     default:
       {
         throw new ZipException("Found unsupported compression method " + ze.getMethod());
       }
   }
 }
Ejemplo n.º 4
0
  public static Map<String, String> readManifest(final File location) throws IOException {

    if (location.isFile()) {
      final ZipFile zip = ZipUtil.open(location);

      try {
        return readManifest(zip);
      } finally {
        try {
          zip.close();
        } catch (IOException e) {
        }
      }
    } else {
      final File manifestFile = new File(location, MANIFEST_PATH);

      if (manifestFile.exists()) {
        final InputStream in = new FileInputStream(manifestFile);

        try {
          return readManifest(new BufferedInputStream(in));
        } finally {
          try {
            in.close();
          } catch (IOException e) {
          }
        }
      } else {
        return Collections.emptyMap();
      }
    }
  }
Ejemplo n.º 5
0
  /**
   * Install an extension directly into profile location
   *
   * @param extensionURL
   * @param extensionID
   * @param dir
   * @return boolean
   */
  public static boolean installExtension(URL extensionURL, String extensionID, File dir) {
    dir = new File(dir, extensionID);
    if (dir.exists()) {
      return true;
    }
    if (!dir.mkdirs()) {
      return false;
    }

    File file = null;
    InputStream in = null;
    FileOutputStream out = null;
    try {
      file = File.createTempFile("ffe", ".zip"); // $NON-NLS-1$ //$NON-NLS-2$
      in = extensionURL.openStream();
      out = new FileOutputStream(file);
      byte[] buffer = new byte[0x1000];
      int n;
      while ((n = in.read(buffer)) > 0) {
        out.write(buffer, 0, n);
      }
    } catch (IOException e) {
      IdeLog.logError(CorePlugin.getDefault(), e.getMessage(), e);
      if (file != null) {
        if (!file.delete()) {
          file.deleteOnExit();
        }
      }
      return false;
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
        }
      }
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) {
        }
      }
    }

    try {
      ZipUtil.extract(file, dir, null);
    } catch (IOException e) {
      IdeLog.logError(CorePlugin.getDefault(), e.getMessage(), e);
      return false;
    } finally {
      if (!file.delete()) {
        file.deleteOnExit();
      }
    }

    return true;
  }
 /**
  * Whether this stream is able to write the given entry.
  *
  * <p>May return false if it is set up to use encryption or a compression method that hasn't been
  * implemented yet.
  *
  * @since 1.1
  */
 @Override
 public boolean canWriteEntryData(ArchiveEntry ae) {
   if (ae instanceof ZipArchiveEntry) {
     ZipArchiveEntry zae = (ZipArchiveEntry) ae;
     return zae.getMethod() != ZipMethod.IMPLODING.getCode()
         && zae.getMethod() != ZipMethod.UNSHRINKING.getCode()
         && ZipUtil.canHandleEntryData(zae);
   }
   return false;
 }
Ejemplo n.º 7
0
 private void readCentralDirectoryEntry(final Map<ZipEntry, NameAndComment> noUTF8Flag)
     throws IOException {
   this.archive.readFully(this.CFH_BUF);
   int off = 0;
   final OffsetEntry offset = new OffsetEntry();
   final Entry ze = new Entry(offset);
   final int versionMadeBy = ZipShort.getValue(this.CFH_BUF, off);
   off += 2;
   ze.setPlatform(versionMadeBy >> 8 & 0xF);
   off += 2;
   final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(this.CFH_BUF, off);
   final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames();
   final ZipEncoding entryEncoding =
       hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : this.zipEncoding;
   ze.setGeneralPurposeBit(gpFlag);
   off += 2;
   ze.setMethod(ZipShort.getValue(this.CFH_BUF, off));
   off += 2;
   final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(this.CFH_BUF, off));
   ze.setTime(time);
   off += 4;
   ze.setCrc(ZipLong.getValue(this.CFH_BUF, off));
   off += 4;
   ze.setCompressedSize(ZipLong.getValue(this.CFH_BUF, off));
   off += 4;
   ze.setSize(ZipLong.getValue(this.CFH_BUF, off));
   off += 4;
   final int fileNameLen = ZipShort.getValue(this.CFH_BUF, off);
   off += 2;
   final int extraLen = ZipShort.getValue(this.CFH_BUF, off);
   off += 2;
   final int commentLen = ZipShort.getValue(this.CFH_BUF, off);
   off += 2;
   final int diskStart = ZipShort.getValue(this.CFH_BUF, off);
   off += 2;
   ze.setInternalAttributes(ZipShort.getValue(this.CFH_BUF, off));
   off += 2;
   ze.setExternalAttributes(ZipLong.getValue(this.CFH_BUF, off));
   off += 4;
   final byte[] fileName = new byte[fileNameLen];
   this.archive.readFully(fileName);
   ze.setName(entryEncoding.decode(fileName), fileName);
   offset.headerOffset = ZipLong.getValue(this.CFH_BUF, off);
   this.entries.add(ze);
   final byte[] cdExtraData = new byte[extraLen];
   this.archive.readFully(cdExtraData);
   ze.setCentralDirectoryExtra(cdExtraData);
   this.setSizesAndOffsetFromZip64Extra(ze, offset, diskStart);
   final byte[] comment = new byte[commentLen];
   this.archive.readFully(comment);
   ze.setComment(entryEncoding.decode(comment));
   if (!hasUTF8Flag && this.useUnicodeExtraFields) {
     noUTF8Flag.put(ze, new NameAndComment(fileName, comment));
   }
 }
Ejemplo n.º 8
0
  public File extractAffFile() {
    if (!type.isArchive()) return new File(FileUtil.changeFileExt(getPath(), ".aff"));

    File result = new File(getTempFolder() + affName);
    if (!result.exists())
      try {
        ZipUtil.unzip(getPath(), getTempFolder(), ".aff");
      } catch (IOException e) {
        return null;
      }

    return result;
  }
Ejemplo n.º 9
0
  public File extractDicFile() {
    if (!type.isArchive()) return this;

    File result = new File(getTempFolder() + dicName);
    if (!result.exists())
      try {
        ZipUtil.unzip(getPath(), getTempFolder(), ".dic");
      } catch (IOException e) {
        return null;
      }

    return result;
  }
Ejemplo n.º 10
0
 /**
  * Writes bytes to ZIP entry.
  *
  * @param b the byte array to write
  * @param offset the start position to write from
  * @param length the number of bytes to write
  * @throws IOException on error
  */
 @Override
 public void write(byte[] b, int offset, int length) throws IOException {
   if (entry == null) {
     throw new IllegalStateException("No current entry");
   }
   ZipUtil.checkRequestedFeatures(entry.entry);
   entry.hasWritten = true;
   if (entry.entry.getMethod() == DEFLATED) {
     writeDeflated(b, offset, length);
   } else {
     writeOut(b, offset, length);
     written += length;
   }
   crc.update(b, offset, length);
   count(length);
 }
Ejemplo n.º 11
0
  public static Map<String, String> readManifest(final ZipFile zip) throws IOException {

    final ZipEntry zipentry = ZipUtil.getZipEntry(zip, MANIFEST_PATH);

    if (zipentry != null) {
      final InputStream in = zip.getInputStream(zipentry);

      try {
        return readManifest(in);
      } finally {
        try {
          in.close();
        } catch (IOException e) {
        }
      }
    } else {
      return Collections.emptyMap();
    }
  }
Ejemplo n.º 12
0
  /**
   * Writes the central file header entry.
   *
   * @param ze the entry to write
   * @throws IOException on error
   * @throws Zip64RequiredException if the archive's size exceeds 4 GByte and {@link Zip64Mode
   *     #setUseZip64} is {@link Zip64Mode#Never}.
   */
  protected void writeCentralFileHeader(ZipArchiveEntry ze) throws IOException {
    writeOut(CFH_SIG);
    written += WORD;

    final long lfhOffset = offsets.get(ze).longValue();
    final boolean needsZip64Extra =
        hasZip64Extra(ze)
            || ze.getCompressedSize() >= ZIP64_MAGIC
            || ze.getSize() >= ZIP64_MAGIC
            || lfhOffset >= ZIP64_MAGIC;

    if (needsZip64Extra && zip64Mode == Zip64Mode.Never) {
      // must be the offset that is too big, otherwise an
      // exception would have been throw in putArchiveEntry or
      // closeArchiveEntry
      throw new Zip64RequiredException(Zip64RequiredException.ARCHIVE_TOO_BIG_MESSAGE);
    }

    handleZip64Extra(ze, lfhOffset, needsZip64Extra);

    // version made by
    // CheckStyle:MagicNumber OFF
    writeOut(
        ZipShort.getBytes(
            (ze.getPlatform() << 8)
                | (!hasUsedZip64 ? DATA_DESCRIPTOR_MIN_VERSION : ZIP64_MIN_VERSION)));
    written += SHORT;

    final int zipMethod = ze.getMethod();
    final boolean encodable = zipEncoding.canEncode(ze.getName());
    writeVersionNeededToExtractAndGeneralPurposeBits(
        zipMethod, !encodable && fallbackToUTF8, needsZip64Extra);
    written += WORD;

    // compression method
    writeOut(ZipShort.getBytes(zipMethod));
    written += SHORT;

    // last mod. time and date
    writeOut(ZipUtil.toDosTime(ze.getTime()));
    written += WORD;

    // CRC
    // compressed length
    // uncompressed length
    writeOut(ZipLong.getBytes(ze.getCrc()));
    if (ze.getCompressedSize() >= ZIP64_MAGIC || ze.getSize() >= ZIP64_MAGIC) {
      writeOut(ZipLong.ZIP64_MAGIC.getBytes());
      writeOut(ZipLong.ZIP64_MAGIC.getBytes());
    } else {
      writeOut(ZipLong.getBytes(ze.getCompressedSize()));
      writeOut(ZipLong.getBytes(ze.getSize()));
    }
    // CheckStyle:MagicNumber OFF
    written += 12;
    // CheckStyle:MagicNumber ON

    ByteBuffer name = getName(ze);

    writeOut(ZipShort.getBytes(name.limit()));
    written += SHORT;

    // extra field length
    byte[] extra = ze.getCentralDirectoryExtra();
    writeOut(ZipShort.getBytes(extra.length));
    written += SHORT;

    // file comment length
    String comm = ze.getComment();
    if (comm == null) {
      comm = "";
    }

    ByteBuffer commentB = getEntryEncoding(ze).encode(comm);

    writeOut(ZipShort.getBytes(commentB.limit()));
    written += SHORT;

    // disk number start
    writeOut(ZERO);
    written += SHORT;

    // internal file attributes
    writeOut(ZipShort.getBytes(ze.getInternalAttributes()));
    written += SHORT;

    // external file attributes
    writeOut(ZipLong.getBytes(ze.getExternalAttributes()));
    written += WORD;

    // relative offset of LFH
    writeOut(ZipLong.getBytes(Math.min(lfhOffset, ZIP64_MAGIC)));
    written += WORD;

    // file name
    writeOut(name.array(), name.arrayOffset(), name.limit() - name.position());
    written += name.limit();

    // extra field
    writeOut(extra);
    written += extra.length;

    // file comment
    writeOut(commentB.array(), commentB.arrayOffset(), commentB.limit() - commentB.position());
    written += commentB.limit();
  }
Ejemplo n.º 13
0
  /**
   * Writes the local file header entry
   *
   * @param ze the entry to write
   * @throws IOException on error
   */
  protected void writeLocalFileHeader(ZipArchiveEntry ze) throws IOException {

    boolean encodable = zipEncoding.canEncode(ze.getName());
    ByteBuffer name = getName(ze);

    if (createUnicodeExtraFields != UnicodeExtraFieldPolicy.NEVER) {
      addUnicodeExtraFields(ze, encodable, name);
    }

    offsets.put(ze, Long.valueOf(written));

    writeOut(LFH_SIG);
    written += WORD;

    // store method in local variable to prevent multiple method calls
    final int zipMethod = ze.getMethod();

    writeVersionNeededToExtractAndGeneralPurposeBits(
        zipMethod, !encodable && fallbackToUTF8, hasZip64Extra(ze));
    written += WORD;

    // compression method
    writeOut(ZipShort.getBytes(zipMethod));
    written += SHORT;

    // last mod. time and date
    writeOut(ZipUtil.toDosTime(ze.getTime()));
    written += WORD;

    // CRC
    // compressed length
    // uncompressed length
    entry.localDataStart = written;
    if (zipMethod == DEFLATED || raf != null) {
      writeOut(LZERO);
      if (hasZip64Extra(entry.entry)) {
        // point to ZIP64 extended information extra field for
        // sizes, may get rewritten once sizes are known if
        // stream is seekable
        writeOut(ZipLong.ZIP64_MAGIC.getBytes());
        writeOut(ZipLong.ZIP64_MAGIC.getBytes());
      } else {
        writeOut(LZERO);
        writeOut(LZERO);
      }
    } else {
      writeOut(ZipLong.getBytes(ze.getCrc()));
      byte[] size = ZipLong.ZIP64_MAGIC.getBytes();
      if (!hasZip64Extra(ze)) {
        size = ZipLong.getBytes(ze.getSize());
      }
      writeOut(size);
      writeOut(size);
    }
    // CheckStyle:MagicNumber OFF
    written += 12;
    // CheckStyle:MagicNumber ON

    // file name length
    writeOut(ZipShort.getBytes(name.limit()));
    written += SHORT;

    // extra field length
    byte[] extra = ze.getLocalFileDataExtra();
    writeOut(ZipShort.getBytes(extra.length));
    written += SHORT;

    // file name
    writeOut(name.array(), name.arrayOffset(), name.limit() - name.position());
    written += name.limit();

    // extra field
    writeOut(extra);
    written += extra.length;

    entry.dataStart = written;
  }
Ejemplo n.º 14
0
 public boolean canReadEntryData(final ZipEntry ze) {
   return ZipUtil.canHandleEntryData(ze);
 }
Ejemplo n.º 15
0
 /**
  * Get version for the specified Firefox extension ID
  *
  * @param extensionID
  * @param profileDir
  * @return
  */
 public static String getExtensionVersion(String extensionID, IPath profileDir) {
   try {
     IPath dir = profileDir.append("extensions").append(extensionID); // $NON-NLS-1$
     InputStream rdfInputStream = null;
     if (dir.toFile().isFile()) {
       dir = Path.fromOSString(IOUtil.read(new FileInputStream(dir.toFile())));
     }
     if (dir.toFile().isDirectory()) {
       File installRdf = dir.append("install.rdf").toFile(); // $NON-NLS-1$
       if (installRdf.exists()) {
         rdfInputStream = new FileInputStream(installRdf);
       }
     } else if (dir.addFileExtension("xpi").toFile().isFile()) // $NON-NLS-1$
     {
       rdfInputStream =
           ZipUtil.openEntry(
               dir.addFileExtension("xpi").toFile(), // $NON-NLS-1$
               Path.fromPortableString("install.rdf")); // $NON-NLS-1$
     }
     if (rdfInputStream != null) {
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       DocumentBuilder parser = factory.newDocumentBuilder();
       Document document = parser.parse(rdfInputStream);
       Node node = document.getDocumentElement().getFirstChild();
       while (node != null) {
         if ("description".equals(node.getNodeName().toLowerCase()) // $NON-NLS-1$
             || "rdf:description".equals(node.getNodeName().toLowerCase())) { // $NON-NLS-1$
           NamedNodeMap attrs = node.getAttributes();
           Node about = attrs.getNamedItem("about"); // $NON-NLS-1$
           if (about == null) {
             about = attrs.getNamedItem("RDF:about"); // $NON-NLS-1$
           }
           if (about != null) {
             if ("urn:mozilla:install-manifest".equals(about.getNodeValue())) { // $NON-NLS-1$
               break;
             }
           }
         }
         node = node.getNextSibling();
       }
       if (node != null) {
         NamedNodeMap attrs = node.getAttributes();
         Node version = attrs.getNamedItem("em:version"); // $NON-NLS-1$
         if (version != null) {
           return version.getNodeValue();
         }
         node = node.getFirstChild();
       }
       while (node != null) {
         if ("em:version".equals(node.getNodeName().toLowerCase())) { // $NON-NLS-1$
           break;
         }
         node = node.getNextSibling();
       }
       if (node != null) {
         return node.getTextContent();
       }
     }
   } catch (Exception e) {
     IdeLog.logError(CorePlugin.getDefault(), e.getMessage(), e);
   }
   return null;
 }