use of java.util.jar.JarFile in project XobotOS by xamarin.
the class URLClassLoader method createURLJarHandler.
private URLHandler createURLJarHandler(URL url) {
String prefixName;
String file = url.getFile();
if (url.getFile().endsWith("!/")) {
prefixName = "";
} else {
int sepIdx = file.lastIndexOf("!/");
if (sepIdx == -1) {
// Invalid URL, don't look here again
return null;
}
sepIdx += 2;
prefixName = file.substring(sepIdx);
}
try {
URL jarURL = ((JarURLConnection) url.openConnection()).getJarFileURL();
JarURLConnection juc = (JarURLConnection) new URL("jar", "", jarURL.toExternalForm() + "!/").openConnection();
JarFile jf = juc.getJarFile();
URLJarHandler jarH = new URLJarHandler(url, jarURL, jf, prefixName);
if (jarH.getIndex() == null) {
try {
Manifest manifest = jf.getManifest();
if (manifest != null) {
String classpath = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
if (classpath != null) {
searchList.addAll(0, getInternalURLs(url, classpath));
}
}
} catch (IOException e) {
}
}
return jarH;
} catch (IOException e) {
}
return null;
}
use of java.util.jar.JarFile in project otertool by wuntee.
the class JarSigner method signJar.
void signJar(String jarName, String alias, String[] args) throws Exception {
boolean aliasUsed = false;
X509Certificate tsaCert = null;
if (sigfile == null) {
sigfile = alias;
aliasUsed = true;
}
if (sigfile.length() > 8) {
sigfile = sigfile.substring(0, 8).toUpperCase();
} else {
sigfile = sigfile.toUpperCase();
}
StringBuilder tmpSigFile = new StringBuilder(sigfile.length());
for (int j = 0; j < sigfile.length(); j++) {
char c = sigfile.charAt(j);
if (!((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '-') || (c == '_'))) {
if (aliasUsed) {
// convert illegal characters from the alias to be _'s
c = '_';
} else {
throw new RuntimeException(rb.getString("signature filename must consist of the following characters: A-Z, 0-9, _ or -"));
}
}
tmpSigFile.append(c);
}
sigfile = tmpSigFile.toString();
String tmpJarName;
if (signedjar == null)
tmpJarName = jarName + ".sig";
else
tmpJarName = signedjar;
File jarFile = new File(jarName);
File signedJarFile = new File(tmpJarName);
// Open the jar (zip) file
try {
zipFile = new ZipFile(jarName);
} catch (IOException ioe) {
error(rb.getString("unable to open jar file: ") + jarName, ioe);
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(signedJarFile);
} catch (IOException ioe) {
error(rb.getString("unable to create: ") + tmpJarName, ioe);
}
PrintStream ps = new PrintStream(fos);
ZipOutputStream zos = new ZipOutputStream(ps);
/* First guess at what they might be - we don't xclude RSA ones. */
String sfFilename = (META_INF + sigfile + ".SF").toUpperCase();
String bkFilename = (META_INF + sigfile + ".DSA").toUpperCase();
Manifest manifest = new Manifest();
Map<String, Attributes> mfEntries = manifest.getEntries();
// The Attributes of manifest before updating
Attributes oldAttr = null;
boolean mfModified = false;
boolean mfCreated = false;
byte[] mfRawBytes = null;
try {
MessageDigest[] digests = { MessageDigest.getInstance(digestalg) };
// Check if manifest exists
ZipEntry mfFile;
if ((mfFile = getManifestFile(zipFile)) != null) {
// Manifest exists. Read its raw bytes.
mfRawBytes = getBytes(zipFile, mfFile);
manifest.read(new ByteArrayInputStream(mfRawBytes));
oldAttr = (Attributes) (manifest.getMainAttributes().clone());
} else {
// Create new manifest
Attributes mattr = manifest.getMainAttributes();
mattr.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
String javaVendor = System.getProperty("java.vendor");
String jdkVersion = System.getProperty("java.version");
mattr.putValue("Created-By", jdkVersion + " (" + javaVendor + ")");
mfFile = new ZipEntry(JarFile.MANIFEST_NAME);
mfCreated = true;
}
/*
* For each entry in jar
* (except for signature-related META-INF entries),
* do the following:
*
* - if entry is not contained in manifest, add it to manifest;
* - if entry is contained in manifest, calculate its hash and
* compare it with the one in the manifest; if they are
* different, replace the hash in the manifest with the newly
* generated one. (This may invalidate existing signatures!)
*/
BASE64Encoder encoder = new JarBASE64Encoder();
Vector<ZipEntry> mfFiles = new Vector<ZipEntry>();
for (Enumeration<? extends ZipEntry> enum_ = zipFile.entries(); enum_.hasMoreElements(); ) {
ZipEntry ze = enum_.nextElement();
if (ze.getName().startsWith(META_INF)) {
// Store META-INF files in vector, so they can be written
// out first
mfFiles.addElement(ze);
if (signatureRelated(ze.getName())) {
// ignore signature-related and manifest files
continue;
}
}
if (manifest.getAttributes(ze.getName()) != null) {
// possibly update its digest attributes
if (updateDigests(ze, zipFile, digests, encoder, manifest) == true) {
mfModified = true;
}
} else if (!ze.isDirectory()) {
// Add entry to manifest
Attributes attrs = getDigestAttributes(ze, zipFile, digests, encoder);
mfEntries.put(ze.getName(), attrs);
mfModified = true;
}
}
// Recalculate the manifest raw bytes if necessary
if (mfModified) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manifest.write(baos);
byte[] newBytes = baos.toByteArray();
if (mfRawBytes != null && oldAttr.equals(manifest.getMainAttributes())) {
/*
* Note:
*
* The Attributes object is based on HashMap and can handle
* continuation columns. Therefore, even if the contents are
* not changed (in a Map view), the bytes that it write()
* may be different from the original bytes that it read()
* from. Since the signature on the main attributes is based
* on raw bytes, we must retain the exact bytes.
*/
int newPos = findHeaderEnd(newBytes);
int oldPos = findHeaderEnd(mfRawBytes);
if (newPos == oldPos) {
System.arraycopy(mfRawBytes, 0, newBytes, 0, oldPos);
} else {
// cat oldHead newTail > newBytes
byte[] lastBytes = new byte[oldPos + newBytes.length - newPos];
System.arraycopy(mfRawBytes, 0, lastBytes, 0, oldPos);
System.arraycopy(newBytes, newPos, lastBytes, oldPos, newBytes.length - newPos);
newBytes = lastBytes;
}
}
mfRawBytes = newBytes;
}
// Write out the manifest
if (mfModified) {
// manifest file has new length
mfFile = new ZipEntry(JarFile.MANIFEST_NAME);
}
zos.putNextEntry(mfFile);
zos.write(mfRawBytes);
// Calculate SignatureFile (".SF") and SignatureBlockFile
ManifestDigester manDig = new ManifestDigester(mfRawBytes);
SignatureFile sf = new SignatureFile(digests, manifest, manDig, sigfile, signManifest);
if (tsaAlias != null) {
tsaCert = getTsaCert(tsaAlias);
}
SignatureFile.Block block = null;
try {
block = sf.generateBlock(privateKey, sigalg, certChain, externalSF, tsaUrl, tsaCert, signingMechanism, args, zipFile);
} catch (SocketTimeoutException e) {
// Provide a helpful message when TSA is beyond a firewall
error(rb.getString("unable to sign jar: ") + rb.getString("no response from the Timestamping Authority. ") + rb.getString("When connecting from behind a firewall then an HTTP proxy may need to be specified. ") + rb.getString("Supply the following options to jarsigner: ") + "\n -J-Dhttp.proxyHost=<hostname> " + "\n -J-Dhttp.proxyPort=<portnumber> ", e);
}
sfFilename = sf.getMetaName();
bkFilename = block.getMetaName();
ZipEntry sfFile = new ZipEntry(sfFilename);
ZipEntry bkFile = new ZipEntry(bkFilename);
long time = System.currentTimeMillis();
sfFile.setTime(time);
bkFile.setTime(time);
// signature file
zos.putNextEntry(sfFile);
sf.write(zos);
// signature block file
zos.putNextEntry(bkFile);
block.write(zos);
// vector
for (int i = 0; i < mfFiles.size(); i++) {
ZipEntry ze = mfFiles.elementAt(i);
if (!ze.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME) && !ze.getName().equalsIgnoreCase(sfFilename) && !ze.getName().equalsIgnoreCase(bkFilename)) {
writeEntry(zipFile, zos, ze);
}
}
// Write out all other files
for (Enumeration<? extends ZipEntry> enum_ = zipFile.entries(); enum_.hasMoreElements(); ) {
ZipEntry ze = enum_.nextElement();
if (!ze.getName().startsWith(META_INF)) {
writeEntry(zipFile, zos, ze);
}
}
} catch (IOException ioe) {
error(rb.getString("unable to sign jar: ") + ioe, ioe);
} finally {
// close the resouces
if (zipFile != null) {
zipFile.close();
zipFile = null;
}
if (zos != null) {
zos.close();
}
}
// try {
if (signedjar == null) {
// one, then delete the original.
if (!signedJarFile.renameTo(jarFile)) {
File origJar = new File(jarName + ".orig");
if (jarFile.renameTo(origJar)) {
if (signedJarFile.renameTo(jarFile)) {
origJar.delete();
} else {
MessageFormat form = new MessageFormat(rb.getString("attempt to rename signedJarFile to jarFile failed"));
Object[] source = { signedJarFile, jarFile };
error(form.format(source));
}
} else {
MessageFormat form = new MessageFormat(rb.getString("attempt to rename jarFile to origJar failed"));
Object[] source = { jarFile, origJar };
error(form.format(source));
}
}
}
if (hasExpiredCert || hasExpiringCert || notYetValidCert || badKeyUsage || badExtendedKeyUsage || badNetscapeCertType) {
logger.warn(rb.getString("Warning: "));
if (badKeyUsage) {
logger.warn(rb.getString("The signer certificate's KeyUsage extension doesn't allow code signing."));
}
if (badExtendedKeyUsage) {
logger.warn(rb.getString("The signer certificate's ExtendedKeyUsage extension doesn't allow code signing."));
}
if (badNetscapeCertType) {
logger.warn(rb.getString("The signer certificate's NetscapeCertType extension doesn't allow code signing."));
}
if (hasExpiredCert) {
logger.warn(rb.getString("The signer certificate has expired."));
} else if (hasExpiringCert) {
logger.warn(rb.getString("The signer certificate will expire within six months."));
} else if (notYetValidCert) {
logger.warn(rb.getString("The signer certificate is not yet valid."));
}
}
// no IOException thrown in the above try clause, so disable
// the catch clause.
// } catch(IOException ioe) {
// error(rb.getString("unable to sign jar: ")+ioe, ioe);
// }
}
use of java.util.jar.JarFile in project OpenAM by OpenRock.
the class FilesDigester method digest.
/**
* This function calculate the hash value of a file.
*
* @param hashAlg The algorithm to be used for calculating the hash.
* @param file The file to be processed.
* @param digestResult The Properties to store the results.
* @param ignoredPath The parent's path to ignore when printing the
* manifest entries.
* @param intoJar The flag to indicate whether to specially handle
* jar file.
* @param intoWar The flag to indicate whether to specially handle
* war file.
*/
public void digest(String hashAlg, File file, Properties digestResult, String ignoredPath, boolean intoJar, boolean intoWar) {
if (file.exists()) {
if (file.isDirectory()) {
if (recursive) {
File[] tempFiles = null;
if (includePattern != null) {
tempFiles = file.listFiles(new GeneralFileFilter(includePattern));
} else {
tempFiles = file.listFiles();
}
for (int i = 0; i < tempFiles.length; i++) {
if (tempFiles[i].isDirectory()) {
digest(hashAlg, tempFiles[i], digestResult, ignoredPath, intoJar, intoWar);
} else {
if (excludePattern != null) {
if (!Utils.isMatch(tempFiles[i].getName(), excludePattern, wildCard)) {
digest(hashAlg, tempFiles[i], digestResult, ignoredPath, intoJar, intoWar);
}
} else {
digest(hashAlg, tempFiles[i], digestResult, ignoredPath, intoJar, intoWar);
}
}
}
}
} else {
if (file.getName().endsWith(WAR_FILE_EXT) && (intoWar)) {
try {
digestWarFile(hashAlg, digestResult, new JarFile(file), intoJar);
} catch (IOException ex) {
ex.printStackTrace();
}
} else {
byte[] digestedbyte = null;
if ((file.getName().endsWith(JAR_FILE_EXT)) && (intoJar)) {
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
digestedbyte = digestJarFile(hashAlg, fin);
fin.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (fin != null) {
try {
fin.close();
} catch (IOException ignored) {
}
fin = null;
}
}
} else {
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
digestedbyte = Utils.getHash(hashAlg, fin);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (fin != null) {
try {
fin.close();
} catch (IOException ignored) {
}
fin = null;
}
}
}
String tempPath = file.getPath();
tempPath = tempPath.substring(tempPath.indexOf(ignoredPath) + ignoredPath.length()).replaceAll("\\\\", FILE_SEPARATOR);
if (tempPath.startsWith(FILE_SEPARATOR)) {
tempPath = tempPath.substring(1);
}
appendResult(digestResult, tempPath, digestedbyte);
}
}
}
}
use of java.util.jar.JarFile in project voltdb by VoltDB.
the class VoltCompiler method upgradeCatalogAsNeeded.
/**
* Check a loaded catalog. If it needs to be upgraded recompile it and save
* an upgraded jar file.
*
* @param outputJar in-memory jar file (updated in place here)
* @return source version upgraded from or null if not upgraded
* @throws IOException
*/
public String upgradeCatalogAsNeeded(InMemoryJarfile outputJar) throws IOException {
// getBuildInfoFromJar() performs some validation.
String[] buildInfoLines = CatalogUtil.getBuildInfoFromJar(outputJar);
String versionFromCatalog = buildInfoLines[0];
// Set if an upgrade happens.
String upgradedFromVersion = null;
// getConfig() may return null if it's being mocked for a test.
if (VoltDB.Configuration.m_forceCatalogUpgrade || !versionFromCatalog.equals(VoltDB.instance().getVersionString())) {
// Patch the buildinfo.
String versionFromVoltDB = VoltDB.instance().getVersionString();
buildInfoLines[0] = versionFromVoltDB;
buildInfoLines[1] = String.format("voltdb-auto-upgrade-to-%s", versionFromVoltDB);
byte[] buildInfoBytes = StringUtils.join(buildInfoLines, "\n").getBytes();
outputJar.put(CatalogUtil.CATALOG_BUILDINFO_FILENAME, buildInfoBytes);
// Gather DDL files for re-compilation
List<VoltCompilerReader> ddlReaderList = new ArrayList<>();
Entry<String, byte[]> entry = outputJar.firstEntry();
while (entry != null) {
String path = entry.getKey();
// ddl files instead of using a brute force *.sql glob.
if (path.toLowerCase().endsWith(".sql")) {
ddlReaderList.add(new VoltCompilerJarFileReader(outputJar, path));
}
entry = outputJar.higherEntry(entry.getKey());
}
// Use the in-memory jarfile-provided class loader so that procedure
// classes can be found and copied to the new file that gets written.
ClassLoader originalClassLoader = m_classLoader;
// Compile and save the file to voltdbroot. Assume it's a test environment if there
// is no catalog context available.
String jarName = String.format("catalog-%s.jar", versionFromVoltDB);
String textName = String.format("catalog-%s.out", versionFromVoltDB);
CatalogContext catalogContext = VoltDB.instance().getCatalogContext();
final String outputJarPath = (catalogContext != null ? new File(VoltDB.instance().getVoltDBRootPath(), jarName).getPath() : VoltDB.Configuration.getPathToCatalogForTest(jarName));
// Place the compiler output in a text file in the same folder.
final String outputTextPath = (catalogContext != null ? new File(VoltDB.instance().getVoltDBRootPath(), textName).getPath() : VoltDB.Configuration.getPathToCatalogForTest(textName));
try {
m_classLoader = outputJar.getLoader();
consoleLog.info(String.format("Version %s catalog will be automatically upgraded to version %s.", versionFromCatalog, versionFromVoltDB));
// Do the compilation work.
boolean success = compileInternalToFile(outputJarPath, null, null, ddlReaderList, outputJar);
// Bomb out if we failed to generate the canonical DDL
if (success) {
boolean foundCanonicalDDL = false;
entry = outputJar.firstEntry();
while (entry != null) {
String path = entry.getKey();
if (path.toLowerCase().endsWith(".sql")) {
if (!path.toLowerCase().equals(AUTOGEN_DDL_FILE_NAME)) {
outputJar.remove(path);
} else {
foundCanonicalDDL = true;
}
}
entry = outputJar.higherEntry(entry.getKey());
}
success = foundCanonicalDDL;
}
if (success) {
// Set up the return string.
upgradedFromVersion = versionFromCatalog;
}
// Summarize the results to a file.
// Briefly log success or failure and mention the output text file.
PrintStream outputStream = new PrintStream(outputTextPath);
try {
if (success) {
summarizeSuccess(outputStream, outputStream, outputJarPath);
consoleLog.info(String.format("The catalog was automatically upgraded from " + "version %s to %s and saved to \"%s\". " + "Compiler output is available in \"%s\".", versionFromCatalog, versionFromVoltDB, outputJarPath, outputTextPath));
} else {
summarizeErrors(outputStream, outputStream);
outputStream.close();
compilerLog.error("Catalog upgrade failed.");
compilerLog.info(String.format("Had attempted to perform an automatic version upgrade of a " + "catalog that was compiled by an older %s version of VoltDB, " + "but the automatic upgrade failed. The cluster will not be " + "able to start until the incompatibility is fixed. " + "Try re-compiling the catalog with the newer %s version " + "of the VoltDB compiler. Compiler output from the failed " + "upgrade is available in \"%s\".", versionFromCatalog, versionFromVoltDB, outputTextPath));
throw new IOException(String.format("Catalog upgrade failed. You will need to recompile using voltdb compile."));
}
} finally {
outputStream.close();
}
} catch (IOException ioe) {
// Do nothing because this could come from the normal failure path
throw ioe;
} catch (Exception e) {
compilerLog.error("Catalog upgrade failed with error:");
compilerLog.error(e.getMessage());
compilerLog.info(String.format("Had attempted to perform an automatic version upgrade of a " + "catalog that was compiled by an older %s version of VoltDB, " + "but the automatic upgrade failed. The cluster will not be " + "able to start until the incompatibility is fixed. " + "Try re-compiling the catalog with the newer %s version " + "of the VoltDB compiler. Compiler output from the failed " + "upgrade is available in \"%s\".", versionFromCatalog, versionFromVoltDB, outputTextPath));
throw new IOException(String.format("Catalog upgrade failed. You will need to recompile using voltdb compile."));
} finally {
// Restore the original class loader
m_classLoader = originalClassLoader;
}
}
return upgradedFromVersion;
}
use of java.util.jar.JarFile in project ACS by ACS-Community.
the class JarSourceExtractor method extractJavaSourcesToFiles.
/**
* Extracts Java source files from a JAR file and puts them as individual files
* under a given directory.
*
* @param jarfile jar file from which Java source will be extracted
* @param outDir root dir under which the extracted java files will be placed
* @throws IOException
*/
public void extractJavaSourcesToFiles(JarFile jarfile, File outDir) throws IOException {
if (!outDir.exists() || !outDir.isDirectory() || !outDir.canWrite()) {
throw new IOException("specified directory " + outDir.getAbsolutePath() + " is not a valid writeable directory.");
}
JarEntry[] javaEntries = getJavaEntries(jarfile);
for (int i = 0; i < javaEntries.length; i++) {
JarEntry javaEntry = javaEntries[i];
String className = getClassName(javaEntry);
FileOutputStream out = null;
try {
File outFile = new File(outDir.getAbsolutePath() + File.separator + className);
// System.out.println("outfile name = " + outFile.getAbsolutePath());
outFile.getParentFile().mkdirs();
out = new FileOutputStream(outFile);
extract(jarfile, javaEntry, out);
} finally {
if (out != null) {
out.close();
}
}
}
}
Aggregations