List of usage examples for java.util.zip ZipEntry isDirectory
public boolean isDirectory()
From source file:com.headswilllol.basiclauncher.Launcher.java
public void actionPerformed(ActionEvent e) { // button was pressed if (e.getActionCommand().equals("play")) { // play button was pressed // clear dem buttons this.remove(play); this.remove(force); this.remove(noUpdate); this.remove(quit); File dir = new File(appData(), FOLDER_NAME + File.separator + "resources"); if (!downloadDir.isEmpty()) // -d flag was used dir = new File(downloadDir, FOLDER_NAME + File.separator + "resources"); dir.mkdir();/*from ww w. j a v a 2s .c o m*/ try { progress = "Downloading JSON file list..."; paintImmediately(0, 0, width, height); Downloader jsonDl = new Downloader(new URL(JSON_LOCATION), dir.getPath() + File.separator + "resources.json", "JSON file list", true); Thread jsonT = new Thread(jsonDl); // download in a separate thread so the GUI will continue to update jsonT.start(); while (jsonT.isAlive()) { } // no need for a progress bar; it's tiny JSONArray files = (JSONArray) ((JSONObject) new JSONParser().parse(new InputStreamReader( new File(dir.getPath(), "resources.json").toURI().toURL().openStream()))).get("resources"); List<String> paths = new ArrayList<String>(); for (Object obj : files) { // iterate the entries in the JSON file JSONObject jFile = (JSONObject) obj; String launch = ((String) jFile.get("launch")); // if true, resource will be used as main binary if (launch != null && launch.equals("true")) main = new File(dir, ((String) jFile.get("localPath")).replace("/", File.separator)); paths.add(((String) jFile.get("localPath")).replace("/", File.separator)); File file = new File(dir, ((String) jFile.get("localPath")).replace("/", File.separator)); boolean reacquire = false; if (!file.exists() || // files doesn't exist (allowReacquire && // allow files to be reacquired (update || // update forced // mismatch between local and remote file !jFile.get("md5").equals(md5(file.getPath()))))) { reacquire = true; if (update) System.out.println( "Update forced, so file " + jFile.get("localPath") + " must be updated"); else if (!file.exists()) System.out.println("Cannot find local copy of file " + jFile.get("localPath")); else System.out.println("MD5 checksum for file " + jFile.get("localPath") + " does not match expected value"); System.out.println("Attempting to reacquire..."); file.delete(); file.getParentFile().mkdirs(); file.createNewFile(); progress = "Downloading " + jFile.get("id"); // update the GUI paintImmediately(0, 0, width, height); Downloader dl = new Downloader(new URL((String) jFile.get("location")), dir + File.separator + ((String) jFile.get("localPath")).replace("/", File.separator), (String) jFile.get("id"), !jFile.containsKey("doNotSpoofUserAgent") || !Boolean.parseBoolean((String) jFile.get("doNotSpoofUserAgent"))); Thread th = new Thread(dl); th.start(); eSize = getFileSize(new URL((String) jFile.get("location"))) / 8; // expected file size speed = 0; // stores the current download speed lastSize = 0; // stores the size of the downloaded file the last time the GUI was updated while (th.isAlive()) { // wait but don't hang the main thread aSize = file.length() / 8; if (lastTime != -1) { // wait so the GUI isn't constantly updating if (System.currentTimeMillis() - lastTime >= SPEED_UPDATE_INTERVAL) { speed = (aSize - lastSize) / ((System.currentTimeMillis() - lastTime) / 1000) * 8; // calculate new speed lastTime = System.currentTimeMillis(); lastSize = aSize; // update the downloaded file's size } } else { speed = 0; // reset the download speed lastTime = System.currentTimeMillis(); // and the last time } paintImmediately(0, 0, width, height); } eSize = -1; aSize = -1; } if (jFile.containsKey("extract")) { // file should be unzipped HashMap<String, JSONObject> elements = new HashMap<String, JSONObject>(); for (Object ex : (JSONArray) jFile.get("extract")) { elements.put((String) ((JSONObject) ex).get("path"), (JSONObject) ex); paths.add(((String) ((JSONObject) ex).get("localPath")).replace("/", File.separator)); File f = new File(dir, ((String) ((JSONObject) ex).get("localPath")).replace("/", File.separator)); if (!f.exists() || // file doesn't exist // file isn't directory and has checksum (!f.isDirectory() && ((JSONObject) ex).get("md5") != null && // mismatch between local and remote file !md5(f.getPath()).equals((((JSONObject) ex).get("md5"))))) reacquire = true; if (((JSONObject) ex).get("id").equals("natives")) // specific to LWJGL launching natives = new File(dir, ((String) ((JSONObject) ex).get("localPath")).replace("/", File.separator)); } if (reacquire) { try { ZipFile zip = new ZipFile(new File(dir, ((String) jFile.get("localPath")).replace("/", File.separator))); @SuppressWarnings("rawtypes") Enumeration en = zip.entries(); List<String> dirs = new ArrayList<String>(); while (en.hasMoreElements()) { // iterate entries in ZIP file ZipEntry entry = (ZipEntry) en.nextElement(); boolean extract = false; // whether the entry should be extracted String parentDir = ""; if (elements.containsKey(entry.getName())) // entry is in list of files to extract extract = true; else for (String d : dirs) if (entry.getName().contains(d)) { extract = true; parentDir = d; } if (extract) { progress = "Extracting " + (elements.containsKey(entry.getName()) ? elements.get(entry.getName()).get("id") : entry.getName() .substring(entry.getName().indexOf(parentDir), entry.getName().length()) .replace("/", File.separator)); // update the GUI paintImmediately(0, 0, width, height); if (entry.isDirectory()) { if (parentDir.equals("")) dirs.add((String) elements.get(entry.getName()).get("localPath")); } else { File path = new File(dir, (parentDir.equals("")) ? ((String) elements.get(entry.getName()).get("localPath")) .replace("/", File.separator) : entry.getName() .substring(entry.getName().indexOf(parentDir), entry.getName().length()) .replace("/", File.separator)); // path to extract to if (path.exists()) path.delete(); unzip(zip, entry, path); // *zziiiip* } } } } catch (Exception ex) { ex.printStackTrace(); createExceptionLog(ex); progress = "Failed to extract files from " + jFile.get("id"); fail = "Errors occurred; see log file for details"; launcher.paintImmediately(0, 0, width, height); } } } } checkFile(dir, dir, paths); } catch (Exception ex) { // can't open resource list ex.printStackTrace(); createExceptionLog(ex); progress = "Failed to read JSON file list"; fail = "Errors occurred; see log file for details"; launcher.paintImmediately(0, 0, width, height); } launch(); } else if (e.getActionCommand().equals("force")) { force.setActionCommand("noForce"); force.setText("Will Force!"); update = true; // reset do not reacquire button noUpdate.setActionCommand("noReacquire"); noUpdate.setText("Do Not Reacquire"); allowReacquire = true; } else if (e.getActionCommand().equals("noForce")) { force.setActionCommand("force"); force.setText("Force Update"); update = false; } else if (e.getActionCommand().equals("noReacquire")) { noUpdate.setActionCommand("yesReacquire"); noUpdate.setText("Will Not Reacquire!"); allowReacquire = false; // reset force update button force.setActionCommand("force"); force.setText("Force Update"); update = false; } else if (e.getActionCommand().equals("yesReacquire")) { noUpdate.setActionCommand("noReacquire"); noUpdate.setText("Do Not Reacquire"); allowReacquire = true; } else if (e.getActionCommand().equals("quit")) { pullThePlug(); } else if (e.getActionCommand().equals("kill")) gameProcess.destroyForcibly(); }
From source file:com.app.server.WarDeployer.java
/** * This method deploys the war in exploded form and configures it. * /*from w ww . j a v a2s.c om*/ * @param file * @param customClassLoader * @param warDirectoryPath */ public void extractWar(File file, ClassLoader classLoader) { StringBuffer classPath = new StringBuffer(); int numBytes; WebClassLoader customClassLoader = null; CopyOnWriteArrayList<URL> jarUrls = new CopyOnWriteArrayList<URL>(); try { ConcurrentHashMap jspMap = new ConcurrentHashMap(); ZipFile zip = new ZipFile(file); ZipEntry ze = null; // String fileName=file.getName(); String directoryName = file.getName(); directoryName = directoryName.substring(0, directoryName.indexOf('.')); try { /*ClassLoader classLoader = Thread.currentThread() .getContextClassLoader();*/ // log.info("file://"+warDirectoryPath+"/WEB-INF/classes/"); jarUrls.add(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/")); // new WebServer().addURL(new // URL("file://"+warDirectoryPath+"/"),customClassLoader); } catch (Exception e) { log.error("syntax of the URL is incorrect", e); //e1.printStackTrace(); } String fileDirectory; Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ze = entries.nextElement(); // //log.info("Unzipping " + ze.getName()); String filePath = scanDirectory + "/" + directoryName + "/" + ze.getName(); if (!ze.isDirectory()) { fileDirectory = filePath.substring(0, filePath.lastIndexOf('/')); } else { fileDirectory = filePath; } // //log.info(fileDirectory); createDirectory(fileDirectory); if (!ze.isDirectory()) { FileOutputStream fout = new FileOutputStream(filePath); byte[] inputbyt = new byte[8192]; InputStream istream = zip.getInputStream(ze); while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) { fout.write(inputbyt, 0, numBytes); } fout.close(); istream.close(); if (ze.getName().endsWith(".jsp")) { jspMap.put(ze.getName(), filePath); } else if (ze.getName().endsWith(".jar")) { jarUrls.add(new URL("file:///" + scanDirectory + "/" + directoryName + "/" + ze.getName())); classPath.append(filePath); classPath.append(";"); } } } zip.close(); Set jsps = jspMap.keySet(); Iterator jspIterator = jsps.iterator(); classPath.append(scanDirectory + "/" + directoryName + "/WEB-INF/classes;"); jarUrls.add(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/;")); ArrayList<String> jspFiles = new ArrayList(); // log.info(classPath.toString()); if (jspIterator.hasNext()) { jarUrls.add(new URL("file:" + scanDirectory + "/temp/" + directoryName + "/")); customClassLoader = new WebClassLoader(jarUrls.toArray(new URL[jarUrls.size()]), classLoader); while (jspIterator.hasNext()) { String filepackageInternal = (String) jspIterator.next(); String filepackageInternalTmp = filepackageInternal; if (filepackageInternal.lastIndexOf('/') == -1) { filepackageInternal = ""; } else { filepackageInternal = filepackageInternal.substring(0, filepackageInternal.lastIndexOf('/')) .replace("/", "."); filepackageInternal = "." + filepackageInternal; } createDirectory(scanDirectory + "/temp/" + directoryName); File jspFile = new File((String) jspMap.get(filepackageInternalTmp)); String fName = jspFile.getName(); String fileNameWithoutExtension = fName.substring(0, fName.lastIndexOf(".jsp")) + "_jsp"; // String fileCreated=new JspCompiler().compileJsp((String) // jspMap.get(filepackageInternalTmp), // scanDirectory+"/temp/"+fileName, // "com.app.server"+filepackageInternal,classPath.toString()); synchronized (customClassLoader) { String fileNameInWar = filepackageInternalTmp; jspFiles.add(fileNameInWar.replace("/", "\\")); if (fileNameInWar.contains("/") || fileNameInWar.contains("\\")) { customClassLoader.addURL("/" + fileNameInWar.replace("\\", "/"), "com.app.server" + filepackageInternal.replace("WEB-INF", "WEB_002dINF") + "." + fileNameWithoutExtension); } else { customClassLoader.addURL("/" + fileNameInWar, "com.app.server" + filepackageInternal.replace("WEB-INF", "WEB_002dINF") + "." + fileNameWithoutExtension); } } } } else { customClassLoader = new WebClassLoader(jarUrls.toArray(new URL[jarUrls.size()]), classLoader); } String filePath = file.getAbsolutePath(); // log.info("filePath"+filePath); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war")); urlClassLoaderMap.put(filePath.replace("\\", "/"), customClassLoader); if (jspFiles.size() > 0) { ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); //Thread.currentThread().setContextClassLoader(customClassLoader); String classPathBefore = ""; try { JspCompiler jspc = new JspCompiler(); jspc.setUriroot(scanDirectory + "/" + directoryName); jspc.setAddWebXmlMappings(false); jspc.setListErrors(false); jspc.setCompile(true); jspc.setOutputDir(scanDirectory + "/temp/" + directoryName + "/"); jspc.setPackage("com.app.server"); StringBuffer buffer = new StringBuffer(); for (String jspFile : jspFiles) { buffer.append(","); buffer.append(jspFile); } String jsp = buffer.toString(); jsp = jsp.substring(1, jsp.length()); //log.info(jsp); classPathBefore = System.getProperty("java.class.path"); System.setProperty("java.class.path", System.getProperty("java.class.path") + ";" + classPath.toString().replace("/", "\\")); //jspc.setClassPath(System.getProperty("java.class.path")+";"+classPath.toString().replace("/", "\\")); jspc.setJspFiles(jsp); jspc.initCL(customClassLoader); jspc.execute(); //jspc.closeClassLoader(); //jspc.closeClassLoader(); } catch (Throwable je) { log.error("Error in compiling the jsp page", je); //je.printStackTrace(); } finally { System.setProperty("java.class.path", classPathBefore); //Thread.currentThread().setContextClassLoader(oldCL); } //Thread.currentThread().setContextClassLoader(customClassLoader); } try { File execxml = new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "executorservices.xml"); if (execxml.exists()) { new ExecutorServicesConstruct().getExecutorServices(serverdigester, executorServiceMap, execxml, customClassLoader); } } catch (Exception e) { log.error("error in getting executor services ", e); // e.printStackTrace(); } try { File messagingxml = new File( scanDirectory + "/" + directoryName + "/WEB-INF/" + "messagingclass.xml"); if (messagingxml.exists()) { new MessagingClassConstruct().getMessagingClass(messagedigester, messagingxml, customClassLoader, messagingClassMap); } } catch (Exception e) { log.error("Error in getting the messaging classes ", e); // e.printStackTrace(); } webxmldigester.setNamespaceAware(true); webxmldigester.setValidating(true); // digester.setRules(null); FileInputStream webxml = new FileInputStream( scanDirectory + "/" + directoryName + "/WEB-INF/" + "web.xml"); InputSource is = new InputSource(webxml); try { //log.info("SCHEMA"); synchronized (webxmldigester) { // webxmldigester.set("config/web-app_2_4.xsd"); WebAppConfig webappConfig = (WebAppConfig) webxmldigester.parse(is); servletMapping.put(scanDirectory + "/" + directoryName.replace("\\", "/"), webappConfig); } webxml.close(); } catch (Exception e) { log.error("Error in pasrsing the web.xml", e); //e.printStackTrace(); } //customClassLoader.close(); // ClassLoaderUtil.closeClassLoader(customClassLoader); } catch (Exception ex) { log.error("Error in Deploying war " + file.getAbsolutePath(), ex); } }
From source file:edu.umd.cs.marmoset.utilities.ZipExtractor.java
/** * Extract the zip file./* w w w . java 2 s .c o m*/ * @throws IOException * @throws BuilderException */ public void extract(File directory) throws IOException, ZipExtractorException { ZipFile z = new ZipFile(zipFile); Pattern badName = Pattern.compile("[\\p{Cntrl}<>]"); try { Enumeration<? extends ZipEntry> entries = z.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (!shouldExtract(entryName)) continue; if (badName.matcher(entryName).find()) { if (entry.getSize() > 0) getLog().debug("Skipped entry of length " + entry.getSize() + " with bad file name " + java.net.URLEncoder.encode(entryName, "UTF-8")); continue; } try { // Get the filename to extract the entry into. // Subclasses may define this to be something other // than the entry name. String entryFileName = transformFileName(entryName); if (!entryFileName.equals(entryName)) { getLog().debug("Transformed zip entry name: " + entryName + " ==> " + entryFileName); } entriesExtractedFromZipArchive.add(entryFileName); File entryOutputFile = new File(directory, entryFileName).getAbsoluteFile(); File parentDir = entryOutputFile.getParentFile(); if (!parentDir.exists()) { if (!parentDir.mkdirs()) { throw new ZipExtractorException( "Couldn't make directory for entry output file " + entryOutputFile.getPath()); } } if (!parentDir.isDirectory()) { throw new ZipExtractorException( "Parent directory for entry " + entryOutputFile.getPath() + " is not a directory"); } // Make sure the entry output file lies within the build directory. // A malicious zip file might have ".." components in it. getLog().trace("entryOutputFile path: " + entryOutputFile.getCanonicalPath()); if (!entryOutputFile.getCanonicalPath().startsWith(directory.getCanonicalPath() + "/")) { if (!entry.isDirectory()) getLog().warn("Zip entry " + entryName + " accesses a path " + entryOutputFile.getPath() + "outside the build directory " + directory.getPath()); continue; } if (entry.isDirectory()) { entryOutputFile.mkdir(); continue; } // Extract the entry InputStream entryInputStream = null; OutputStream entryOutputStream = null; try { entryInputStream = z.getInputStream(entry); entryOutputStream = new BufferedOutputStream(new FileOutputStream(entryOutputFile)); CopyUtils.copy(entryInputStream, entryOutputStream); } finally { IOUtils.closeQuietly(entryInputStream); IOUtils.closeQuietly(entryOutputStream); } // Hook for subclasses, to specify when entries are // successfully extracted. successfulFileExtraction(entryName, entryFileName); ++numFilesExtacted; } catch (RuntimeException e) { getLog().error("Error extracting " + entryName, e); throw e; } } } finally { z.close(); } }
From source file:com.flexive.core.storage.GenericDivisionImporter.java
/** * Import database and filesystem binaries * * @param con an open and valid connection to store imported data * @param zip zip file containing the data * @throws Exception on errors/*w ww . j a v a 2 s . c o m*/ */ public void importBinaries(Connection con, ZipFile zip) throws Exception { ZipEntry ze = getZipEntry(zip, FILE_BINARIES); Statement stmt = con.createStatement(); try { importTable(stmt, zip, ze, "binaries/binary", DatabaseConst.TBL_CONTENT_BINARY); ZipEntry curr; final String nodeBinDir = FxBinaryUtils.getBinaryDirectory(); File binDir = new File( nodeBinDir + File.separatorChar + String.valueOf(FxContext.get().getDivisionId())); if (!binDir.exists()) //noinspection ResultOfMethodCallIgnored binDir.mkdirs(); if (!binDir.exists() && binDir.isDirectory()) { LOG.error("Failed to create binary directory [" + binDir.getAbsolutePath() + "]!"); return; } int count = 0; for (Enumeration e = zip.entries(); e.hasMoreElements();) { curr = (ZipEntry) e.nextElement(); if (curr.getName().startsWith(FOLDER_FS_BINARY) && !curr.isDirectory()) { File out = new File(binDir.getAbsolutePath() + File.separatorChar + curr.getName().substring(FOLDER_FS_BINARY.length() + 1)); String path = out.getAbsolutePath(); path = path.replace('\\', '/'); //normalize separator chars path = path.replace('/', File.separatorChar); path = path.substring(0, out.getAbsolutePath().lastIndexOf(File.separatorChar)); File fPath = new File(path); if (!fPath.exists()) { if (!fPath.mkdirs()) { LOG.error("Failed to create path [" + path + "!]"); continue; } } if (!out.createNewFile()) { LOG.error("Failed to create file [" + out.getAbsolutePath() + "]!"); continue; } if (FxFileUtils.copyStream2File(curr.getSize(), zip.getInputStream(curr), out)) count++; else LOG.error("Failed to write zip stream to file [" + out.getAbsolutePath() + "]!"); } } FxContext.get().runAsSystem(); try { EJBLookup.getNodeConfigurationEngine().put(SystemParameters.NODE_BINARY_PATH, nodeBinDir); } finally { FxContext.get().stopRunAsSystem(); } LOG.info("Imported [" + count + "] files to filesystem binary storage located at [" + binDir.getAbsolutePath() + "]"); } finally { Database.closeObjects(GenericDivisionImporter.class, stmt); } }
From source file:com.mobicage.rogerthat.plugins.messaging.BrandingMgr.java
private BrandingResult extractBranding(final BrandedItem item, final File encryptedBrandingFile, final File tmpDecryptedBrandingFile, final File tmpBrandingDir) throws BrandingFailureException { try {//from ww w . j a v a 2 s. co m L.i("Extracting " + tmpDecryptedBrandingFile + " (" + item.brandingKey + ")"); File brandingFile = new File(tmpBrandingDir, "branding.html"); File watermarkFile = null; Integer backgroundColor = null; Integer menuItemColor = null; ColorScheme scheme = ColorScheme.light; boolean showHeader = true; String contentType = null; boolean wakelockEnabled = false; ByteArrayOutputStream brandingBos = new ByteArrayOutputStream(); try { MessageDigest digester = MessageDigest.getInstance("SHA256"); DigestInputStream dis = new DigestInputStream( new BufferedInputStream(new FileInputStream(tmpDecryptedBrandingFile)), digester); try { ZipInputStream zis = new ZipInputStream(dis); try { byte data[] = new byte[BUFFER_SIZE]; ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { L.d("Extracting: " + entry); int count = 0; if (entry.getName().equals("branding.html")) { while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) { brandingBos.write(data, 0, count); } } else { if (entry.isDirectory()) { L.d("Skipping branding dir " + entry.getName()); continue; } File destination = new File(tmpBrandingDir, entry.getName()); destination.getParentFile().mkdirs(); if ("__watermark__".equals(entry.getName())) { watermarkFile = destination; } final OutputStream fos = new BufferedOutputStream(new FileOutputStream(destination), BUFFER_SIZE); try { while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) { fos.write(data, 0, count); } } finally { fos.close(); } } } while (dis.read(data) >= 0) ; } finally { zis.close(); } } finally { dis.close(); } String hexDigest = com.mobicage.rogerthat.util.TextUtils.toHex(digester.digest()); if (!hexDigest.equals(item.brandingKey)) { encryptedBrandingFile.delete(); SystemUtils.deleteDir(tmpBrandingDir); throw new BrandingFailureException("Branding cache was invalid!"); } brandingBos.flush(); byte[] brandingBytes = brandingBos.toByteArray(); if (brandingBytes.length == 0) { encryptedBrandingFile.delete(); SystemUtils.deleteDir(tmpBrandingDir); throw new BrandingFailureException("Invalid branding package!"); } String brandingHtml = new String(brandingBytes, "UTF8"); switch (item.type) { case BrandedItem.TYPE_MESSAGE: MessageTO message = (MessageTO) item.object; brandingHtml = brandingHtml.replace(NUNTIUZ_MESSAGE, TextUtils.htmlEncode(message.message).replace("\r", "").replace("\n", "<br>")); brandingHtml = brandingHtml.replace(NUNTIUZ_TIMESTAMP, TimeUtils.getDayTimeStr(mContext, message.timestamp * 1000)); FriendsPlugin friendsPlugin = mMainService.getPlugin(FriendsPlugin.class); brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME, TextUtils.htmlEncode(friendsPlugin.getName(message.sender))); break; case BrandedItem.TYPE_FRIEND: FriendTO friend = (FriendTO) item.object; // In this case Friend is fully populated brandingHtml = brandingHtml.replace(NUNTIUZ_MESSAGE, TextUtils.htmlEncode(friend.description).replace("\r", "").replace("\n", "<br>")); brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME, TextUtils.htmlEncode(friend.name)); break; case BrandedItem.TYPE_GENERIC: if (item.object instanceof FriendTO) { brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME, TextUtils.htmlEncode(((FriendTO) item.object).name)); } break; } Matcher matcher = RegexPatterns.BRANDING_BACKGROUND_COLOR.matcher(brandingHtml); if (matcher.find()) { String bg = matcher.group(1); if (bg.length() == 4) { StringBuilder sb = new StringBuilder(); sb.append("#"); sb.append(bg.charAt(1)); sb.append(bg.charAt(1)); sb.append(bg.charAt(2)); sb.append(bg.charAt(2)); sb.append(bg.charAt(3)); sb.append(bg.charAt(3)); bg = sb.toString(); } backgroundColor = Color.parseColor(bg); } matcher = RegexPatterns.BRANDING_MENU_ITEM_COLOR.matcher(brandingHtml); if (matcher.find()) { String bg = matcher.group(1); if (bg.length() == 4) { StringBuilder sb = new StringBuilder(); sb.append("#"); sb.append(bg.charAt(1)); sb.append(bg.charAt(1)); sb.append(bg.charAt(2)); sb.append(bg.charAt(2)); sb.append(bg.charAt(3)); sb.append(bg.charAt(3)); bg = sb.toString(); } menuItemColor = Color.parseColor(bg); } matcher = RegexPatterns.BRANDING_COLOR_SCHEME.matcher(brandingHtml); if (matcher.find()) { String schemeStr = matcher.group(1); scheme = "dark".equalsIgnoreCase(schemeStr) ? ColorScheme.dark : ColorScheme.light; } matcher = RegexPatterns.BRANDING_SHOW_HEADER.matcher(brandingHtml); if (matcher.find()) { String showHeaderStr = matcher.group(1); showHeader = "true".equalsIgnoreCase(showHeaderStr); } matcher = RegexPatterns.BRANDING_CONTENT_TYPE.matcher(brandingHtml); if (matcher.find()) { String contentTypeStr = matcher.group(1); L.i("Branding content-type: " + contentTypeStr); if (AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(contentTypeStr)) { File tmpBrandingFile = new File(tmpBrandingDir, "embed.pdf"); if (tmpBrandingFile.exists()) { contentType = AttachmentViewerActivity.CONTENT_TYPE_PDF; } } } Dimension dimension1 = null; Dimension dimension2 = null; matcher = RegexPatterns.BRANDING_DIMENSIONS.matcher(brandingHtml); if (matcher.find()) { String dimensionsStr = matcher.group(1); L.i("Branding dimensions: " + dimensionsStr); String[] dimensions = dimensionsStr.split(","); try { dimension1 = new Dimension(Integer.parseInt(dimensions[0]), Integer.parseInt(dimensions[1])); dimension2 = new Dimension(Integer.parseInt(dimensions[2]), Integer.parseInt(dimensions[3])); } catch (Exception e) { L.bug("Invalid branding dimension: " + matcher.group(), e); } } matcher = RegexPatterns.BRANDING_WAKELOCK_ENABLED.matcher(brandingHtml); if (matcher.find()) { String wakelockEnabledStr = matcher.group(1); wakelockEnabled = "true".equalsIgnoreCase(wakelockEnabledStr); } final List<String> externalUrlPatterns = new ArrayList<String>(); matcher = RegexPatterns.BRANDING_EXTERNAL_URLS.matcher(brandingHtml); while (matcher.find()) { externalUrlPatterns.add(matcher.group(1)); } FileOutputStream fos = new FileOutputStream(brandingFile); try { fos.write(brandingHtml.getBytes("UTF8")); } finally { fos.close(); } if (contentType != null && AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(contentType)) { brandingFile = new File(tmpBrandingDir, "embed.pdf"); } return new BrandingResult(tmpBrandingDir, brandingFile, watermarkFile, backgroundColor, menuItemColor, scheme, showHeader, dimension1, dimension2, contentType, wakelockEnabled, externalUrlPatterns); } finally { brandingBos.close(); } } catch (IOException e) { L.e(e); throw new BrandingFailureException("Error copying cached branded file to private space", e); } catch (NoSuchAlgorithmException e) { L.e(e); throw new BrandingFailureException("Cannot validate ", e); } }
From source file:com.izforge.izpack.compiler.CompilerConfig.java
/** * Add files in an archive to a pack/*from www. ja v a 2 s .com*/ * * @param archive the archive file to unpack * @param targetdir the target directory where the content of the archive will be installed * @param osList The target OS constraints. * @param override Overriding behaviour. * @param pack Pack to be packed into * @param additionals Map which contains additional data * @param condition condition that must evaluate {@code} true for the file to be installed. May * be {@code null} */ protected void addArchiveContent(File baseDir, File archive, String targetdir, List<OsModel> osList, OverrideType override, String overrideRenameTo, Blockable blockable, PackInfo pack, Map additionals, String condition) throws IOException { FileInputStream fin = new FileInputStream(archive); ZipInputStream zin = new ZipInputStream(fin); List<String> allDirList = new ArrayList<String>(); while (true) { ZipEntry zentry = zin.getNextEntry(); if (zentry == null) { break; } if (zentry.isDirectory()) { // add to all dir listing/empty dir needs to be handle String dName = zentry.getName().substring(0, zentry.getName().length() - 1); allDirList.add(dName); continue; } try { File temp = FileUtils.createTempFile("izpack", null); temp.deleteOnExit(); FileOutputStream out = new FileOutputStream(temp); IoHelper.copyStream(zin, out); out.close(); String target = targetdir + "/" + zentry.getName(); logger.info("Adding file " + zentry.getName() + " from archive as target file=" + target); pack.addFile(baseDir, temp, target, osList, override, overrideRenameTo, blockable, additionals, condition); } catch (IOException e) { throw new IOException("Couldn't create temporary file for " + zentry.getName() + " in archive " + archive + " (" + e.getMessage() + ")"); } } for (String dirName : allDirList) { File tmp = new File(dirName); if (!tmp.mkdirs()) { throw new CompilerException("Failed to create directory: " + tmp); } tmp.deleteOnExit(); String target = targetdir + "/" + dirName; logger.info("Adding file: " + tmp + ", as target file=" + target); pack.addFile(baseDir, tmp, target, osList, override, overrideRenameTo, blockable, additionals, condition); } fin.close(); }
From source file:org.openmeetings.servlet.outputhandler.BackupImportController.java
public void performImport(InputStream is, String current_dir) throws Exception { File working_dir = new File(current_dir, OpenmeetingsVariables.UPLOAD_DIR + File.separatorChar + "import"); if (!working_dir.exists()) { working_dir.mkdir();//from w w w . j av a 2 s .c o m } File f = new File(working_dir, "import_" + CalendarPatterns.getTimeForStreamId(new Date())); int recursiveNumber = 0; do { if (f.exists()) { f = new File(f.getAbsolutePath() + (recursiveNumber++)); } } while (f.exists()); f.mkdir(); log.debug("##### WRITE FILE TO: " + f); ZipInputStream zipinputstream = new ZipInputStream(is); byte[] buf = new byte[1024]; ZipEntry zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { // for each entry to be extracted int n; FileOutputStream fileoutputstream; File fentryName = new File(f, zipentry.getName()); if (zipentry.isDirectory()) { if (!fentryName.mkdir()) { break; } zipentry = zipinputstream.getNextEntry(); continue; } File fparent = new File(fentryName.getParent()); if (!fparent.exists()) { File fparentparent = new File(fparent.getParent()); if (!fparentparent.exists()) { File fparentparentparent = new File(fparentparent.getParent()); if (!fparentparentparent.exists()) { fparentparentparent.mkdir(); fparentparent.mkdir(); fparent.mkdir(); } else { fparentparent.mkdir(); fparent.mkdir(); } } else { fparent.mkdir(); } } fileoutputstream = new FileOutputStream(fentryName); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) { fileoutputstream.write(buf, 0, n); } fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } // while zipinputstream.close(); /* * ##################### Import Organizations */ File orgFile = new File(f, "organizations.xml"); if (!orgFile.exists()) { throw new Exception("organizations.xml missing"); } this.importOrganizsations(orgFile); log.info("Organizations import complete, starting user import"); /* * ##################### Import Users */ File userFile = new File(f, "users.xml"); if (!userFile.exists()) { throw new Exception("users.xml missing"); } this.importUsers(userFile); log.info("Users import complete, starting room import"); /* * ##################### Import Rooms */ File roomFile = new File(f, "rooms.xml"); if (!roomFile.exists()) { throw new Exception("rooms.xml missing"); } this.importRooms(roomFile); log.info("Room import complete, starting room organizations import"); /* * ##################### Import Room Organisations */ File orgRoomListFile = new File(f, "rooms_organisation.xml"); if (!orgRoomListFile.exists()) { throw new Exception("rooms_organisation.xml missing"); } this.importOrgRooms(orgRoomListFile); log.info("Room organizations import complete, starting appointement import"); /* * ##################### Import Appointements */ File appointementListFile = new File(f, "appointements.xml"); if (!appointementListFile.exists()) { throw new Exception("appointements.xml missing"); } this.importAppointements(appointementListFile); log.info("Appointement import complete, starting meeting members import"); /* * ##################### Import MeetingMembers * * Reminder Invitations will be NOT send! */ File meetingmembersListFile = new File(f, "meetingmembers.xml"); if (!meetingmembersListFile.exists()) { throw new Exception("meetingmembersListFile missing"); } this.importMeetingmembers(meetingmembersListFile); log.info("Meeting members import complete, starting ldap config import"); /* * ##################### Import LDAP Configs */ File ldapConfigListFile = new File(f, "ldapconfigs.xml"); if (!ldapConfigListFile.exists()) { log.debug("meetingmembersListFile missing"); // throw new Exception // ("meetingmembersListFile missing"); } else { this.importLdapConfig(ldapConfigListFile); } log.info("Ldap config import complete, starting recordings import"); /* * ##################### Import Recordings */ File flvRecordingsListFile = new File(f, "flvRecordings.xml"); if (!flvRecordingsListFile.exists()) { log.debug("flvRecordingsListFile missing"); // throw new Exception // ("meetingmembersListFile missing"); } else { this.importFlvRecordings(flvRecordingsListFile); } log.info("FLVrecording import complete, starting private message folder import"); /* * ##################### Import Private Message Folders */ File privateMessageFoldersFile = new File(f, "privateMessageFolder.xml"); if (!privateMessageFoldersFile.exists()) { log.debug("privateMessageFoldersFile missing"); // throw new Exception // ("meetingmembersListFile missing"); } else { this.importPrivateMessageFolders(privateMessageFoldersFile); } log.info("Private message folder import complete, starting private message import"); /* * ##################### Import Private Messages */ File privateMessagesFile = new File(f, "privateMessages.xml"); if (!privateMessagesFile.exists()) { log.debug("privateMessagesFile missing"); // throw new Exception // ("meetingmembersListFile missing"); } else { this.importPrivateMessages(privateMessagesFile); } log.info("Private message import complete, starting usercontact import"); /* * ##################### Import User Contacts */ File userContactsFile = new File(f, "userContacts.xml"); if (!userContactsFile.exists()) { log.debug("userContactsFile missing"); // throw new Exception // ("meetingmembersListFile missing"); } else { this.importUserContacts(userContactsFile); } log.info("Usercontact import complete, starting file explorer item import"); /* * ##################### Import File-Explorer Items */ File fileExplorerListFile = new File(f, "fileExplorerItems.xml"); if (!fileExplorerListFile.exists()) { log.debug("fileExplorerListFile missing"); // throw new Exception // ("meetingmembersListFile missing"); } else { this.importFileExplorerItems(fileExplorerListFile); } log.info("File explorer item import complete, starting file poll import"); /* * ##################### Import Room Polls */ File roomPollListFile = new File(f, "roompolls.xml"); if (!roomPollListFile.exists()) { log.debug("roomPollListFile missing"); } else { this.importRoomPolls(roomPollListFile); } log.info("Poll import complete, starting configs import"); /* * ##################### Import Configs */ File configsFile = new File(f, "configs.xml"); if (!configsFile.exists()) { log.debug("configsFile missing"); } else { importConfigs(configsFile); } log.info("Configs import complete, starting asteriskSipUsersFile import"); /* * ##################### Import AsteriskSipUsers */ File asteriskSipUsersFile = new File(f, "asterisksipusers.xml"); if (!asteriskSipUsersFile.exists()) { log.debug("asteriskSipUsersFile missing"); } else { importAsteriskSipUsers(asteriskSipUsersFile); } log.info("AsteriskSipUsers import complete, starting extensions import"); /* * ##################### Import Extensions */ File extensionsFile = new File(f, "extensions.xml"); if (!extensionsFile.exists()) { log.debug("extensionsFile missing"); } else { importExtensions(extensionsFile); } log.info("Extensions import complete, starting members import"); /* * ##################### Import Extensions */ File membersFile = new File(f, "members.xml"); if (!membersFile.exists()) { log.debug("membersFile missing"); } else { importMembers(membersFile); } log.info("Members import complete, starting copy of files and folders"); /* * ##################### Import real files and folders */ importFolders(current_dir, f); log.info("File explorer item import complete, clearing temp files"); deleteDirectory(f); }
From source file:com.amalto.workbench.utils.Util.java
/** * DOC hbhong Comment method "unZipFile". same with unZipFile(String zipfile, String unzipdir) method except having * a progressMonitor/* w ww .j av a2 s. c o m*/ * * @param zipfile * @param unzipdir * @param totalProgress * @param monitor * @throws IOException * @throws Exception */ public static void unZipFile(String zipfile, String unzipdir, int totalProgress, IProgressMonitor monitor) throws IOException { monitor.setTaskName(Messages.Util_50); File unzipF = new File(unzipdir); if (!unzipF.exists()) { unzipF.mkdirs(); } ZipFile zfile = null; try { zfile = new ZipFile(zipfile); int total = zfile.size(); // System.out.println("zip's entry size:"+total); int interval, step; if (totalProgress / total > 0) { interval = 1; step = Math.round(totalProgress / total); } else { step = 1; interval = Math.round(total / totalProgress + 0.5f); } Enumeration zList = zfile.entries(); ZipEntry ze = null; byte[] buf = new byte[1024]; int tmp = 1; while (zList.hasMoreElements()) { ze = (ZipEntry) zList.nextElement(); monitor.subTask(ze.getName()); if (ze.isDirectory()) { File f = new File(unzipdir + ze.getName()); f.mkdirs(); continue; } unzipdir = unzipdir.replace('\\', '/'); if (!unzipdir.endsWith("/")) { //$NON-NLS-1$ unzipdir = unzipdir + "/"; //$NON-NLS-1$ } String filename = unzipdir + ze.getName(); File zeF = new File(filename); if (!zeF.getParentFile().exists()) { zeF.getParentFile().mkdirs(); } OutputStream os = null; InputStream is = null; try { os = new BufferedOutputStream(new FileOutputStream(zeF)); is = new BufferedInputStream(zfile.getInputStream(ze)); int readLen = 0; while ((readLen = is.read(buf, 0, 1024)) != -1) { os.write(buf, 0, readLen); } } catch (IOException e) { log.error(e.getMessage(), e); } finally { try { if (is != null) { is.close(); } } catch (Exception e) { } try { if (os != null) { os.close(); } } catch (Exception e) { } } // update monitor if (interval == 1) { monitor.worked(step); } else { if (tmp >= interval) { monitor.worked(step); tmp = 1; } else { tmp++; } } } } catch (IOException e) { log.error(e.getMessage(), e); throw e; } finally { if (zfile != null) { try { zfile.close(); } catch (IOException e) { } } } }
From source file:com.pari.pcb.zip.ZIPProcessor.java
public void process(boolean blocking) { tmpRoot = new File("TEMP" + File.separator + "ZIP_TMP_" + System.nanoTime()); tmpRoot.mkdirs();/*from w w w . j a va 2 s . c o m*/ long start = System.currentTimeMillis(); if (!zipFile.exists()) { errMsg = "File " + fileName + " does not exist"; setCompleted(); return; } if (!zipFile.canRead()) { errMsg = "Unable to read the contents of the file " + fileName; setCompleted(); return; } try { ZipFile inZip = new ZipFile(zipFile); numEntries = inZip.size(); Enumeration<? extends ZipEntry> entryEnumeration = inZip.entries(); if (numEntries == 0) { errMsg = "Empty ZIP file."; setCompleted(); return; } while (entryEnumeration.hasMoreElements()) { ZipEntry entry = entryEnumeration.nextElement(); currentEntryName = entry.getName(); if (entry.isDirectory()) { if (numEntries > 1) { numEntries--; } continue; } currentEntryIdx++; if (currentEntryIdx % 100 == 0) { System.gc(); NCCMObserver.getInstance().logMemoryUsage( "After handling " + currentEntryIdx + " files in Zip Processor, Memory Usage"); } InputStream ipStream = inZip.getInputStream(entry); String fileName = entry.getName(); System.err.println("Processing file: " + fileName); String line = null; try { BufferedReader br = new BufferedReader(new InputStreamReader(ipStream)); line = br.readLine(); CharsetDetector detector = new CharsetDetector(); if (entry.getSize() == 0) { logger.error("No Contents found in the file"); continue; } else { detector.setText(line.getBytes()); charset = Charset.forName(detector.detect().getName()); } } catch (Exception ex) { logger.error("Error while getting the charset encoding of the file"); } finally { try { ipStream.close(); } catch (Exception e) { logger.error("Exception while closing the stream"); } } ipStream = inZip.getInputStream(entry); processZipEntry(ipStream, fileName, entry, inZip); if (progressIf != null) { progressIf.updateProgress(currentEntryName, currentEntryIdx, numEntries); } if (fileResultMap.get(fileName) == null) { ZIPFileResult fr = new ZIPFileResult(fileName); fr.fileType = ZIPFileType.UNKNOWN; fr.msg = "Unable to process the file."; fileResultMap.put(fileName, fr); } try { ipStream.close(); } catch (Exception ex) { logger.warn("Unable to close the inputstream for entry " + entry.getName(), ex); ex.printStackTrace(); } if (isCancelled) { break; } if (!blocking) { Thread.sleep(100 /* msec */); } if (isCancelled) { break; } } if (!isCancelled) { processCatOsVersionFiles(inZip); processFileResult(); } inZip.close(); } catch (ZipException e) { errMsg = "File is not a valid Zip file"; logger.error("Exception while processing ZipFile: " + fileName, e); } catch (IOException e) { errMsg = "Unable to parse Zip file "; logger.error("IOException while processing ZipFile: " + fileName, e); } catch (InterruptedException e) { errMsg = "Zip processing Interrupted internally."; logger.error("Interrupted while processing ZipFile: " + fileName, e); } catch (Exception e) { errMsg = "Exception while processing zip file."; logger.error("Exception while processing ZipFile: " + fileName, e); } logger.debug("Done with : " + numEntries + " in " + (System.currentTimeMillis() - start) + " msecs"); String[] devNames = getDeviceNames(); if (devNames == null || devNames.length == 0) { addWarning("No valid devices found in the specified Zip file."); } setCompleted(); return; }