List of usage examples for java.util.zip ZipFile getEntry
public ZipEntry getEntry(String name)
From source file:com.samczsun.helios.transformers.decompilers.KrakatauDecompiler.java
public boolean decompile(ClassNode classNode, byte[] bytes, StringBuilder output) { if (Helios.ensurePython2Set()) { if (Helios.ensureJavaRtSet()) { File inputJar = null; File outputJar = null; ZipFile zipFile = null; Process createdProcess; String log = ""; try { inputJar = Files.createTempFile("kdein", ".jar").toFile(); outputJar = Files.createTempFile("kdeout", ".zip").toFile(); Map<String, byte[]> loadedData = Helios.getAllLoadedData(); loadedData.put(classNode.name + ".class", bytes); Utils.saveClasses(inputJar, loadedData); createdProcess = Helios// www . java2 s . c om .launchProcess(new ProcessBuilder(Settings.PYTHON2_LOCATION.get().asString(), "-O", "decompile.py", "-skip", "-nauto", "-path", buildPath(inputJar), "-out", outputJar.getAbsolutePath(), classNode.name + ".class") .directory(Constants.KRAKATAU_DIR)); log = Utils.readProcess(createdProcess); System.out.println(log); zipFile = new ZipFile(outputJar); ZipEntry zipEntry = zipFile.getEntry(classNode.name + ".java"); if (zipEntry == null) throw new IllegalArgumentException("Class failed to decompile (no class in output zip)"); InputStream inputStream = zipFile.getInputStream(zipEntry); byte[] data = IOUtils.toByteArray(inputStream); output.append(new String(data, "UTF-8")); return true; } catch (Exception e) { output.append(parseException(e)).append("\n").append(log); return false; } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { } } if (inputJar != null) { if (!inputJar.delete()) { inputJar.deleteOnExit(); } } if (outputJar != null) { if (!outputJar.delete()) { outputJar.deleteOnExit(); } } } } else { output.append("You need to set the location of rt.jar"); } } else { output.append("You need to set the location of Python 2.x"); } return false; }
From source file:fr.gouv.finances.dgfip.xemelios.importers.archives.ArchiveImporter.java
protected File extractFileFromZip(ZipFile zf, String filePath) throws IOException { ZipEntry ze = zf.getEntry(filePath); File ret = new File(getTempDir(), filePath); File parent = ret.getParentFile(); parent.mkdirs();/*from www.j av a 2 s .c o m*/ InputStream is = zf.getInputStream(ze); OutputStream fos = new FileOutputStream(ret); byte[] buffer = new byte[1024]; int read = is.read(buffer); do { if (read > 0) { fos.write(buffer, 0, read); } read = is.read(buffer); } while (read > 0); fos.flush(); fos.close(); filesToDrop.add(ret); return ret; }
From source file:org.digidoc4j.impl.bdoc.BDocContainerTest.java
@Test public void whenSigningContainer_withSignatureNameContainingNonNumericCharacters_shouldCreateSignatureFileName_inSequence() throws Exception { ZipFile zip = new ZipFile( "testFiles/valid-containers/valid-bdoc-ts-signature-file-name-with-non-numeric-characters.asice"); assertNotNull(zip.getEntry("META-INF/l77Tsignaturesn00B.xml")); assertNull(zip.getEntry("META-INF/signatures0.xml")); assertNull(zip.getEntry("META-INF/signatures1.xml")); Container container = open(//from w w w . j a v a 2 s .c o m "testFiles/valid-containers/valid-bdoc-ts-signature-file-name-with-non-numeric-characters.asice"); signContainer(container, SignatureProfile.LT); signContainer(container, SignatureProfile.LT); String containerPath = testFolder.newFile("test-container.asice").getPath(); container.saveAsFile(containerPath); zip = new ZipFile(containerPath); assertNotNull(zip.getEntry("META-INF/l77Tsignaturesn00B.xml")); assertNotNull(zip.getEntry("META-INF/signatures0.xml")); assertNotNull(zip.getEntry("META-INF/signatures1.xml")); }
From source file:dalma.container.ClassLoaderImpl.java
/** * Returns an inputstream to a given resource in the given file which may * either be a directory or a zip file.// w w w .java 2 s. co m * * @param file the file (directory or jar) in which to search for the * resource. Must not be <code>null</code>. * @param resourceName The name of the resource for which a stream is * required. Must not be <code>null</code>. * * @return a stream to the required resource or <code>null</code> if * the resource cannot be found in the given file. */ private InputStream getResourceStream(File file, String resourceName) { try { if (!file.exists()) { return null; } if (file.isDirectory()) { File resource = new File(file, resourceName); if (resource.exists()) { return new FileInputStream(resource); } } else { // is the zip file in the cache ZipFile zipFile = zipFiles.get(file); if (zipFile == null) { zipFile = new ZipFile(file); zipFiles.put(file, zipFile); } ZipEntry entry = zipFile.getEntry(resourceName); if (entry != null) { return zipFile.getInputStream(entry); } } } catch (Exception e) { logger.fine("Ignoring Exception " + e.getClass().getName() + ": " + e.getMessage() + " reading resource " + resourceName + " from " + file); } return null; }
From source file:dalma.container.ClassLoaderImpl.java
/** * Returns the URL of a given resource in the given file which may * either be a directory or a zip file./*w ww. ja v a 2 s . c o m*/ * * @param file The file (directory or jar) in which to search for * the resource. Must not be <code>null</code>. * @param resourceName The name of the resource for which a stream * is required. Must not be <code>null</code>. * * @return a stream to the required resource or <code>null</code> if the * resource cannot be found in the given file object. */ protected URL getResourceURL(File file, String resourceName) { try { if (!file.exists()) { return null; } if (file.isDirectory()) { File resource = new File(file, resourceName); if (resource.exists()) { try { return resource.toURL(); } catch (MalformedURLException ex) { return null; } } } else { ZipFile zipFile = zipFiles.get(file); if (zipFile == null) { zipFile = new ZipFile(file); zipFiles.put(file, zipFile); } ZipEntry entry = zipFile.getEntry(resourceName); if (entry != null) { try { return new URL("jar:" + file.toURL() + "!/" + entry); } catch (MalformedURLException ex) { return null; } } } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.heliosdecompiler.helios.transformers.decompilers.KrakatauDecompiler.java
public boolean decompile(ClassNode classNode, byte[] bytes, StringBuilder output) { if (Helios.ensurePython2Set()) { if (Helios.ensureJavaRtSet()) { File inputJar = null; File outputJar = null; ZipFile zipFile = null; Process createdProcess; String log = ""; try { inputJar = Files.createTempFile("kdein", ".jar").toFile(); outputJar = Files.createTempFile("kdeout", ".zip").toFile(); Map<String, byte[]> loadedData = Helios.getAllLoadedData(); loadedData.put(classNode.name + ".class", bytes); Utils.saveClasses(inputJar, loadedData); createdProcess = Helios.launchProcess(new ProcessBuilder( com.heliosdecompiler.helios.Settings.PYTHON2_LOCATION.get().asString(), "-O", "decompile.py", "-skip", "-nauto", Settings.MAGIC_THROW.isEnabled() ? "-xmagicthrow" : "", "-path", buildPath(inputJar), "-out", outputJar.getAbsolutePath(), classNode.name + ".class") .directory(Constants.KRAKATAU_DIR)); log = Utils.readProcess(createdProcess); System.out.println(log); zipFile = new ZipFile(outputJar); ZipEntry zipEntry = zipFile.getEntry(classNode.name + ".java"); if (zipEntry == null) throw new IllegalArgumentException("Class failed to decompile (no class in output zip)"); InputStream inputStream = zipFile.getInputStream(zipEntry); byte[] data = IOUtils.toByteArray(inputStream); output.append(new String(data, "UTF-8")); return true; } catch (Exception e) { output.append(parseException(e)).append("\n").append(log); return false; } finally { IOUtils.closeQuietly(zipFile); FileUtils.deleteQuietly(inputJar); FileUtils.deleteQuietly(outputJar); }//from w ww. j a va 2 s . c o m } else { output.append("You need to set the location of rt.jar"); } } else { output.append("You need to set the location of Python 2.x"); } return false; }
From source file:openaf.AFCmdOS.java
/** * /* w ww. j a v a2 s. c o m*/ * @param in * @param out * @param appoperation2 * @throws Exception */ protected com.google.gson.JsonObject execute(com.google.gson.JsonObject pmIn, String op, boolean processScript, StringBuilder theInput, boolean isolatePMs) throws Exception { // 3. Process input // INPUT_TYPE = inputtype.INPUT_SCRIPT; if (((!pipe) && (!filescript) && (!processScript) && (!injectcode) && (!injectclass))) { if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { /*injectscript = true; injectscriptfile = "/js/openafgui.js"; filescript = true;*/ injectclass = true; injectclassfile = "openafgui_js"; filescript = false; silentMode = true; } } if (processScript || filescript || injectcode || injectclass) { // Obtain script String script = null; if (filescript) { if (injectscript) { script = IOUtils.toString(getClass().getResourceAsStream(injectscriptfile), "UTF-8"); } else { boolean isZip = false; boolean isOpack = false; com.google.gson.JsonObject pm = null; ZipFile tmpZip = null; // Determine if it's opack/zip DataInputStream dis = new DataInputStream( new BufferedInputStream(new FileInputStream(scriptfile.replaceFirst("::[^:]+$", "")))); int test = dis.readInt(); dis.close(); if (test == 0x504b0304) { isZip = true; try { tmpZip = new ZipFile(scriptfile.replaceFirst("::[^:]+$", "")); isOpack = tmpZip.getEntry(OPACK) != null; zip = tmpZip; } catch (Exception e) { } if (isOpack) { if (scriptfile.indexOf("::") <= 0) { pm = new Gson().fromJson( IOUtils.toString(zip.getInputStream(zip.getEntry(OPACK)), (Charset) null), JsonObject.class); try { pm.get("main"); } catch (Exception e) { isZip = false; } } } } // Read normal script or opack/zip if (isZip) { if (scriptfile.indexOf("::") <= 0 && isOpack) { if (pm.get("main").getAsString().length() > 0) { script = IOUtils.toString( zip.getInputStream(zip.getEntry(pm.get("main").getAsString())), "UTF-8"); scriptfile = scriptfile + "/" + pm.get("main").getAsString(); } else { throw new Exception("Can't execute main script in " + scriptfile); } } else { try { script = IOUtils.toString( zip.getInputStream(zip.getEntry(scriptfile.replaceFirst(".+::", ""))), "UTF-8"); } catch (NullPointerException e) { throw new Exception("Can't find " + scriptfile.replaceFirst(".+::", "")); } } } else { script = FileUtils.readFileToString(new File(scriptfile), (Charset) null); zip = null; } } } else { if (!injectclass) script = theInput.toString(); } if (script != null) { script = script.replaceAll("^#.*", "//"); script = script.replaceFirst(PREFIX_SCRIPT, ""); if (daemon) script = "ow.loadServer().simpleCheckIn('" + scriptfile + "'); " + script + "; ow.loadServer().daemon();"; if (injectcode) script += code; } Context cx = (Context) jse.getNotSafeContext(); cx.setErrorReporter(new OpenRhinoErrorReporter()); String includeScript = ""; NativeObject jsonPMOut = new NativeObject(); synchronized (this) { Object opmIn; opmIn = AFBase.jsonParse(pmIn.toString()); Object noSLF4JErrorOnly = Context.javaToJS(__noSLF4JErrorOnly, (Scriptable) jse.getGlobalscope()); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__noSLF4JErrorOnly", noSLF4JErrorOnly); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "pmIn", opmIn); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__pmIn", opmIn); // Add pmOut object Object opmOut = Context.javaToJS(jsonPMOut, (Scriptable) jse.getGlobalscope()); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "pmOut", opmOut); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__pmOut", opmOut); // Add expr object Object opmExpr = Context.javaToJS(exprInput, (Scriptable) jse.getGlobalscope()); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "expr", opmExpr); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__expr", opmExpr); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__args", args); // Add scriptfile object if (filescript) { Object scriptFile = Context.javaToJS(scriptfile, (Scriptable) jse.getGlobalscope()); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__scriptfile", scriptFile); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__iszip", (zip == null) ? false : true); } // Add AF class ScriptableObject.defineClass((Scriptable) jse.getGlobalscope(), AFBase.class, false, true); // Add DB class ScriptableObject.defineClass((Scriptable) jse.getGlobalscope(), DB.class, false, true); // Add CSV class ScriptableObject.defineClass((Scriptable) jse.getGlobalscope(), CSV.class, false, true); // Add IO class ScriptableObject.defineClass((Scriptable) jse.getGlobalscope(), IOBase.class, false, true); // Add this object Scriptable afScript = null; //if (!ScriptableObject.hasProperty((Scriptable) jse.getGlobalscope(), "AF")) { afScript = (Scriptable) jse.newObject((Scriptable) jse.getGlobalscope(), "AF"); //} if (!ScriptableObject.hasProperty((Scriptable) jse.getGlobalscope(), "af")) ((IdScriptableObject) jse.getGlobalscope()).put("af", (Scriptable) jse.getGlobalscope(), afScript); // Add the IO object if (!ScriptableObject.hasProperty((Scriptable) jse.getGlobalscope(), "io")) ((IdScriptableObject) jse.getGlobalscope()).put("io", (Scriptable) jse.getGlobalscope(), jse.newObject(jse.getGlobalscope(), "IO")); } // Compile & execute script /*try { InputStream in1 = getClass().getResourceAsStream("/js/openaf.js"); includeScript = IOUtils.toString(in1, (Charset) null); numberOfIncludedLines = numberOfIncludedLines + includeScript.split("\r\n|\r|\n").length; AFCmdBase.jse.addNumberOfLines(includeScript); } catch (Exception e) { SimpleLog.log(logtype.DEBUG, "Error including openaf.js", e); }*/ AFBase.runFromClass(Class.forName("openaf_js").getDeclaredConstructor().newInstance()); cx.setErrorReporter(new OpenRhinoErrorReporter()); if (isolatePMs) { script = "(function(__pIn) { var __pmOut = {}; var __pmIn = __pIn; " + script + "; return __pmOut; })(" + pmIn.toString() + ")"; } Object res = null; if (injectscript || filescript || injectcode || processScript) { Context cxl = (Context) jse.enterContext(); org.mozilla.javascript.Script compiledScript = cxl.compileString(includeScript + script, scriptfile, 1, null); res = compiledScript.exec(cxl, (Scriptable) jse.getGlobalscope()); jse.exitContext(); } if (injectclass) { res = AFBase.runFromClass(Class.forName(injectclassfile).getDeclaredConstructor().newInstance()); } if (isolatePMs && res != null && !(res instanceof Undefined)) { jsonPMOut = (NativeObject) res; } else { // Obtain pmOut as output jsonPMOut = (NativeObject) ((ScriptableObject) jse.getGlobalscope()).get("__pmOut"); } // Convert to ParameterMap Object stringify = NativeJSON.stringify(cx, (Scriptable) jse.getGlobalscope(), jsonPMOut, null, null); com.google.gson.Gson gson = new com.google.gson.Gson(); pmOut = gson.fromJson(stringify.toString(), com.google.gson.JsonObject.class); // Leave Rhino //org.mozilla.javascript.Context.exit(); //jse.exitContext(); } return pmOut; }
From source file:streamflow.service.FrameworkService.java
/** * Process the annotations found in a framework jar * * @param jarFile//from w w w.j a v a2s . c o m * @return a FrameworkConfig or null if no annotations were found */ public FrameworkConfig processFrameworkAnnotations(File jarFile) { FrameworkConfig config = new FrameworkConfig(); ArrayList<ComponentConfig> components = new ArrayList<ComponentConfig>(); String frameworkLevel = null; boolean foundFrameworkAnnotations = false; ZipFile zipFile = null; try { zipFile = new ZipFile(jarFile); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entry.isDirectory()) { if (frameworkLevel != null) { if (entryName.startsWith(frameworkLevel) == false) { frameworkLevel = null; } } ZipEntry packageInfoEntry = zipFile.getEntry(entryName + "package-info.class"); if (packageInfoEntry != null) { InputStream fileInputStream = zipFile.getInputStream(packageInfoEntry); DataInputStream dstream = new DataInputStream(fileInputStream); ClassFile cf = new ClassFile(dstream); String cfName = cf.getName(); AnnotationsAttribute attr = (AnnotationsAttribute) cf .getAttribute(AnnotationsAttribute.visibleTag); Annotation annotation = attr.getAnnotation("streamflow.annotations.Framework"); if (annotation == null) { continue; } frameworkLevel = cfName; foundFrameworkAnnotations = true; StringMemberValue frameworkLabel = (StringMemberValue) annotation.getMemberValue("label"); if (frameworkLabel != null) { config.setLabel(frameworkLabel.getValue()); } StringMemberValue frameworkName = (StringMemberValue) annotation.getMemberValue("name"); if (frameworkName != null) { config.setName(frameworkName.getValue()); } StringMemberValue frameworkVersion = (StringMemberValue) annotation .getMemberValue("version"); if (frameworkVersion != null) { config.setVersion(frameworkVersion.getValue()); } Annotation descriptionAnnotation = attr.getAnnotation("streamflow.annotations.Description"); if (descriptionAnnotation != null) { StringMemberValue frameworkDescription = (StringMemberValue) descriptionAnnotation .getMemberValue("value"); if (frameworkDescription != null) { config.setDescription(frameworkDescription.getValue()); } } } } else if (frameworkLevel != null && entryName.endsWith(".class") && entryName.endsWith("package-info.class") == false) { ZipEntry packageInfoEntry = zipFile.getEntry(entryName); InputStream fileInputStream = zipFile.getInputStream(packageInfoEntry); DataInputStream dstream = new DataInputStream(fileInputStream); ClassFile cf = new ClassFile(dstream); String cfName = cf.getName(); AnnotationsAttribute attr = (AnnotationsAttribute) cf .getAttribute(AnnotationsAttribute.visibleTag); if (attr == null) { continue; } Annotation componentAnnotation = attr.getAnnotation("streamflow.annotations.Component"); if (componentAnnotation == null) { continue; } ComponentConfig component = new ComponentConfig(); component.setMainClass(cf.getName()); StringMemberValue componentLabel = (StringMemberValue) componentAnnotation .getMemberValue("label"); if (componentLabel != null) { component.setLabel(componentLabel.getValue()); } StringMemberValue componentName = (StringMemberValue) componentAnnotation .getMemberValue("name"); if (componentName != null) { component.setName(componentName.getValue()); } StringMemberValue componentType = (StringMemberValue) componentAnnotation .getMemberValue("type"); if (componentType != null) { component.setType(componentType.getValue()); } StringMemberValue componentIcon = (StringMemberValue) componentAnnotation .getMemberValue("icon"); if (componentIcon != null) { component.setIcon(componentIcon.getValue()); } Annotation componentDescriptionAnnotation = attr .getAnnotation("streamflow.annotations.Description"); if (componentDescriptionAnnotation != null) { StringMemberValue componentDescription = (StringMemberValue) componentDescriptionAnnotation .getMemberValue("value"); if (componentDescription != null) { component.setDescription(componentDescription.getValue()); } } Annotation componentInputsAnnotation = attr .getAnnotation("streamflow.annotations.ComponentInputs"); if (componentInputsAnnotation != null) { ArrayList<ComponentInterface> inputs = new ArrayList<ComponentInterface>(); ArrayMemberValue componentInputs = (ArrayMemberValue) componentInputsAnnotation .getMemberValue("value"); for (MemberValue value : componentInputs.getValue()) { AnnotationMemberValue annotationMember = (AnnotationMemberValue) value; Annotation annotationValue = annotationMember.getValue(); StringMemberValue keyAnnotationValue = (StringMemberValue) annotationValue .getMemberValue("key"); StringMemberValue descriptionAnnotationValue = (StringMemberValue) annotationValue .getMemberValue("description"); ComponentInterface inputInterface = new ComponentInterface(); if (keyAnnotationValue != null) { inputInterface.setKey(keyAnnotationValue.getValue()); } if (descriptionAnnotationValue != null) { inputInterface.setDescription(descriptionAnnotationValue.getValue()); } inputs.add(inputInterface); } component.setInputs(inputs); } Annotation componentOutputsAnnotation = attr .getAnnotation("streamflow.annotations.ComponentOutputs"); if (componentOutputsAnnotation != null) { ArrayList<ComponentInterface> outputs = new ArrayList<ComponentInterface>(); ArrayMemberValue componentOutputs = (ArrayMemberValue) componentOutputsAnnotation .getMemberValue("value"); for (MemberValue value : componentOutputs.getValue()) { AnnotationMemberValue annotationMember = (AnnotationMemberValue) value; Annotation annotationValue = annotationMember.getValue(); StringMemberValue keyAnnotationValue = (StringMemberValue) annotationValue .getMemberValue("key"); StringMemberValue descriptionAnnotationValue = (StringMemberValue) annotationValue .getMemberValue("description"); ComponentInterface outputInterface = new ComponentInterface(); if (keyAnnotationValue != null) { outputInterface.setKey(keyAnnotationValue.getValue()); } if (descriptionAnnotationValue != null) { outputInterface.setDescription(descriptionAnnotationValue.getValue()); } outputs.add(outputInterface); } component.setOutputs(outputs); } List<MethodInfo> memberMethods = cf.getMethods(); if (memberMethods != null) { ArrayList<ComponentProperty> properties = new ArrayList<ComponentProperty>(); for (MethodInfo method : memberMethods) { AnnotationsAttribute methodAttr = (AnnotationsAttribute) method .getAttribute(AnnotationsAttribute.visibleTag); if (methodAttr == null) { continue; } Annotation propertyAnnotation = methodAttr .getAnnotation("streamflow.annotations.ComponentProperty"); if (propertyAnnotation == null) { continue; } ComponentProperty property = new ComponentProperty(); StringMemberValue propertyName = (StringMemberValue) propertyAnnotation .getMemberValue("name"); if (propertyName != null) { property.setName(propertyName.getValue()); } StringMemberValue propertylabel = (StringMemberValue) propertyAnnotation .getMemberValue("label"); if (propertylabel != null) { property.setLabel(propertylabel.getValue()); } StringMemberValue propertyType = (StringMemberValue) propertyAnnotation .getMemberValue("type"); if (propertyType != null) { property.setType(propertyType.getValue()); } StringMemberValue propertyDefaultValue = (StringMemberValue) propertyAnnotation .getMemberValue("defaultValue"); if (propertyDefaultValue != null) { property.setDefaultValue(propertyDefaultValue.getValue()); } BooleanMemberValue propertyRequired = (BooleanMemberValue) propertyAnnotation .getMemberValue("required"); if (propertyRequired != null) { property.setRequired(propertyRequired.getValue()); } Annotation methodDescriptionAnnotation = methodAttr .getAnnotation("streamflow.annotations.Description"); if (methodDescriptionAnnotation != null) { StringMemberValue methodDescription = (StringMemberValue) methodDescriptionAnnotation .getMemberValue("value"); if (methodDescription != null) { property.setDescription(methodDescription.getValue()); } } properties.add(property); } component.setProperties(properties); } components.add(component); } } config.setComponents(components); // return null if no framework annotations were located if (foundFrameworkAnnotations == false) { return null; } return config; } catch (IOException ex) { LOG.error("Error while parsing framework annotations: ", ex); throw new EntityInvalidException("Error while parsing framework annotations: " + ex.getMessage()); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { LOG.error("Error while closing framework zip"); } } } }
From source file:org.geoserver.kml.KMLReflectorTest.java
protected void doTestRasterPlacemark(boolean doPlacemarks) throws Exception { // the style selects a single feature final String requestUrl = "wms/kml?layers=" + getLayerId(MockData.BASIC_POLYGONS) + "&styles=&mode=download&kmscore=0&format_options=kmplacemark:" + doPlacemarks + "&format=" + KMZMapOutputFormat.MIME_TYPE; MockHttpServletResponse response = getAsServletResponse(requestUrl); assertEquals(KMZMapOutputFormat.MIME_TYPE, response.getContentType()); ZipFile zipFile = null; try {/*from w w w .j a v a2s . c o m*/ // create the kmz File tempDir = org.geoserver.data.util.IOUtils.createRandomDirectory("./target", "kmplacemark", "test"); tempDir.deleteOnExit(); File zip = new File(tempDir, "kmz.zip"); zip.deleteOnExit(); FileOutputStream output = new FileOutputStream(zip); FileUtils.writeByteArrayToFile(zip, getBinary(response)); output.flush(); output.close(); assertTrue(zip.exists()); // unzip and test it zipFile = new ZipFile(zip); ZipEntry entry = zipFile.getEntry("wms.kml"); assertNotNull(entry); assertNotNull(zipFile.getEntry("images/layers_0.png")); // unzip the wms.kml to file byte[] buffer = new byte[1024]; int len; InputStream inStream = zipFile.getInputStream(entry); File temp = File.createTempFile("test_out", "kmz", tempDir); temp.deleteOnExit(); BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(temp)); while ((len = inStream.read(buffer)) >= 0) outStream.write(buffer, 0, len); inStream.close(); outStream.close(); // read in the wms.kml and check its contents Document document = dom(new BufferedInputStream(new FileInputStream(temp))); // print(document); assertEquals("kml", document.getDocumentElement().getNodeName()); if (doPlacemarks) { assertEquals(getFeatureSource(MockData.BASIC_POLYGONS).getFeatures().size(), document.getElementsByTagName("Placemark").getLength()); XMLAssert.assertXpathEvaluatesTo("3", "count(//kml:Placemark//kml:Point)", document); } else { assertEquals(0, document.getElementsByTagName("Placemark").getLength()); } } finally { if (zipFile != null) { zipFile.close(); } } }
From source file:net.sf.sripathi.ws.mock.util.Folder.java
public void createFilesAndFolder(ZipFile zip) { @SuppressWarnings("unchecked") Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries(); Set<String> files = new TreeSet<String>(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.getName().toLowerCase().endsWith(".wsdl") || entry.getName().toLowerCase().endsWith(".xsd")) files.add(entry.getName());//from ww w. j a v a 2s . c om } for (String fileStr : files) { String[] split = fileStr.split("/"); Folder parent = this; if (split.length > 1) { Folder sub = null; for (int i = 0; i < split.length - 1; i++) { sub = parent.getSubFolderByName(split[i]); if (sub == null) { sub = parent.createSubFolder(split[i]); } parent = sub; } } File file = parent.createFile(split[split.length - 1]); FileOutputStream fos = null; InputStream zipStream = null; try { fos = new FileOutputStream(file); zipStream = zip.getInputStream(zip.getEntry(fileStr)); fos.write(IOUtils.toByteArray(zipStream)); } catch (Exception e) { throw new MockException("Unable to create file - " + fileStr); } finally { try { fos.close(); } catch (Exception e) { } try { zipStream.close(); } catch (Exception e) { } } } }