Java Code Examples for java.util.jar.JarFile#getJarEntry()

The following examples show how to use java.util.jar.JarFile#getJarEntry() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestNormal.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
    try {
        if (jf1.size() != jf2.size()) {
            throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
                    + " have different number of entries");
        }
        for (JarEntry elem1 : Collections.list(jf1.entries())) {
            JarEntry elem2 = jf2.getJarEntry(elem1.getName());
            if (elem2 == null) {
                throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
            }
            if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
                throw new Exception("The crc of " + elem1.getName() + " is different.");
            }
        }
    } finally {
        jf1.close();
        jf2.close();
    }
}
 
Example 2
Source File: MavenHelper.java    From cyclonedx-gradle-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts a pom from an artifacts jar file and creates a MavenProject from it.
 * @param artifact the artifact to extract the pom from
 * @return a Maven project
 */
MavenProject extractPom(ResolvedArtifact artifact) {
    if (!isDescribedArtifact(artifact)) {
        return null;
    }
    if (artifact.getFile() != null) {
        try {
            final JarFile jarFile = new JarFile(artifact.getFile());
            final ModuleVersionIdentifier mid = artifact.getModuleVersion().getId();
            final JarEntry entry = jarFile.getJarEntry("META-INF/maven/"+ mid.getGroup() + "/" + mid.getName() + "/pom.xml");
            if (entry != null) {
                try (final InputStream input = jarFile.getInputStream(entry)) {
                    return readPom(input);
                }
            }
        } catch (IOException e) {
            logger.error("An error occurred attempting to extract POM from artifact", e);
        }
    }
    return null;
}
 
Example 3
Source File: URLUtils.java    From confucius-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Is directory URL?
 *
 * @param url
 *         URL
 * @return if directory , return <code>true</code>
 */
public static boolean isDirectoryURL(URL url) {
    boolean isDirectory = false;
    if (url != null) {
        String protocol = url.getProtocol();
        try {
            if (ProtocolConstants.JAR.equals(protocol)) {
                JarFile jarFile = JarUtils.toJarFile(url); // Test whether valid jar or not
                final String relativePath = JarUtils.resolveRelativePath(url);
                if (StringUtils.EMPTY.equals(relativePath)) { // root directory in jar
                    isDirectory = true;
                } else {
                    JarEntry jarEntry = jarFile.getJarEntry(relativePath);
                    isDirectory = jarEntry != null && jarEntry.isDirectory();
                }
            } else if (ProtocolConstants.FILE.equals(protocol)) {
                File classPathFile = new File(url.toURI());
                isDirectory = classPathFile.isDirectory();
            }
        } catch (Exception e) {
            isDirectory = false;
        }
    }
    return isDirectory;
}
 
Example 4
Source File: TestNormal.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
    try {
        if (jf1.size() != jf2.size()) {
            throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
                    + " have different number of entries");
        }
        for (JarEntry elem1 : Collections.list(jf1.entries())) {
            JarEntry elem2 = jf2.getJarEntry(elem1.getName());
            if (elem2 == null) {
                throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
            }
            if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
                throw new Exception("The crc of " + elem1.getName() + " is different.");
            }
        }
    } finally {
        jf1.close();
        jf2.close();
    }
}
 
Example 5
Source File: TestNormal.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
    try {
        if (jf1.size() != jf2.size()) {
            throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
                    + " have different number of entries");
        }
        for (JarEntry elem1 : Collections.list(jf1.entries())) {
            JarEntry elem2 = jf2.getJarEntry(elem1.getName());
            if (elem2 == null) {
                throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
            }
            if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
                throw new Exception("The crc of " + elem1.getName() + " is different.");
            }
        }
    } finally {
        jf1.close();
        jf2.close();
    }
}
 
Example 6
Source File: JBossJaxWsStack.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String resolveImplementationVersion() throws IOException {
    // take webservices-tools.jar file
    File wsToolsJar = new File(root, JAXWS_TOOLS_JAR);
    
    if (wsToolsJar.exists()) {            
        JarFile jarFile = new JarFile(wsToolsJar);
        JarEntry entry = jarFile.getJarEntry("com/sun/tools/ws/version.properties"); //NOI18N
        if (entry != null) {
            InputStream is = jarFile.getInputStream(entry);
            BufferedReader r = new BufferedReader(new InputStreamReader(is));
            String ln = null;
            String ver = null;
            while ((ln=r.readLine()) != null) {
                String line = ln.trim();
                if (line.startsWith("major-version=")) { //NOI18N
                    ver = line.substring(14);
                }
            }
            r.close();
            return ver;
        }           
    }
    return null;
}
 
