List of usage examples for java.util.zip ZipInputStream read
public int read() throws IOException
From source file:reconcile.hbase.mapreduce.ZipInputFormat.java
private static byte[] read(String entry, ZipInputStream zis) { ArrayList<byte[]> dataArray = new ArrayList<byte[]>(); byte[] current = null; int i = 0;// w w w. ja va 2s . com int n = 0; try { while (zis.available() == 1) { if (n % bufSize == 0) { current = new byte[bufSize]; dataArray.add(current); i = 0; } current[i] = (byte) zis.read(); ++n; ++i; } } catch (IOException e) { LOG.error("failure reading zip entry(" + entry + ")"); e.printStackTrace(); return null; } --n; // Copy multiple buffers into single large buffer byte[] data = new byte[n]; i = 0; for (byte[] buffer : dataArray) { int copyLength = bufSize; if ((i + copyLength) > n) { copyLength = n - i; } for (int j = 0; j < copyLength; ++j) { data[i] = buffer[j]; ++i; } } LOG.info("Read bytes(" + n + ") from entry (" + entry + ")"); LOG.debug("Read value(" + Bytes.toString(data) + ") from entry (" + entry + ")"); return data; }
From source file:org.openremote.beehive.utils.ZipUtil.java
public static boolean unzip(InputStream inputStream, String targetDir, String filterdFileName) { ZipInputStream zipInputStream = new ZipInputStream(inputStream); ZipEntry zipEntry;/* w w w. ja v a 2s. c o m*/ FileOutputStream fileOutputStream = null; File zippedFile = null; try { while ((zipEntry = zipInputStream.getNextEntry()) != null) { if (!zipEntry.isDirectory()) { if (filterdFileName != null && !zipEntry.getName().equals(filterdFileName)) { continue; } targetDir = targetDir.endsWith("/") || targetDir.endsWith("\\") ? targetDir : targetDir + "/"; zippedFile = new File(targetDir, zipEntry.getName()); FileUtils.deleteQuietly(zippedFile); FileUtils.touch(zippedFile); fileOutputStream = new FileOutputStream(zippedFile); int b; while ((b = zipInputStream.read()) != -1) { fileOutputStream.write(b); } fileOutputStream.close(); } } } catch (IOException e) { logger.error("Can't unzip file to " + zippedFile.getPath(), e); return false; } finally { try { zipInputStream.closeEntry(); if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e) { logger.error("Error while closing stream.", e); } } return true; }
From source file:de.spiritcroc.ownlog.FileHelper.java
public static ImportFiles unpackImport(Context context, InputStream inputStream) { File importingDir = new File(context.getCacheDir(), context.getString(R.string.import_file_dir)); rmdir(importingDir);/*w ww . ja v a 2 s .c o m*/ importingDir.mkdirs(); ZipInputStream in = new ZipInputStream(inputStream); ZipEntry entry; try { while ((entry = in.getNextEntry()) != null) { String path = importingDir.getAbsolutePath() + File.separator + entry.getName(); if (DEBUG) Log.d(TAG, "Unzipping path: " + path); File f = new File(path); if (entry.isDirectory()) { if (!f.isDirectory()) { f.mkdirs(); } } else { f.getParentFile().mkdirs(); f.createNewFile(); FileOutputStream out = new FileOutputStream(path, false); try { int size; while ((size = in.read()) != -1) { out.write(size); } in.closeEntry(); } finally { try { out.close(); } catch (Exception e) { e.printStackTrace(); } } } } } catch (Exception e) { Log.w(TAG, "Import failed", e); return null; } File logDbFile = new File(importingDir, context.getString(R.string.import_file_db)); File attachmentsDir = new File(importingDir, context.getString(R.string.import_file_attachments)); if (logDbFile.exists()) { return new ImportFiles(logDbFile, attachmentsDir); } else { Log.w(TAG, "Import failed: database not found"); return null; } }
From source file:com.baasbox.service.dbmanager.DbManagerService.java
public static void importDb(String appcode, ZipInputStream zis) throws FileFormatException, Exception { File newFile = null;/*from w w w . j a va2 s .c o m*/ FileOutputStream fout = null; try { //get the zipped file list entry ZipEntry ze = zis.getNextEntry(); if (ze == null) throw new FileFormatException("Looks like the uploaded file is not a valid export."); if (ze.isDirectory()) { ze = zis.getNextEntry(); } if (ze != null) { newFile = File.createTempFile("export", ".json"); fout = new FileOutputStream(newFile); IOUtils.copy(zis, fout, BBConfiguration.getImportExportBufferSize()); fout.close(); } else { throw new FileFormatException("Looks like the uploaded file is not a valid export."); } ZipEntry manifest = zis.getNextEntry(); if (manifest != null) { File manifestFile = File.createTempFile("manifest", ".txt"); fout = new FileOutputStream(manifestFile); for (int c = zis.read(); c != -1; c = zis.read()) { fout.write(c); } fout.close(); String manifestContent = FileUtils.readFileToString(manifestFile); manifestFile.delete(); Pattern p = Pattern.compile(BBInternalConstants.IMPORT_MANIFEST_VERSION_PATTERN); Matcher m = p.matcher(manifestContent); if (m.matches()) { String version = m.group(1); if (version.compareToIgnoreCase("0.6.0") < 0) { //we support imports from version 0.6.0 throw new FileFormatException(String.format( "Current baasbox version(%s) is not compatible with import file version(%s)", BBConfiguration.getApiVersion(), version)); } else { if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Version : " + version + " is valid"); } } else { throw new FileFormatException("The manifest file does not contain a version number"); } } else { throw new FileFormatException("Looks like zip file does not contain a manifest file"); } if (newFile != null) { DbHelper.importData(appcode, newFile); zis.closeEntry(); zis.close(); } else { throw new FileFormatException("The import file is empty"); } } catch (FileFormatException e) { BaasBoxLogger.error(ExceptionUtils.getMessage(e)); throw e; } catch (Throwable e) { BaasBoxLogger.error(ExceptionUtils.getStackTrace(e)); throw new Exception("There was an error handling your zip import file.", e); } finally { try { if (zis != null) { zis.close(); } if (fout != null) { fout.close(); } } catch (IOException e) { // Nothing to do here } } }
From source file:org.apache.nutch.parse.zip.ZipTextExtractor.java
public String extractText(InputStream input, String url, List outLinksList) throws IOException { String resultText = ""; byte temp;// ww w . j a v a 2 s .co m ZipInputStream zin = new ZipInputStream(input); ZipEntry entry; while ((entry = zin.getNextEntry()) != null) { if (!entry.isDirectory()) { int size = (int) entry.getSize(); byte[] b = new byte[size]; for (int x = 0; x < size; x++) { int err = zin.read(); if (err != -1) { b[x] = (byte) err; } } String newurl = url + "/"; String fname = entry.getName(); newurl += fname; URL aURL = new URL(newurl); String base = aURL.toString(); int i = fname.lastIndexOf('.'); if (i != -1) { // Trying to resolve the Mime-Type String contentType = MIME.getMimeType(fname).getName(); try { Metadata metadata = new Metadata(); metadata.set(Response.CONTENT_LENGTH, Long.toString(entry.getSize())); metadata.set(Response.CONTENT_TYPE, contentType); Content content = new Content(newurl, base, b, contentType, metadata, this.conf); Parse parse = new ParseUtil(this.conf).parse(content).get(content.getUrl()); ParseData theParseData = parse.getData(); Outlink[] theOutlinks = theParseData.getOutlinks(); for (int count = 0; count < theOutlinks.length; count++) { outLinksList.add( new Outlink(theOutlinks[count].getToUrl(), theOutlinks[count].getAnchor())); } resultText += entry.getName() + " " + parse.getText() + " "; } catch (ParseException e) { if (LOG.isInfoEnabled()) { LOG.info("fetch okay, but can't parse " + fname + ", reason: " + e.getMessage()); } } } } } return resultText; }
From source file:org.eclipse.swordfish.p2.internal.deploy.server.RepositoryManager.java
private final File unzip(String iu, InputStream repoZipStream) throws IOException { File tempDir = new File(System.getProperty("java.io.tmpdir"), iu + "_" + new java.util.Random().nextInt()); tempDir.mkdir();//from w w w. jav a2s. c o m tempDir.deleteOnExit(); ZipInputStream zin = new ZipInputStream(repoZipStream); ZipEntry ze = null; int extracted = 0; while ((ze = zin.getNextEntry()) != null) { File outFile = new File(tempDir.getCanonicalPath(), ze.getName()); if (ze.isDirectory()) { if (!outFile.exists()) { outFile.mkdir(); outFile.deleteOnExit(); extracted++; } } else { FileOutputStream fout = new FileOutputStream(outFile); outFile.deleteOnExit(); for (int c = zin.read(); c != -1; c = zin.read()) { fout.write(c); } fout.close(); extracted++; } zin.closeEntry(); } zin.close(); if (extracted == 0) { throw new IOException("Empty or invalid archive."); } return tempDir; }
From source file:com.jlgranda.fede.ejb.mail.reader.FacturaElectronicaMailReader.java
/** * Obtiene una lista de objetos <tt>FacturaReader</tt> desde el mensaje de correo, si existe * * @param mime4jMessage/* w w w .j a va 2 s .c om*/ * @return lista de instancias instancia <tt>FacturaReader</tt> si existe la factura, null * en caso contrario */ private List<FacturaReader> handleMessage(org.apache.james.mime4j.dom.Message mime4jMessage) throws IOException, Exception { List<FacturaReader> result = new ArrayList<>(); ByteArrayOutputStream os = null; String filename = null; Factura factura = null; EmailHelper emailHelper = new EmailHelper(); if (mime4jMessage.isMultipart()) { org.apache.james.mime4j.dom.Multipart mime4jMultipart = (org.apache.james.mime4j.dom.Multipart) mime4jMessage .getBody(); emailHelper.parseBodyParts(mime4jMultipart); //Obtener la factura en los adjuntos if (emailHelper.getAttachments().isEmpty()) { //If it's single part message, just get text body String text = emailHelper.getHtmlBody().toString(); emailHelper.getTxtBody().append(text); if (mime4jMessage.getSubject().contains("Ghost")) { String url = FacturaUtil.extraerURL(emailHelper.getHtmlBody().toString(), "<a href=\"", "\" target=\"_blank\">Descarga formato XML</a>"); if (url != null) { result.add(FacturaElectronicaURLReader.getFacturaElectronica(url)); } } } else { for (Entity entity : emailHelper.getAttachments()) { filename = EmailHelper.getFilename(entity); //if (entity.getBody() instanceof BinaryBody) { if (("application/octet-stream".equalsIgnoreCase(entity.getMimeType()) || "application/xml".equalsIgnoreCase(entity.getMimeType()) || "text/xml".equalsIgnoreCase(entity.getMimeType()) || "text/plain".equalsIgnoreCase(entity.getMimeType())) && (filename != null && filename.endsWith(".xml"))) { //attachFiles += part.getFileName() + ", "; os = EmailHelper.writeBody(entity.getBody()); factura = FacturaUtil.read(os.toString()); if (factura != null) { result.add(new FacturaReader(factura, os.toString(), entity.getFilename(), mime4jMessage.getFrom().get(0).getAddress())); } } else if (("application/octet-stream".equalsIgnoreCase(entity.getMimeType()) || "aplication/xml".equalsIgnoreCase(entity.getMimeType()) || "text/xml".equalsIgnoreCase(entity.getMimeType())) && (filename != null && filename.endsWith(".zip"))) { //http://www.java2s.com/Tutorial/Java/0180__File/UnzipusingtheZipInputStream.htm os = EmailHelper.writeBody(entity.getBody()); ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(os.toByteArray())); try { ZipEntry entry = null; String tmp = null; ByteArrayOutputStream fout = null; while ((entry = zis.getNextEntry()) != null) { if (entry.getName().endsWith(".xml")) { //logger.debug("Unzipping {}", entry.getFilename()); fout = new ByteArrayOutputStream(); for (int c = zis.read(); c != -1; c = zis.read()) { fout.write(c); } tmp = new String(fout.toByteArray(), Charset.defaultCharset()); factura = FacturaUtil.read(tmp); if (factura != null) { result.add(new FacturaReader(factura, tmp, entity.getFilename())); } fout.close(); } zis.closeEntry(); } zis.close(); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(zis); } } else if ("message/rfc822".equalsIgnoreCase(entity.getMimeType())) { if (entity.getBody() instanceof org.apache.james.mime4j.message.MessageImpl) { result.addAll( handleMessage((org.apache.james.mime4j.message.MessageImpl) entity.getBody())); } } } } } else { //If it's single part message, just get text body String text = emailHelper.getTxtPart(mime4jMessage); emailHelper.getTxtBody().append(text); if (mime4jMessage.getSubject().contains("Ghost")) { String url = FacturaUtil.extraerURL(emailHelper.getHtmlBody().toString(), "<a href=\"", "\" target=\"_blank\">Descarga formato XML</a>"); if (url != null) { result.add(FacturaElectronicaURLReader.getFacturaElectronica(url)); } } } return result; }
From source file:nova.core.render.model.TechneModelProvider.java
@Override public void load(InputStream stream) { try {/*from w w w.ja v a 2 s .c o m*/ Map<String, byte[]> zipContents = new HashMap<>(); 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 RenderException("Model " + name + " 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 RenderException("Model " + name + " contains no Techne tag"); } NodeList nodeListModel = document.getElementsByTagName("Model"); if (nodeListModel.getLength() < 1) { throw new RenderException("Model " + name + " contains no Model tag"); } NamedNodeMap modelAttributes = nodeListModel.item(0).getAttributes(); if (modelAttributes == null) { throw new RenderException("Model " + name + " contains a Model tag with no attributes"); } NodeList textureSize = document.getElementsByTagName("TextureSize"); if (textureSize.getLength() == 0) throw new RenderException("Model has no texture size"); String[] textureDimensions = textureSize.item(0).getTextContent().split(","); double textureWidth = Integer.parseInt(textureDimensions[0]); double 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 RenderException("Shape #" + (i + 1) + " in " + name + " 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 && !cubeIDs.contains(shapeType)) { System.out.println( "Model shape [" + shapeName + "] in " + this.name + " is not a cube, ignoring"); continue; } 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; } } } /* Generate new models Models in Techne are based on cubes. Each cube is, by default, skewed to the side. They are not centered. Everything is scaled by a factor of 16. The y coordinate is inversed, y = 24 is the surface The z coordinate is inverted, too. */ double positionX = Double.parseDouble(position[0]) / 16d; double positionY = (16 - Double.parseDouble(position[1])) / 16d; double positionZ = -Double.parseDouble(position[2]) / 16d; double sizeX = Double.parseDouble(size[0]) / 16d; double sizeY = Double.parseDouble(size[1]) / 16d; double sizeZ = Double.parseDouble(size[2]) / 16d; double offsetX = Double.parseDouble(offset[0]) / 16d; double offsetY = -Double.parseDouble(offset[1]) / 16d; double offsetZ = -Double.parseDouble(offset[2]) / 16d; double angleX = -Math.toRadians(Double.parseDouble(rotation[0])); double angleY = Math.toRadians(Double.parseDouble(rotation[1])); double angleZ = Math.toRadians(Double.parseDouble(rotation[2])); double textureOffsetU = Double.parseDouble(textureOffset[0]); double textureOffsetV = Double.parseDouble(textureOffset[1]); CubeTextureCoordinates textureCoordinates = new TechneCubeTextureCoordinates(textureWidth, textureHeight, textureOffsetU, textureOffsetV, sizeX, sizeY, sizeZ); final String modelName = shapeName; MeshModel modelPart = new MeshModel(modelName); BlockRenderPipeline.drawCube(modelPart, offsetX, offsetY - sizeY, offsetZ - sizeZ, offsetX + sizeX, offsetY, offsetZ, textureCoordinates); MatrixStack ms = new MatrixStack(); ms.translate(positionX, positionY, positionZ); ms.rotate(Vector3D.PLUS_J, angleY); ms.rotate(Vector3D.PLUS_I, angleX); ms.rotate(Vector3D.PLUS_K, angleZ); modelPart.matrix = ms; modelPart.textureOffset = new Vector2D(Integer.parseInt(textureOffset[0]), Integer.parseInt(textureOffset[1])); if (model.children.stream().anyMatch(m -> m.name.equals(modelName))) { throw new RenderException( "Model contained duplicate part name: '" + shapeName + "' node #" + i); } model.children.add(modelPart); } } catch (ZipException e) { throw new RenderException("Model " + name + " is not a valid zip file"); } catch (IOException e) { throw new RenderException("Model " + name + " could not be read", e); } catch (SAXException e) { throw new RenderException("Model " + name + " contains invalid XML", e); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.theospi.portfolio.guidance.impl.GuidanceManagerImpl.java
protected void importAttachmentRef(ContentCollection fileParent, ZipEntry currentEntry, String siteId, ZipInputStream zis, Map attachmentMap) { File file = new File(currentEntry.getName()); MimeType mimeType = new MimeType(file.getParentFile().getParentFile().getParentFile().getName(), file.getParentFile().getParentFile().getName()); String contentType = mimeType.getValue(); String oldId = file.getParentFile().getName(); try {/*from w ww. jav a 2 s.c o m*/ ByteArrayOutputStream bos = new ByteArrayOutputStream(); int c = zis.read(); while (c != -1) { bos.write(c); c = zis.read(); } String fileId = fileParent.getId() + file.getName(); ContentResource rez = null; try { rez = getContentHostingService().getResource(fileId); } catch (IdUnusedException iduue) { logger.info(iduue); } if (rez == null) { ContentResourceEdit resource = getContentHostingService().addResource(fileId); ResourcePropertiesEdit resourceProperties = resource.getPropertiesEdit(); resourceProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, file.getName()); resource.setContent(bos.toByteArray()); resource.setContentType(contentType); getContentHostingService().commitResource(resource); rez = resource; } attachmentMap.put(oldId, rez.getReference()); } catch (Exception exp) { throw new RuntimeException(exp); } }
From source file:org.jlgranda.fede.controller.FacturaElectronicaHome.java
public void procesarUploadFile(UploadedFile file) { if (file == null) { this.addErrorMessage(I18nUtil.getMessages("action.fail"), I18nUtil.getMessages("fede.file.null")); return;/* ww w . j ava2 s . c om*/ } if (subject == null) { this.addErrorMessage(I18nUtil.getMessages("action.fail"), I18nUtil.getMessages("fede.subject.null")); return; } String xml = null; try { if (file.getFileName().endsWith(".xml")) { byte[] content = IOUtils.toByteArray(file.getInputstream()); xml = new String(content); procesarFactura(FacturaUtil.read(xml), xml, file.getFileName(), SourceType.FILE); this.addSuccessMessage(I18nUtil.getMessages("action.sucessfully"), "Su factura electrnica " + file.getFileName() + " ahora empieza a generar valor para ud!"); IOUtils.closeQuietly(file.getInputstream()); } else if (file.getFileName().endsWith(".zip")) { ZipInputStream zis = new ZipInputStream(file.getInputstream()); try { ZipEntry entry = null; ByteArrayOutputStream fout = null; while ((entry = zis.getNextEntry()) != null) { if (entry.getName().endsWith(".xml")) { //logger.debug("Unzipping {}", entry.getFilename()); fout = new ByteArrayOutputStream(); for (int c = zis.read(); c != -1; c = zis.read()) { fout.write(c); } xml = new String(fout.toByteArray(), Charset.defaultCharset()); procesarFactura(FacturaUtil.read(xml), xml, file.getFileName(), SourceType.FILE); this.addSuccessMessage(I18nUtil.getMessages("action.sucessfully"), "Su factura electrnica " + entry.getName() + " ahora empieza a generar valor para ud!"); fout.close(); } zis.closeEntry(); } zis.close(); } finally { IOUtils.closeQuietly(file.getInputstream()); IOUtils.closeQuietly(zis); } } } catch (IOException | FacturaXMLReadException e) { this.addErrorMessage(I18nUtil.getMessages("action.fail"), e.getMessage()); } }