use of java.util.zip.ZipException in project webtools.sourceediting by eclipse.
the class JarUtilities method getEntryNames.
/**
* @param jarFilename
* the location of the zip file
* @param excludeDirectories
* whether to not include directories in the results
* @return a string array containing the entry paths to every file in the
* zip file at this location, excluding directories if indicated
*/
public static String[] getEntryNames(String jarFilename, boolean excludeDirectories) {
ZipFile jarfile = null;
List entryNames = new ArrayList();
File f = new File(jarFilename);
if (f.exists() && f.canRead()) {
try {
jarfile = new ZipFile(f);
Enumeration entries = jarfile.entries();
while (entries.hasMoreElements()) {
ZipEntry z = (ZipEntry) entries.nextElement();
if (!(z.isDirectory() && excludeDirectories))
entryNames.add(z.getName());
}
} catch (ZipException zExc) {
// $NON-NLS-1$ //$NON-NLS-2$
Logger.log(Logger.WARNING_DEBUG, "JarUtilities ZipException: " + jarFilename + " " + zExc.getMessage());
} catch (IOException ioExc) {
// no cleanup can be done
} finally {
closeJarFile(jarfile);
}
}
String[] names = (String[]) entryNames.toArray(new String[0]);
return names;
}
use of java.util.zip.ZipException in project maven-plugins by apache.
the class EarMojo method changeManifestClasspath.
private void changeManifestClasspath(EarModule module, File original, JavaEEVersion javaEEVersion) throws MojoFailureException {
try {
File workDirectory;
// Handle the case that the destination might be a directory (project-038)
if (original.isFile()) {
// Create a temporary work directory
// MEAR-167 use uri as directory to prevent merging of artifacts with the same artifactId
workDirectory = new File(new File(getTempFolder(), "temp"), module.getUri());
workDirectory.mkdirs();
getLog().debug("Created a temporary work directory: " + workDirectory.getAbsolutePath());
// Unpack the archive to a temporary work directory
zipUnArchiver.setSourceFile(original);
zipUnArchiver.setDestDirectory(workDirectory);
zipUnArchiver.extract();
} else {
workDirectory = original;
}
// Create a META-INF/MANIFEST.MF file if it doesn't exist (project-038)
File metaInfDirectory = new File(workDirectory, "META-INF");
boolean newMetaInfCreated = metaInfDirectory.mkdirs();
if (newMetaInfCreated) {
// CHECKSTYLE_OFF: LineLength
getLog().debug("This project did not have a META-INF directory before, so a new directory was created.");
// CHECKSTYLE_ON: LineLength
}
File newCreatedManifestFile = new File(metaInfDirectory, "MANIFEST.MF");
boolean newManifestCreated = newCreatedManifestFile.createNewFile();
if (newManifestCreated) {
// CHECKSTYLE_OFF: LineLength
getLog().debug("This project did not have a META-INF/MANIFEST.MF file before, so a new file was created.");
// CHECKSTYLE_ON: LineLength
}
// Read the manifest from disk
Manifest mf = new Manifest(new FileInputStream(newCreatedManifestFile));
Attribute classPath = mf.getMainSection().getAttribute("Class-Path");
List<String> classPathElements = new ArrayList<String>();
if (classPath != null) {
classPathElements.addAll(Arrays.asList(classPath.getValue().split(" ")));
} else {
classPath = new Attribute("Class-Path", "");
}
// Remove JAR modules
for (JarModule jm : getAllJarModules()) {
if (module.getLibDir() != null) {
// MEAR-189:
// We use the original name, cause in case of fileNameMapping to no-version/full
// we could not not delete it and it will end up in the resulting EAR and the WAR
// will not be cleaned up.
// CHECKSTYLE_OFF: LineLength
File artifact = new File(new File(workDirectory, module.getLibDir()), module.getArtifact().getFile().getName());
// FIXME: Need to check this based on the new name mapping.!
if (!artifact.exists()) {
getLog().debug("module does not exist with original file name.");
artifact = new File(new File(workDirectory, module.getLibDir()), jm.getBundleFileName());
getLog().debug("Artifact with mapping:" + artifact.getAbsolutePath());
}
if (!artifact.exists()) {
getLog().debug("Artifact with mapping does not exist.");
artifact = new File(new File(workDirectory, module.getLibDir()), jm.getArtifact().getFile().getName());
getLog().debug("Artifact with orignal file name:" + artifact.getAbsolutePath());
}
if (artifact.exists()) {
getLog().debug(" -> Artifact to delete: " + artifact);
if (!artifact.delete()) {
getLog().error("Could not delete '" + artifact + "'");
}
}
}
}
// Modify the classpath entries in the manifest
for (EarModule o : getModules()) {
if (o instanceof JarModule) {
JarModule jm = (JarModule) o;
if (classPathElements.contains(jm.getBundleFileName())) {
classPathElements.set(classPathElements.indexOf(jm.getBundleFileName()), jm.getUri());
} else {
if (!skipClassPathModification) {
classPathElements.add(jm.getUri());
} else {
if (javaEEVersion.lt(JavaEEVersion.FIVE) || defaultLibBundleDir == null) {
classPathElements.add(jm.getUri());
}
}
}
}
}
classPath.setValue(StringUtils.join(classPathElements.iterator(), " "));
mf.getMainSection().addConfiguredAttribute(classPath);
// Write the manifest to disk
PrintWriter pw = new PrintWriter(newCreatedManifestFile);
mf.write(pw);
pw.close();
if (original.isFile()) {
// Pack up the archive again from the work directory
if (!original.delete()) {
getLog().error("Could not delete original artifact file " + original);
}
getLog().debug("Zipping module");
zipArchiver.setDestFile(original);
zipArchiver.addDirectory(workDirectory);
zipArchiver.createArchive();
}
} catch (ManifestException e) {
throw new MojoFailureException(e.getMessage());
} catch (ZipException e) {
throw new MojoFailureException(e.getMessage());
} catch (IOException e) {
throw new MojoFailureException(e.getMessage());
} catch (ArchiverException e) {
throw new MojoFailureException(e.getMessage());
}
}
use of java.util.zip.ZipException in project maven-plugins by apache.
the class DefaultShader method addRemappedClass.
private void addRemappedClass(RelocatorRemapper remapper, JarOutputStream jos, File jar, String name, InputStream is) throws IOException, MojoExecutionException {
if (!remapper.hasRelocators()) {
try {
jos.putNextEntry(new JarEntry(name));
IOUtil.copy(is, jos);
} catch (ZipException e) {
getLogger().debug("We have a duplicate " + name + " in " + jar);
}
return;
}
ClassReader cr = new ClassReader(is);
// We don't pass the ClassReader here. This forces the ClassWriter to rebuild the constant pool.
// Copying the original constant pool should be avoided because it would keep references
// to the original class names. This is not a problem at runtime (because these entries in the
// constant pool are never used), but confuses some tools such as Felix' maven-bundle-plugin
// that use the constant pool to determine the dependencies of a class.
ClassWriter cw = new ClassWriter(0);
final String pkg = name.substring(0, name.lastIndexOf('/') + 1);
ClassVisitor cv = new ClassRemapper(cw, remapper) {
@Override
public void visitSource(final String source, final String debug) {
if (source == null) {
super.visitSource(source, debug);
} else {
final String fqSource = pkg + source;
final String mappedSource = remapper.map(fqSource);
final String filename = mappedSource.substring(mappedSource.lastIndexOf('/') + 1);
super.visitSource(filename, debug);
}
}
};
try {
cr.accept(cv, ClassReader.EXPAND_FRAMES);
} catch (Throwable ise) {
throw new MojoExecutionException("Error in ASM processing class " + name, ise);
}
byte[] renamedClass = cw.toByteArray();
// Need to take the .class off for remapping evaluation
String mappedName = remapper.map(name.substring(0, name.indexOf('.')));
try {
// Now we put it back on so the class file is written out with the right extension.
jos.putNextEntry(new JarEntry(mappedName + ".class"));
IOUtil.copy(renamedClass, jos);
} catch (ZipException e) {
getLogger().debug("We have a duplicate " + mappedName + " in " + jar);
}
}
use of java.util.zip.ZipException in project dex2jar by pxb1988.
the class ZipFile method readCentralDir.
/**
* Find the central directory and read the contents.
*
* <p>
* The central directory can be followed by a variable-length comment field, so we have to scan through it
* backwards. The comment is at most 64K, plus we have 18 bytes for the end-of-central-dir stuff itself, plus
* apparently sometimes people throw random junk on the end just for the fun of it.
*
* <p>
* This is all a little wobbly. If the wrong value ends up in the EOCD area, we're hosed. This appears to be the way
* that everybody handles it though, so we're in good company if this fails.
*/
private void readCentralDir() throws IOException {
ByteBuffer raf = this.raf;
// Scan back, looking for the End Of Central Directory field. If the zip file doesn't
// have an overall comment (unrelated to any per-entry comments), we'll hit the EOCD
// on the first try.
// No need to synchronize raf here -- we only do this when we first open the zip file.
long scanOffset = raf.limit() - ENDHDR;
if (scanOffset < 0) {
throw new ZipException("File too short to be a zip file: " + raf.limit());
}
// not check Magic
// raf.position(0);
// final int headerMagic = raf.getInt();
// if (headerMagic != LOCSIG) {
// throw new ZipException("Not a zip archive");
// }
long stopOffset = scanOffset - 65536;
if (stopOffset < 0) {
stopOffset = 0;
}
while (true) {
raf.position((int) scanOffset);
if (raf.getInt() == ENDSIG) {
break;
}
scanOffset--;
if (scanOffset < stopOffset) {
throw new ZipException("End Of Central Directory signature not found");
}
}
// Read the End Of Central Directory. ENDHDR includes the signature bytes,
// which we've already read.
// Pull out the information we need.
int diskNumber = raf.getShort() & 0xffff;
int diskWithCentralDir = raf.getShort() & 0xffff;
int numEntries = raf.getShort() & 0xffff;
int totalNumEntries = raf.getShort() & 0xffff;
// Ignore centralDirSize.
skip(raf, 4);
long centralDirOffset = ((long) raf.getInt()) & 0xffffffffL;
int commentLength = raf.getShort() & 0xffff;
if (numEntries != totalNumEntries || diskNumber != 0 || diskWithCentralDir != 0) {
throw new ZipException("Spanned archives not supported");
}
boolean skipCommentsAndExtra = true;
if (commentLength > 0) {
if (commentLength > raf.remaining()) {
System.err.println("WARN: the zip comment exceed the zip content");
} else {
if (skipCommentsAndExtra) {
skip(raf, commentLength);
} else {
byte[] commentBytes = new byte[commentLength];
raf.get(commentBytes);
comment = new String(commentBytes, 0, commentBytes.length, StandardCharsets.UTF_8);
}
}
}
// Seek to the first CDE and read all entries.
// We have to do this now (from the constructor) rather than lazily because the
// public API doesn't allow us to throw IOException except from the constructor
// or from getInputStream.
ByteBuffer buf = (ByteBuffer) raf.duplicate().order(ByteOrder.LITTLE_ENDIAN).position((int) centralDirOffset);
entries = new ArrayList<>(numEntries);
for (int i = 0; i < numEntries; ++i) {
ZipEntry newEntry = new ZipEntry(buf, skipCommentsAndExtra);
if (newEntry.localHeaderRelOffset >= centralDirOffset) {
// Ignore the entry
// throw new ZipException("Local file header offset is after central directory");
} else {
entries.add(newEntry);
}
}
}
use of java.util.zip.ZipException in project Engine by VoltzEngine-Project.
the class FixedTechneModel method loadTechneModel.
// TODO break into smaller methods
private void loadTechneModel(InputStream stream) throws ModelFormatException {
try {
ZipInputStream zipInput = new ZipInputStream(stream);
ZipEntry entry;
while ((entry = zipInput.getNextEntry()) != null) {
byte[] data = new byte[(int) entry.getSize()];
// For some reason, using read(byte[]) makes reading stall upon reaching a 0x1E byte
int i = 0;
while (zipInput.available() > 0 && i < data.length) {
data[i++] = (byte) zipInput.read();
}
zipContents.put(entry.getName(), data);
}
byte[] modelXml = zipContents.get("model.xml");
if (modelXml == null) {
throw new ModelFormatException("Model " + fileName + " contains no model.xml file");
}
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new ByteArrayInputStream(modelXml));
NodeList nodeListTechne = document.getElementsByTagName("Techne");
if (nodeListTechne.getLength() < 1) {
throw new ModelFormatException("Model " + fileName + " contains no Techne tag");
}
NodeList nodeListModel = document.getElementsByTagName("Model");
if (nodeListModel.getLength() < 1) {
throw new ModelFormatException("Model " + fileName + " contains no Model tag");
}
NamedNodeMap modelAttributes = nodeListModel.item(0).getAttributes();
if (modelAttributes == null) {
throw new ModelFormatException("Model " + fileName + " contains a Model tag with no attributes");
}
Node modelTexture = modelAttributes.getNamedItem("texture");
if (modelTexture != null) {
// TODO texture = modelTexture.getTextContent();
}
NodeList textureSize = document.getElementsByTagName("TextureSize");
for (int i = 0; i < textureSize.getLength(); i++) {
String size = textureSize.item(i).getTextContent();
String[] textureDimensions = size.split(",");
textureWidth = Integer.parseInt(textureDimensions[0]);
textureHeight = Integer.parseInt(textureDimensions[1]);
}
NodeList shapes = document.getElementsByTagName("Shape");
for (int i = 0; i < shapes.getLength(); i++) {
Node shape = shapes.item(i);
NamedNodeMap shapeAttributes = shape.getAttributes();
if (shapeAttributes == null) {
throw new ModelFormatException("Shape #" + (i + 1) + " in " + fileName + " has no attributes");
}
Node name = shapeAttributes.getNamedItem("name");
String shapeName = null;
if (name != null) {
shapeName = name.getNodeValue();
}
if (shapeName == null) {
shapeName = "Shape #" + (i + 1);
}
String shapeType = null;
Node type = shapeAttributes.getNamedItem("type");
if (type != null) {
shapeType = type.getNodeValue();
}
if (shapeType != null && !cubeTypes.contains(shapeType)) {
FMLLog.warning("Model shape [" + shapeName + "] in " + fileName + " is not a cube, ignoring");
continue;
}
try {
boolean mirrored = false;
String[] offset = new String[3];
String[] position = new String[3];
String[] rotation = new String[3];
String[] size = new String[3];
String[] textureOffset = new String[2];
NodeList shapeChildren = shape.getChildNodes();
for (int j = 0; j < shapeChildren.getLength(); j++) {
Node shapeChild = shapeChildren.item(j);
String shapeChildName = shapeChild.getNodeName();
String shapeChildValue = shapeChild.getTextContent();
if (shapeChildValue != null) {
shapeChildValue = shapeChildValue.trim();
switch(shapeChildName) {
case "IsMirrored":
mirrored = !shapeChildValue.equals("False");
break;
case "Offset":
offset = shapeChildValue.split(",");
break;
case "Position":
position = shapeChildValue.split(",");
break;
case "Rotation":
rotation = shapeChildValue.split(",");
break;
case "Size":
size = shapeChildValue.split(",");
break;
case "TextureOffset":
textureOffset = shapeChildValue.split(",");
break;
}
}
}
// That's what the ModelBase subclassing is needed for
ModelRenderer cube = new ModelRenderer(this, shapeName);
cube.setTextureOffset(Integer.parseInt(textureOffset[0]), Integer.parseInt(textureOffset[1]));
cube.mirror = mirrored;
cube.addBox(Float.parseFloat(offset[0]), Float.parseFloat(offset[1]), Float.parseFloat(offset[2]), Integer.parseInt(size[0]), Integer.parseInt(size[1]), Integer.parseInt(size[2]));
cube.setRotationPoint(Float.parseFloat(position[0]), Float.parseFloat(position[1]) - 16, Float.parseFloat(position[2]));
cube.rotateAngleX = (float) Math.toRadians(Float.parseFloat(rotation[0]));
cube.rotateAngleY = (float) Math.toRadians(Float.parseFloat(rotation[1]));
cube.rotateAngleZ = (float) Math.toRadians(Float.parseFloat(rotation[2]));
if (parts.containsKey(shapeName)) {
throw new ModelFormatException("Model contained duplicate part name: '" + shapeName + "' node #" + i);
}
parts.put(shapeName, cube);
} catch (NumberFormatException e) {
FMLLog.warning("Model shape [" + shapeName + "] in " + fileName + " contains malformed integers within its data, ignoring");
e.printStackTrace();
}
}
} catch (ZipException e) {
throw new ModelFormatException("Model " + fileName + " is not a valid zip file");
} catch (IOException e) {
throw new ModelFormatException("Model " + fileName + " could not be read", e);
} catch (ParserConfigurationException e) {
// hush
} catch (SAXException e) {
throw new ModelFormatException("Model " + fileName + " contains invalid XML", e);
}
}
Aggregations