Example 7
Source File: TemplateVars.java    From auto with Apache License 2.0 6 votes vote down vote up
private static InputStream inputStreamFromJar(URL resourceUrl)
    throws URISyntaxException, IOException {
  // Jar URLs look like this: jar:file:/path/to/file.jar!/entry/within/jar
  // So take apart the URL to open the jar /path/to/file.jar and read the entry
  // entry/within/jar from it.
  String resourceUrlString = resourceUrl.toString().substring("jar:".length());
  int bang = resourceUrlString.lastIndexOf('!');
  String entryName = resourceUrlString.substring(bang + 1);
  if (entryName.startsWith("/")) {
    entryName = entryName.substring(1);
  }
  URI jarUri = new URI(resourceUrlString.substring(0, bang));
  JarFile jar = new JarFile(new File(jarUri));
  JarEntry entry = jar.getJarEntry(entryName);
  InputStream in = jar.getInputStream(entry);
  // We have to be careful not to close the JarFile before the stream has been read, because
  // that would also close the stream. So we defer closing the JarFile until the stream is closed.
  return new FilterInputStream(in) {
    @Override
    public void close() throws IOException {
      super.close();
      jar.close();
    }
  };
}
 
Example 8
Source File: APPUtil.java    From DownloadManager with Apache License 2.0 6 votes vote down vote up
/**
 * 获取未安装APK的签名
 * @param file
 * @return
 * @throws IOException
 */
public static List<String> getUninstallApkSignatures(File file){
    List<String> signatures=new ArrayList<String>();
    try {
        JarFile jarFile=new JarFile(file);
        JarEntry je=jarFile.getJarEntry("AndroidManifest.xml");
        byte[] readBuffer=new byte[8192];
        Certificate[] certs=loadCertificates(jarFile, je, readBuffer);
        if(certs != null) {
            for(Certificate c: certs) {
                String sig=toCharsString(c.getEncoded());
                signatures.add(sig);
            }
        }
    } catch(Exception ex) {
    }
    return signatures;
}
 
Example 9
Source File: JarFileReadingServlet.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  File jarFile = new File(getPathOfJarContainingThisClass());
  File jarDirectory = jarFile.getParentFile();
  // write the contents of the directory to the response
  for (File f : jarDirectory.listFiles()) {
    response.getOutputStream().print(f.getName());
  }
  JarFile jar = new JarFile(jarFile);
  JarEntry entry =
      jar.getJarEntry(getClass().getPackage().getName().replace(".", "/") + "/AnXmlResource.xml");
  InputStream is = jar.getInputStream(entry);
  byte[] buffer = new byte[8192];
  int len;
  while ((len = is.read(buffer, 0, buffer.length)) != -1) {
    response.getOutputStream().write(buffer, 0, len);
  }
}
 
Example 10
Source File: BrandingSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void loadLocalizedBundlesFromPlatform(final BrandableModule moduleEntry,
        final String bundleEntry, final Set<String> keys, final Set<BundleKey> bundleKeys) throws IOException {
    Properties p = new Properties();
    JarFile module = new JarFile(moduleEntry.getJarLocation());
    JarEntry je = module.getJarEntry(bundleEntry);
    InputStream is = module.getInputStream(je);
    File bundle = new File(getModuleEntryDirectory(moduleEntry),bundleEntry);
    try {
        
        p.load(is);
    } finally {
        is.close();
    }
    for (String key : NbCollections.checkedMapByFilter(p, String.class, String.class, true).keySet()) {
        if (keys.contains(key)) {
            String value = p.getProperty(key);
            bundleKeys.add(new BundleKey(moduleEntry, bundle, key, value));
        } 
    }
}
 
Example 11
Source File: AutoMakeLoadHandler.java    From molicode with Apache License 2.0 6 votes vote down vote up
/**
 * 从jar file中获取 autoMake 信息
 *
 * @param autoCodeParams
 * @param jarFilePath
 * @return
 * @throws IOException
 */
