List of usage examples for java.util.zip ZipInputStream read
public int read() throws IOException
From source file:com.visural.stereotyped.ui.service.StereotypeServiceImpl.java
public ComponentLibrary readComponentLibrary(String name) { File jar = new File(getComponentJarsPath() + "/" + name); if (jar.exists()) { ZipInputStream zis = null; try {// ww w . j a v a 2 s . co m ComponentLibrary cl = new ComponentLibrary(jar.getName(), new HashSet(), new HashMap()); File ovrDir = getOverrideLibPath(cl); zis = new ZipInputStream(new FileInputStream(jar)); ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { if (!ze.isDirectory()) { if (!ze.getName().endsWith(".class")) { // check for override first File ovr = new File(ovrDir.getCanonicalPath() + "/" + ze.getName()); if (ovr.exists()) { byte[] data = IOUtil.fileToByteArray(ovr.getCanonicalPath()); cl.getTemplate().put(ze.getName(), new Binary(data, true)); } else { // no override, read from JAR ByteArrayOutputStream baos = new ByteArrayOutputStream(); int r; while ((r = zis.read()) != -1) { baos.write(r); } cl.getTemplate().put(ze.getName(), new Binary(baos.toByteArray())); } } else { Class c = getComponentClassWithName(ze.getName() .substring(0, ze.getName().lastIndexOf(".class")).replace("/", ".")); if (c != null) { cl.getComponents().add(c); } } } } addOverrideFiles(ovrDir.getAbsolutePath(), cl, ovrDir); return cl; } catch (IOException e) { throw new IllegalStateException(e); } finally { if (zis != null) { try { zis.close(); } catch (IOException ex) { Logger.getLogger(StereotypeServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } } } else { throw new IllegalArgumentException("Library " + name + " does not exist."); } }
From source file:org.openbravo.erpCommon.modules.ImportModule.java
/** * Reads an ZipInputStream and returns it as a ByteArrayInputStream * //w w w .ja va2 s . c om * @throws Exception */ private ByteArrayInputStream getCurrentEntryStream(ZipInputStream obxInputStream) throws Exception { final ByteArrayOutputStream fout = new ByteArrayOutputStream(); for (int c = obxInputStream.read(); c != -1; c = obxInputStream.read()) { fout.write(c); } fout.close(); final ByteArrayInputStream ba = new ByteArrayInputStream(fout.toByteArray()); return ba; }
From source file:org.openremote.controller.service.Deployer.java
/** * Extracts an OpenRemote deployment archive into a given target file directory. * * @param inputStream Input stream for reading the ZIP archive. Note that this method will * attempt to close the stream on exiting. * * @param targetDir URI that points to the root directory where the extracted files should * be placed. Note that the URI must be an absolute file URI. * * @throws ConfigurationException If target file URI cannot be resolved, or if the target * file path does not exist * * @throws IOException If there was an unrecovable I/O error reading or extracting * the ZIP archive. Note that errors on individual files within * the archive may not generate exceptions but be logged as * errors or warnings instead. *///from w ww . j av a2 s . com private void unzip(InputStream inputStream, URI targetDir) throws ConfigurationException, IOException { if (targetDir == null || targetDir.getPath().equals("") || !targetDir.isAbsolute()) { throw new ConfigurationException( "Target dir must be absolute file: protocol URI, got '" + targetDir + +'.'); } File checkedTargetDir = new File(targetDir); if (!checkedTargetDir.exists()) { throw new ConfigurationException("The path ''{0}'' doesn't exist.", targetDir); } ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream)); ZipEntry zipEntry = null; BufferedOutputStream fileOutputStream = null; try { while ((zipEntry = zipInputStream.getNextEntry()) != null) { if (zipEntry.isDirectory()) { continue; } try { URI extractFileURI = targetDir.resolve(new URI(null, null, zipEntry.getName(), null)); log.debug("Resolved URI to ''{0}''", extractFileURI); File zippedFile = new File(extractFileURI); log.debug("Attempting to extract ''{0}'' to ''{1}''.", zipEntry, zippedFile); try { fileOutputStream = new BufferedOutputStream(new FileOutputStream(zippedFile)); int b; while ((b = zipInputStream.read()) != -1) { fileOutputStream.write(b); } } catch (FileNotFoundException e) { log.error("Could not extract ''{0}'' -- file ''{1}'' could not be created : {2}", e, zipEntry.getName(), zippedFile, e.getMessage()); } catch (IOException e) { log.warn("Zip extraction of ''{0}'' to ''{1}'' failed : {2}", e, zipEntry, zippedFile, e.getMessage()); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); log.debug("Extraction of ''{0}'' to ''{1}'' completed.", zipEntry, zippedFile); } catch (Throwable t) { log.warn("Failed to close file ''{0}'' : {1}", t, zippedFile, t.getMessage()); } } if (zipInputStream != null) { if (zipEntry != null) { try { zipInputStream.closeEntry(); } catch (IOException e) { log.warn("Failed to close ZIP file entry ''{0}'' : {1}", e, zipEntry, e.getMessage()); } } } } } catch (URISyntaxException e) { log.warn("Cannot extract {0} from zip : {1}", e, zipEntry, e.getMessage()); } } } finally { try { if (zipInputStream != null) { zipInputStream.close(); } } catch (IOException e) { log.warn("Failed to close zip file : {0}", e, e.getMessage()); } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { log.warn("Failed to close file : {0}", e, e.getMessage()); } } } }
From source file:org.sakaiproject.metaobj.shared.mgt.impl.StructuredArtifactDefinitionManagerImpl.java
protected void processFile(ZipEntry currentEntry, ZipInputStream zis, Hashtable fileMap, ContentCollection fileParent) throws IOException { File file = new File(currentEntry.getName()); // Unclear what the original intention is of checking for a files great-grandparent for mime-type // but for now we'll make sure grand-parent exists to avoid throwing NPE. // In testing, NPE was thrown for __MACOSX files if (file.getParentFile() == null || file.getParentFile().getParentFile() == null || file.getParentFile().getParentFile().getParentFile() == null) { logger.warn("StructuredArtifactDefinitionManagerImpl.processFile() found unexpected file " + currentEntry.getName()); return;//from ww w.j ava2 s. c o m } MimeType mimeType = new MimeType(file.getParentFile().getParentFile().getParentFile().getName(), file.getParentFile().getParentFile().getName()); String contentType = mimeType.getValue(); Id oldId = getIdManager().getId(file.getParentFile().getName()); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); int c = zis.read(); while (c != -1) { bos.write(c); c = zis.read(); } String fileName = findUniqueFileName(fileParent.getId(), file.getName()); ResourcePropertiesEdit resourceProperties = getContentHosting().newResourceProperties(); resourceProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, fileName); ContentResource /*Edit*/ resource; resource = getContentHosting().addResource(fileParent.getId() + fileName, contentType, bos.toByteArray(), resourceProperties, NotificationService.NOTI_NONE); Id newId = getIdManager().getId(getContentHosting().getUuid(resource.getId())); fileMap.put(oldId, newId); } catch (Exception exp) { logger.error(".processFile", exp); } }
From source file:com.cloudera.whirr.cm.server.impl.CmServerImpl.java
@Override @CmServerCommandMethod(name = "client") public boolean getServiceConfigs(final CmServerCluster cluster, final File directory) throws CmServerException { final AtomicBoolean executed = new AtomicBoolean(false); try {/*from w ww . j a v a 2 s. com*/ if (isProvisioned(cluster)) { logger.logOperation("GetConfig", new CmServerLogSyncCommand() { @Override public void execute() throws IOException { for (ApiService apiService : apiResourceRootV3.getClustersResource() .getServicesResource(getName(cluster)).readServices(DataView.SUMMARY)) { CmServerServiceType type = CmServerServiceType.valueOfId(apiService.getType()); if (type.equals(CmServerServiceType.HDFS) || type.equals(CmServerServiceType.MAPREDUCE) || type.equals(CmServerServiceType.YARN) || type.equals(CmServerServiceType.HBASE) || versionApi >= 4 && type.equals(CmServerServiceType.HIVE) || versionApi >= 5 && type.equals(CmServerServiceType.SOLR)) { ZipInputStream configInputZip = null; try { InputStreamDataSource configInput = apiResourceRootV3.getClustersResource() .getServicesResource(getName(cluster)) .getClientConfig(apiService.getName()); if (configInput != null) { configInputZip = new ZipInputStream(configInput.getInputStream()); ZipEntry configInputZipEntry = null; while ((configInputZipEntry = configInputZip.getNextEntry()) != null) { String configFile = configInputZipEntry.getName(); if (configFile.contains(File.separator)) { configFile = configFile.substring( configFile.lastIndexOf(File.separator), configFile.length()); } directory.mkdirs(); BufferedWriter configOutput = null; try { int read; configOutput = new BufferedWriter( new FileWriter(new File(directory, configFile))); while (configInputZip.available() > 0) { if ((read = configInputZip.read()) != -1) { configOutput.write(read); } } } finally { configOutput.close(); } } } } finally { if (configInputZip != null) { configInputZip.close(); } } executed.set(true); } } } }); } } catch (Exception e) { throw new CmServerException("Failed to get cluster config", e); } return executed.get(); }
From source file:org.ejbca.ui.web.admin.certprof.CertProfilesBean.java
public void importProfilesFromZip(byte[] filebuffer) throws CertificateProfileExistsException, AuthorizationDeniedException, NumberFormatException, IOException { if (filebuffer.length == 0) { throw new IllegalArgumentException("No input file"); }//from www .ja v a2 s.co m String importedFiles = ""; String ignoredFiles = ""; int nrOfFiles = 0; ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(filebuffer)); ZipEntry ze = zis.getNextEntry(); if (ze == null) { String msg = uploadFile.getName() + " is not a zip file."; log.info(msg); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, null)); return; } do { nrOfFiles++; String filename = ze.getName(); if (log.isDebugEnabled()) { log.debug("Importing file: " + filename); } if (ignoreFile(filename)) { ignoredFiles += filename + ", "; continue; } try { filename = URLDecoder.decode(filename, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 was not a known character encoding", e); } int index1 = filename.indexOf("_"); int index2 = filename.lastIndexOf("-"); int index3 = filename.lastIndexOf(".xml"); String profilename = filename.substring(index1 + 1, index2); int profileid = 0; try { profileid = Integer.parseInt(filename.substring(index2 + 1, index3)); } catch (NumberFormatException e) { if (log.isDebugEnabled()) { log.debug("NumberFormatException parsing certificate profile id: " + e.getMessage()); } ignoredFiles += filename + ", "; continue; } if (log.isDebugEnabled()) { log.debug("Extracted profile name '" + profilename + "' and profile ID '" + profileid + "'"); } if (ignoreProfile(filename, profilename, profileid)) { ignoredFiles += filename + ", "; continue; } if (getEjbcaWebBean().getEjb().getCertificateProfileSession() .getCertificateProfile(profileid) != null) { log.warn("Certificate profile id '" + profileid + "' already exist in database. Adding with a new profile id instead."); profileid = -1; // means we should create a new id when adding the cert profile } byte[] filebytes = new byte[102400]; int i = 0; while ((zis.available() == 1) && (i < filebytes.length)) { filebytes[i++] = (byte) zis.read(); } final CertificateProfile certificateProfile = getCertProfileFromByteArray(profilename, filebytes); if (certificateProfile == null) { String msg = "Faulty XML file '" + filename + "'. Failed to read Certificate Profile."; log.info(msg + " Ignoring file."); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, null)); continue; } certificateProfile.setAvailableCAs(getEjbcaWebBean().getInformationMemory().getAuthorizedCAIds()); getEjbcaWebBean().getEjb().getCertificateProfileSession().addCertificateProfile(getAdmin(), profilename, certificateProfile); getEjbcaWebBean().getInformationMemory().certificateProfilesEdited(); importedFiles += filename + ", "; log.info("Added Certificate profile: " + profilename); } while ((ze = zis.getNextEntry()) != null); zis.closeEntry(); zis.close(); String msg = uploadFile.getName() + " contained " + nrOfFiles + " files. "; log.info(msg); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null)); if (StringUtils.isNotEmpty(importedFiles)) { importedFiles = importedFiles.substring(0, importedFiles.length() - 2); } msg = "Imported Certificate Profiles from files: " + importedFiles; if (log.isDebugEnabled()) { log.debug(msg); } FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null)); if (StringUtils.isNotEmpty(ignoredFiles)) { ignoredFiles = ignoredFiles.substring(0, ignoredFiles.length() - 2); } msg = "Ignored files: " + ignoredFiles; if (log.isDebugEnabled()) { log.debug(msg); } FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null)); }
From source file:org.ejbca.ui.web.admin.rainterface.RAInterfaceBean.java
public String importProfilesFromZip(byte[] filebuffer) { if (log.isTraceEnabled()) { log.trace(">importProfiles(): " + importedProfileName + " - " + filebuffer.length + " bytes"); }//from w ww . j av a 2s .c o m String retmsg = ""; String faultXMLmsg = ""; if (StringUtils.isEmpty(importedProfileName) || filebuffer.length == 0) { retmsg = "Error: No input file"; log.error(retmsg); return retmsg; } int importedFiles = 0; int ignoredFiles = 0; int nrOfFiles = 0; try { ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(filebuffer)); ZipEntry ze = zis.getNextEntry(); if (ze == null) { retmsg = "Error: Expected a zip file. '" + importedProfileName + "' is not a zip file."; log.error(retmsg); return retmsg; } do { nrOfFiles++; String filename = ze.getName(); if (log.isDebugEnabled()) { log.debug("Importing file: " + filename); } if (ignoreFile(filename)) { ignoredFiles++; continue; } String profilename; filename = URLDecoder.decode(filename, "UTF-8"); int index1 = filename.indexOf("_"); int index2 = filename.lastIndexOf("-"); int index3 = filename.lastIndexOf(".xml"); profilename = filename.substring(index1 + 1, index2); int profileid = 0; try { profileid = Integer.parseInt(filename.substring(index2 + 1, index3)); } catch (NumberFormatException e) { if (log.isDebugEnabled()) { log.debug("NumberFormatException parsing certificate profile id: " + e.getMessage()); } ignoredFiles++; continue; } if (log.isDebugEnabled()) { log.debug("Extracted profile name '" + profilename + "' and profile ID '" + profileid + "'"); } if (ignoreProfile(filename, profilename, profileid)) { ignoredFiles++; continue; } if (endEntityProfileSession.getEndEntityProfile(profileid) != null) { int newprofileid = endEntityProfileSession.findFreeEndEntityProfileId(); log.warn("Entity profileid '" + profileid + "' already exist in database. Using " + newprofileid + " instead."); profileid = newprofileid; } byte[] filebytes = new byte[102400]; int i = 0; while ((zis.available() == 1) && (i < filebytes.length)) { filebytes[i++] = (byte) zis.read(); } EndEntityProfile eprofile = getEEProfileFromByteArray(profilename, filebytes); if (eprofile == null) { String msg = "Faulty XML file '" + filename + "'. Failed to read End Entity Profile."; log.info(msg + " Ignoring file."); ignoredFiles++; faultXMLmsg += filename + ", "; continue; } profiles.addEndEntityProfile(profilename, eprofile); importedFiles++; log.info("Added EndEntity profile: " + profilename); } while ((ze = zis.getNextEntry()) != null); zis.closeEntry(); zis.close(); } catch (UnsupportedEncodingException e) { retmsg = "Error: UTF-8 was not a known character encoding."; log.error(retmsg, e); return retmsg; } catch (IOException e) { log.error(e); retmsg = "Error: " + e.getLocalizedMessage(); return retmsg; } catch (AuthorizationDeniedException e) { log.error(e); retmsg = "Error: " + e.getLocalizedMessage(); return retmsg; } catch (EndEntityProfileExistsException e) { log.error(e); retmsg = "Error: " + e.getLocalizedMessage(); return retmsg; } if (StringUtils.isNotEmpty(faultXMLmsg)) { faultXMLmsg = faultXMLmsg.substring(0, faultXMLmsg.length() - 2); retmsg = "Faulty XML files: " + faultXMLmsg + ". " + importedFiles + " profiles were imported."; } else { retmsg = importedProfileName + " contained " + nrOfFiles + " files. " + importedFiles + " EndEntity Profiles were imported and " + ignoredFiles + " files were ignored."; } log.info(retmsg); return retmsg; }