private AutoMakeVo loadAutoMakeFromJarFile(AutoCodeParams autoCodeParams, File jarFilePath) throws IOException {

    JarFile jarFile = new JarFile(jarFilePath);

    JarEntry jarEntry = jarFile.getJarEntry(AUTO_CODE_XML_FILE_NAME);
    if (jarEntry == null) {
        throw new AutoCodeException("maven下载的jar包中,没有autoCode.xml配置文件!", ResultCodeEnum.FAILURE);
    }

    InputStream autoCodeXmlInputStream = jarFile.getInputStream(jarEntry);
    String autoCodeContent = IOUtils.toString(autoCodeXmlInputStream, Profiles.getInstance().getFileEncoding());
    IOUtils.closeQuietly(autoCodeXmlInputStream);
    AutoMakeVo autoMake = XmlUtils.getAutoMakeByContent(autoCodeContent);

    if (autoCodeParams.getLoadTemplateContent()) {
        ThreadLocalHolder.setJarFileToCodeContext(jarFile);
        autoMakeService.loadTemplateContent(autoMake, jarFile);
    }

    loadMavenInfo(jarFile, autoMake);
    return autoMake;
}
 
Example 12
Source File: BaseCycloneDxMojo.java    From cyclonedx-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts a pom from an artifacts jar file and creates a MavenProject from it.
 * @param artifact the artifact to extract the pom from
 * @return a Maven project
 */
private MavenProject extractPom(Artifact artifact) {
    if (!isDescribedArtifact(artifact)) {
        return null;
    }
    if (artifact.getFile() != null) {
        try {
            final JarFile jarFile = new JarFile(artifact.getFile());
            final JarEntry entry = jarFile.getJarEntry("META-INF/maven/"+ artifact.getGroupId() + "/" + artifact.getArtifactId() + "/pom.xml");
            if (entry != null) {
                try (final InputStream input = jarFile.getInputStream(entry)) {
                    return readPom(input);
                }
            } else {
                // Read the pom.xml directly from the filesystem as a fallback
                Path artifactPath = Paths.get(artifact.getFile().getPath());
                String pomFilename = artifactPath.getFileName().toString().replace("jar", "pom");
                Path pomPath = artifactPath.resolveSibling(pomFilename);
                if (Files.exists(pomPath)) {
                   try (final InputStream input = Files.newInputStream(pomPath)) {
                      return readPom(input);
                   }
                }
            }
        } catch (IOException e) {
            getLog().error("An error occurred attempting to extract POM from artifact", e);
        }
    }
    return null;
}
 
Example 13
Source File: JarSigner.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private static String getManifest(JarFile jar) throws IOException {

		JarEntry manifestEntry = jar.getJarEntry(MANIFEST_LOCATION);

		try (InputStream jis = jar.getInputStream(manifestEntry);
				ByteArrayOutputStream baos = new ByteArrayOutputStream()){

			CopyUtil.copyClose(jis, baos);
			return baos.toString();
		}
	}
 
Example 14
Source File: EnvironmentUtil.java    From apkextractor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获取apk包签名基本信息
 * @return string[0]证书发行者,string[1]证书所有者,string[2]序列号
 * string[3]证书起始时间 string[4]证书结束时间
 */
public static @NonNull String[] getAPKSignInfo(String filePath) {
    String subjectDN = "";
    String issuerDN = "";
    String serial = "";
    String notBefore="";
    String notAfter="";
    try {
        JarFile JarFile = new JarFile(filePath);
        JarEntry JarEntry = JarFile.getJarEntry("AndroidManifest.xml");
        if (JarEntry != null) {
            byte[] readBuffer = new byte[8192];
            InputStream is = new BufferedInputStream(JarFile.getInputStream(JarEntry));
            while (is.read(readBuffer, 0, readBuffer.length) != -1) {
                //notusing
            }
            Certificate[] certs = JarEntry.getCertificates();
            if (certs != null && certs.length > 0) {
                //获取证书
                X509Certificate x509cert = (X509Certificate) certs[0];
                //获取证书发行者
                issuerDN = x509cert.getIssuerDN().toString();
                //System.out.println("发行者:" + issuerDN);
                //获取证书所有者
                subjectDN = x509cert.getSubjectDN().toString();
                //System.out.println("所有者:" + subjectDN);
                //证书序列号
                serial = x509cert.getSerialNumber().toString();
                //System.out.println("publicKey:" + publicKey);
                //证书起始有效期
                notBefore=x509cert.getNotBefore().toString();
                //证书结束有效期
                notAfter=x509cert.getNotAfter().toString();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new String[]{subjectDN,issuerDN,serial,notBefore,notAfter};
}
 
Example 15
Source File: Util.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies whether the file resource exists.
 *
 * @param uri the URI to locate the resource
 * @param openJarFile a flag to indicate whether a JAR file should be
 * opened. This operation may be expensive.
 * @return true if the resource exists, false otherwise.
 */
static boolean isFileUriExist(URI uri, boolean openJarFile) {
    if (uri != null && uri.isAbsolute()) {
        if (null != uri.getScheme()) {
            switch (uri.getScheme()) {
                case SCHEME_FILE:
                    String path = uri.getPath();
                    File f1 = new File(path);
                    if (f1.isFile()) {
                        return true;
                    }
                    break;
                case SCHEME_JAR:
                    String tempUri = uri.toString();
                    int pos = tempUri.indexOf("!");
                    if (pos < 0) {
                        return false;
                    }
                    if (openJarFile) {
                        String jarFile = tempUri.substring(SCHEME_JARFILE.length(), pos);
                        String entryName = tempUri.substring(pos + 2);
                        try {
                            JarFile jf = new JarFile(jarFile);
                            JarEntry je = jf.getJarEntry(entryName);
                            if (je != null) {
                                return true;
                            }
                        } catch (IOException ex) {
                            return false;
                        }
                    } else {
                        return true;
                    }
                    break;
            }
        }
    }
    return false;
}
 
Example 16
Source File: PropertySetter.java    From tmc-intellij with MIT License 5 votes vote down vote up
private void setPluginLog() {
    String jarPath =
            PathManager.getPluginsPath() + "/tmc-plugin-intellij/lib/tmc-plugin-intellij.jar";
    try {
        JarFile jar = new JarFile(jarPath);
        JarEntry entry = jar.getJarEntry("log4j.properties");
        InputStream is = jar.getInputStream(entry);
        PropertyConfigurator.configure(is);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 17
Source File: DataTrackTool.java    From tracker with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Determines if a jar file is a (likely) data source.
 *
 * @param jarPath the path to a jar file
 * @return true if the jar contains the DataTrackSupport class
 */
public static boolean isDataSource(String jarPath) {
try {
	JarFile jar = new JarFile(jarPath);
	String classPath = DataTrackSupport.class.getName().replace(".", "/"); //$NON-NLS-1$ //$NON-NLS-2$
	JarEntry entry = jar.getJarEntry(classPath+".class"); //$NON-NLS-1$
	jar.close();
	return entry!=null;
} catch (IOException ex) {
}
return false;
}
 
Example 18
Source File: InstallationDescriptorHandler.java    From uima-uimaj with Apache License 2.0 3 votes vote down vote up
/**
 * Parses XML installation descriptor automatically extracting it from a given PEAR (JAR) file.
 * 
 * @param pearFile
 *          The given PEAR (JAR) file.
 * @throws IOException
 *           if any I/O exception occurred.
 * @throws SAXException
 *           Any SAX exception, possibly wrapping another exception.
 */
public synchronized void parseInstallationDescriptor(JarFile pearFile) throws IOException,
        SAXException {
  String insdFilePath = InstallationProcessor.INSD_FILE_PATH;
  JarEntry insdJarEntry = pearFile.getJarEntry(insdFilePath);
  if (insdJarEntry != null) {
    parse(pearFile.getInputStream(insdJarEntry));
  } else
    throw new IOException("installation drescriptor not found");
}
 
Example 19
Source File: JarUtils.java    From confucius-commons with Apache License 2.0 3 votes vote down vote up
/**
 * Find {@link JarEntry} from specified <code>url</code>
 *
 * @param jarURL
 *         jar resource url
 * @return If found , return {@link JarEntry}
 */
public static JarEntry findJarEntry(URL jarURL) throws IOException {
    JarFile jarFile = JarUtils.toJarFile(jarURL);
    final String relativePath = JarUtils.resolveRelativePath(jarURL);
    JarEntry jarEntry = jarFile.getJarEntry(relativePath);
    return jarEntry;
}
 
Example 20
Source File: FileUtil.java    From uima-uimaj with Apache License 2.0 3 votes vote down vote up
/**
 * Loads a specified text file from a given JAR file.
 * 
 * @param filePath
 *          The specified text file path inside the JAR file.
 * @param jarFile
 *          The given JAR file.
 * @return The content of the text specified file, or <code>null</code>, if the text file was
 *         not found in the given JAR file.
 * @throws IOException
 *           If any I/O exception occurs.
 */
public static String loadTextFileFromJar(String filePath, JarFile jarFile) throws IOException {
  String content = null;
  String name = filePath.replace('\\', '/');
  JarEntry jarEntry = jarFile.getJarEntry(name);
  if (jarEntry != null) {
    try (BufferedReader iStream = new BufferedReader(new InputStreamReader(jarFile.getInputStream(jarEntry)))) {
      content = loadTextFile(iStream);
    }
  }
  return content;
}