Java Code Examples for java.util.jar.JarEntry

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Application-Builder, under directory /src/main/java/org/silverpeas/applicationbuilder/.

Source file: ReadOnlyArchive.java

  20 
vote

/** 
 * @param entry the entry to read
 * @return the stream for reading the contents of the entry
 * @since 1.0/B
 * @roseuid 3AB080F602D2
 */
public long getEntrySize(ApplicationBuilderItem entry){
  long size=0;
  JarEntry jarEntry=null;
  jarEntry=getJarEntry(entry);
  if (jarEntry != null) {
    size=jarEntry.getSize();
  }
  return size;
}
 

Example 2

From project apb, under directory /modules/apb-base/src/apb/tasks/.

Source file: JarTask.java

  19 
vote

private void writeToJar(JarOutputStream jarOut,final String fileName,final InputStream is,Set<String> addedDirs) throws IOException {
  writeParentDirs(jarOut,fileName,addedDirs);
  logVerbose("Adding entry... %s\n",fileName);
  JarEntry entry=new JarEntry(fileName);
  jarOut.putNextEntry(entry);
  byte[] arr=new byte[1024];
  int n;
  while ((n=is.read(arr)) > 0) {
    jarOut.write(arr,0,n);
  }
  is.close();
  jarOut.flush();
}
 

Example 3

From project artimate, under directory /artimate-demo/src/main/java/com/jdotsoft/jarloader/.

Source file: JarClassLoader.java

  18 
vote

private JarEntryInfo findJarEntry(String sName){
  for (  JarFileInfo jarFileInfo : lstJarFile) {
    JarFile jarFile=jarFileInfo.jarFile;
    JarEntry jarEntry=jarFile.getJarEntry(sName);
    if (jarEntry != null) {
      return new JarEntryInfo(jarFileInfo,jarEntry);
    }
  }
  return null;
}
 

Example 4

From project bundlemaker, under directory /main/org.bundlemaker.core/src/org/bundlemaker/core/internal/modules/modularizedsystem/.

Source file: AbstractTransformationAwareModularizedSystem.java

  18 
vote

/** 
 * <p> </p>
 * @param file
 * @return
 * @throws IOException
 */
private static List<String> getContainedTypesFromJarFile(File file) throws IOException {
  List<String> result=new LinkedList<String>();
  JarFile jarFile=new JarFile(file);
  Enumeration<JarEntry> entries=jarFile.entries();
  while (entries.hasMoreElements()) {
    JarEntry jarEntry=(JarEntry)entries.nextElement();
    if (jarEntry.getName().endsWith(".class")) {
      result.add(jarEntry.getName().substring(0,jarEntry.getName().length() - ".class".length()).replace('/','.'));
    }
  }
  return result;
}
 

Example 5

From project Coffee-Framework, under directory /coffeeframework-core/src/main/java/coffee/resources/.

Source file: ServletContextResourceLoader.java

  18 
vote

public List<String> retrieveResourcesFromJar(String jarName) throws IOException, ClassNotFoundException {
  ArrayList<String> list=new ArrayList<String>();
  JarInputStream stream=new JarInputStream(servletContext.getResourceAsStream(jarName));
  while (true) {
    JarEntry entry=stream.getNextJarEntry();
    if (entry == null)     break;
    list.add(entry.getName());
  }
  stream.close();
  return list;
}
 

Example 6

From project cp-common-utils, under directory /src/com/clarkparsia/common/util/.

Source file: ClassPath.java

  18 
vote

/** 
 * Return the list of classes from a JarFile object
 * @param theFile the JarFile to get classes from
 * @return the list of classes in the jar file
 */
private static Collection<? extends Class> listClassesFromJarFile(JarFile theFile){
  Collection<Class> aClassList=new HashSet<Class>();
  Enumeration<JarEntry> aEntries=theFile.entries();
  while (aEntries.hasMoreElements()) {
    JarEntry aEntry=aEntries.nextElement();
    if (aEntry.getName().endsWith(".class")) {
      Class aClass=_class(classNameFromFileName(aEntry.getName()));
      if (aClass != null) {
        aClassList.add(aClass);
      }
    }
  }
  return aClassList;
}
 

Example 7

From project crunch, under directory /crunch/src/test/java/org/apache/crunch/.

Source file: WordCountHBaseTest.java

  18 
vote

private void jarUp(JarOutputStream jos,File baseDir,String classDir) throws IOException {
  File file=new File(baseDir,classDir);
  JarEntry e=new JarEntry(classDir);
  e.setTime(file.lastModified());
  jos.putNextEntry(e);
  ByteStreams.copy(new FileInputStream(file),jos);
  jos.closeEntry();
}
 

Example 8

From project etherpad, under directory /infrastructure/yuicompressor/src/com/yahoo/platform/yui/compressor/.

Source file: JarClassLoader.java

  18 
vote

private static JarEntry findJarEntry(JarFile jarFile,String entryName){
  Enumeration entries=jarFile.entries();
  while (entries.hasMoreElements()) {
    JarEntry entry=(JarEntry)entries.nextElement();
    if (entry.getName().equals(entryName)) {
      return entry;
    }
  }
  return null;
}
 

Example 9

From project gedcom5-conversion, under directory /src/test/java/org/gedcomx/tools/.

Source file: Gedcom2GedcomxTest.java

  18 
vote

private static void printEntry(Object jarEntry) throws IOException {
  JarEntry entry=(JarEntry)jarEntry;
  String name=entry.getName();
  long size=entry.getSize();
  long compressedSize=entry.getCompressedSize();
  Attributes attributes=entry.getAttributes();
  System.out.print(name + "\t" + size+ "\t"+ compressedSize+ "\t");
  printAttributes(attributes);
}
 

Example 10

From project geronimo-xbean, under directory /xbean-blueprint/src/main/java/org/apache/xbean/blueprint/generator/.

Source file: QdoxMappingLoader.java

  18 
vote

private static void listAllJarEntries(File base,String[] excludedClasses,JavaDocBuilder builder) throws IOException {
  JarFile jarFile=new JarFile(base);
  for (Enumeration entries=jarFile.entries(); entries.hasMoreElements(); ) {
    JarEntry entry=(JarEntry)entries.nextElement();
    String name=entry.getName();
    if (name.endsWith(".java") && !isExcluded(name,excludedClasses) && !name.endsWith("/package-info.java")) {
      builder.addSource(new URL("jar:" + base.toURL().toString() + "!/"+ name));
    }
  }
}
 

Example 11

From project imageflow, under directory /src/de/danielsenff/imageflow/controller/.

Source file: JarUnitXMLLoader.java

  18 
vote

@Override protected void retrieveRelevantXMLPaths(Enumeration entries,Set<String> relevantXmlFiles){
  while (entries.hasMoreElements()) {
    JarEntry entry=(JarEntry)entries.nextElement();
    String absoluteName=entry.getName();
    if (absoluteName.startsWith(DelegatesController.getUnitFolderName())) {
      String fileName=absoluteName.substring(DelegatesController.getUnitFolderName().length());
      if (fileName.startsWith("."))       continue;
      if (fileName.endsWith("/"))       continue;
      relevantXmlFiles.add(fileName);
    }
  }
}
 

Example 12

From project JavalibCore, under directory /src/main/java/org/robotframework/javalib/beans/annotation/.

Source file: KeywordBeanLoader.java

  18 
vote

private void addJarKeywords(IClassFilter classFilter,Map kws,URL url) throws IOException {
  JarURLConnection connection=(JarURLConnection)url.openConnection();
  File jar=new File(connection.getJarFileURL().getFile());
  JarInputStream is=new JarInputStream(new FileInputStream(jar));
  JarEntry entry;
  while ((entry=is.getNextJarEntry()) != null) {
    if (entry.getName().endsWith(".class")) {
      addKeyword(classFilter,kws,entry.getName());
    }
  }
}
 

Example 13

From project jboss-vfs, under directory /src/main/java/org/jboss/vfs/spi/.

Source file: JavaZipFileSystem.java

  18 
vote

/** 
 * {@inheritDoc} 
 */
public long getSize(VirtualFile mountPoint,VirtualFile target){
  final ZipNode zipNode=getZipNode(mountPoint,target);
  if (zipNode == null) {
    return 0L;
  }
  final File cachedFile=zipNode.cachedFile;
  final JarEntry entry=zipNode.entry;
  if (zipNode == rootNode) {
    return archiveFile.length();
  }
  return cachedFile != null ? cachedFile.length() : entry == null ? 0L : entry.getSize();
}
 

Example 14

From project jPOS, under directory /jpos/src/main/java/org/jpos/q2/.

Source file: CLIPrefixedClassNameCompletor.java

  18 
vote

private static List<String> resolveModuleEntriesFromJar(URL url,String _prefix) throws IOException {
  final String prefix=_prefix.endsWith("/") ? _prefix : _prefix + "/";
  List<String> resourceList=new ArrayList<String>();
  JarURLConnection conn=(JarURLConnection)url.openConnection();
  Enumeration entries=conn.getJarFile().entries();
  while (entries.hasMoreElements()) {
    JarEntry entry=(JarEntry)entries.nextElement();
    String name=entry.getName();
    if (name.startsWith(prefix) && !entry.isDirectory()) {
      resourceList.add(name);
    }
  }
  return resourceList;
}
 

Example 15

From project jPOS-EE, under directory /modules/core/src/main/java/org/jpos/ee/support/.

Source file: ModuleUtils.java

  18 
vote

private static List<String> resolveModuleEntriesFromJar(URL url,String _prefix) throws IOException {
  final String prefix=_prefix.endsWith("/") ? _prefix : _prefix + "/";
  List<String> resourceList=new ArrayList<String>();
  JarURLConnection conn=(JarURLConnection)url.openConnection();
  Enumeration entries=conn.getJarFile().entries();
  while (entries.hasMoreElements()) {
    JarEntry entry=(JarEntry)entries.nextElement();
    String name=entry.getName();
    if (name.startsWith(prefix) && !entry.isDirectory()) {
      resourceList.add(name);
    }
  }
  return resourceList;
}
 

Example 16

From project json-schema-validator, under directory /src/test/java/org/eel/kitchen/jsonschema/other/.

Source file: JarNamespaceValidationTest.java

  18 
vote

private void doWriteJar(final JarOutputStream jarfh,final URI baseURI) throws IOException {
  final File src=new File(baseURI.getPath());
  String basePath=rootURI.relativize(baseURI).getPath();
  if (src.isDirectory() && !basePath.endsWith("/"))   basePath+="/";
  final JarEntry entry=new JarEntry(basePath);
  jarfh.putNextEntry(entry);
  if (src.isDirectory()) {
    for (    final File file : src.listFiles())     doWriteJar(jarfh,file.toURI());
    return;
  }
  Files.copy(src,jarfh);
}
 

Example 17

From project JsTestDriver, under directory /JsTestDriver/lib/yuicompressor-2.4.2/src/com/yahoo/platform/yui/compressor/.

Source file: JarClassLoader.java

  18 
vote

private static JarEntry findJarEntry(JarFile jarFile,String entryName){
  Enumeration entries=jarFile.entries();
  while (entries.hasMoreElements()) {
    JarEntry entry=(JarEntry)entries.nextElement();
    if (entry.getName().equals(entryName)) {
      return entry;
    }
  }
  return null;
}
 

Example 18

From project jumpnevolve, under directory /src/com/jdotsoft/jarloader/.

Source file: JarClassLoader.java

  18 
vote

private JarEntryInfo findJarEntry(String sName){
  for (  JarFile jarFile : this.lstJarFile) {
    JarEntry jarEntry=jarFile.getJarEntry(sName);
    if (jarEntry != null) {
      return new JarEntryInfo(jarFile,jarEntry);
    }
  }
  return null;
}
 

Example 19

From project Junit-DynamicSuite, under directory /src/main/java/org/junit/extensions/dynamicsuite/engine/.

Source file: ClassPathScanner.java

  18 
vote

private void loadJarEntries(JarFile jar){
  Enumeration<JarEntry> entries=jar.entries();
  while (entries.hasMoreElements()) {
    JarEntry element=entries.nextElement();
    String name=element.getName();
    if (name.toLowerCase().endsWith(".class")) {
      String className=StringUtils.replace(name,"/",".");
      className=StringUtils.removeEnd(className,".class");
      foundClasses.add(className);
    }
  }
}
 

Example 20

From project juzu, under directory /core/src/main/java/juzu/impl/fs/spi/jar/.

Source file: JarFileSystem.java

  18 
vote

public JarFileSystem(JarFile f) throws IOException {
  this.jar=f;
  this.jarURL=new File(f.getName()).toURI().toURL();
  JarPath root=new JarPath(this);
  for (Enumeration<JarEntry> en=jar.entries(); en.hasMoreElements(); ) {
    JarEntry entry=en.nextElement();
    root.append(entry);
  }
  this.root=root;
}
 

Example 21

From project kernel_1, under directory /exo.kernel.component.common/src/main/java/org/exoplatform/services/compress/.

Source file: CompressData.java

  18 
vote

public JarOutputStream addToArchive(JarOutputStream jarOutput,InputStream input,String entryName1) throws Exception {
  byte data[]=new byte[BUFFER];
  JarEntry entry=new JarEntry(entryName1);
  jarOutput.putNextEntry(entry);
  if (input != null) {
    int count;
    while ((count=input.read(data,0,BUFFER)) != EOF)     jarOutput.write(data,0,count);
  }
  jarOutput.closeEntry();
  return jarOutput;
}
 

Example 22

From project linkedin-utils, under directory /org.linkedin.util-core/src/main/java/org/linkedin/util/io/resource/.

Source file: JarResource.java

  18 
vote

private static InputStream extractInputStream(JarFile jarFile,String location,Resource resource) throws IOException {
  JarEntry jarEntry=jarFile.getJarEntry(location);
  if (jarEntry == null)   throw new IOException("cannot get input stream for entry " + location + " for "+ resource.toURI());
  if (jarEntry.getSize() == 0) {
    JarEntry directoryEntry=jarFile.getJarEntry(PathUtils.addTrailingSlash(location));
    if (directoryEntry != null)     throw new IOException("cannot read directory for " + resource.toURI());
  }
  InputStream is=jarFile.getInputStream(jarEntry);
  if (is == null) {
    throw new IOException("cannot get input stream for entry " + jarEntry + " for "+ resource.toURI());
  }
  return is;
}
 

Example 23

From project liquibase, under directory /liquibase-core/src/main/java/liquibase/integration/commandline/.

Source file: Main.java

  18 
vote

private void addWarFileClasspathEntries(File classPathFile,List<URL> urls) throws IOException {
  URL url=new URL("jar:" + classPathFile.toURL() + "!/WEB-INF/classes/");
  urls.add(url);
  JarFile warZip=new JarFile(classPathFile);
  Enumeration<? extends JarEntry> entries=warZip.entries();
  while (entries.hasMoreElements()) {
    JarEntry entry=entries.nextElement();
    if (entry.getName().startsWith("WEB-INF/lib") && entry.getName().toLowerCase().endsWith(".jar")) {
      File jar=extract(warZip,entry);
      urls.add(new URL("jar:" + jar.toURL() + "!/"));
      jar.deleteOnExit();
    }
  }
}
 

Example 24

From project maven-shared, under directory /maven-dependency-analyzer/src/main/java/org/apache/maven/shared/dependency/analyzer/.

Source file: ClassFileVisitorUtils.java

  18 
vote

private static void acceptJar(URL url,ClassFileVisitor visitor) throws IOException {
  JarInputStream in=new JarInputStream(url.openStream());
  JarEntry entry=null;
  while ((entry=in.getNextJarEntry()) != null) {
    String name=entry.getName();
    if (name.endsWith(".class")) {
      visitClass(name,in,visitor);
    }
  }
  in.close();
}
 

Example 25

From project ALP, under directory /workspace/alp-reporter/src/main/java/com/lohika/alp/reporter/helpers/.

Source file: Resources.java

  17 
vote

/** 
 * Copy JAR resources from path to outside destination. If destination does not exist, it will be created
 * @param jar package with required resources
 * @param path resources path inside package. Should end with "/", but not start with one
 * @param destination outside destination
 * @throws IOException
 */
public void copy(JarFile jar,String path,File destination) throws IOException {
  logger.debug("Copying " + path + " to "+ destination);
  Enumeration<JarEntry> entries=jar.entries();
  int len=path.length();
  while (entries.hasMoreElements()) {
    JarEntry entry=entries.nextElement();
    String name=entry.getName();
    if (name.startsWith(path)) {
      File file=new File(destination,name.substring(len));
      if (entry.isDirectory())       file.mkdir();
 else {
        InputStream is=jar.getInputStream(entry);
        FileOutputStream os=new FileOutputStream(file);
        while (is.available() > 0) {
          os.write(is.read());
        }
        os.close();
        is.close();
      }
    }
  }
}
 

Example 26

From project android_build, under directory /tools/signapk/.

Source file: SignApk.java

  17 
vote

/** 
 * Add the SHA1 of every file to the manifest, creating it if necessary. 
 */
private static Manifest addDigestsToManifest(JarFile jar) throws IOException, GeneralSecurityException {
  Manifest input=jar.getManifest();
  Manifest output=new Manifest();
  Attributes main=output.getMainAttributes();
  if (input != null) {
    main.putAll(input.getMainAttributes());
  }
 else {
    main.putValue("Manifest-Version","1.0");
    main.putValue("Created-By","1.0 (Android SignApk)");
  }
  BASE64Encoder base64=new BASE64Encoder();
  MessageDigest md=MessageDigest.getInstance("SHA1");
  byte[] buffer=new byte[4096];
  int num;
  TreeMap<String,JarEntry> byName=new TreeMap<String,JarEntry>();
  for (Enumeration<JarEntry> e=jar.entries(); e.hasMoreElements(); ) {
    JarEntry entry=e.nextElement();
    byName.put(entry.getName(),entry);
  }
  for (  JarEntry entry : byName.values()) {
    String name=entry.getName();
    if (!entry.isDirectory() && !name.equals(JarFile.MANIFEST_NAME) && !name.equals(CERT_SF_NAME)&& !name.equals(CERT_RSA_NAME)&& (stripPattern == null || !stripPattern.matcher(name).matches())) {
      InputStream data=jar.getInputStream(entry);
      while ((num=data.read(buffer)) > 0) {
        md.update(buffer,0,num);
      }
      Attributes attr=null;
      if (input != null)       attr=input.getAttributes(name);
      attr=attr != null ? new Attributes(attr) : new Attributes();
      attr.putValue("SHA1-Digest",base64.encode(md.digest()));
      output.getEntries().put(name,attr);
    }
  }
  return output;
}
 

Example 27

From project ant4eclipse, under directory /org.ant4eclipse.lib.jdt.ecj/src/org/ant4eclipse/lib/jdt/ecj/internal/tools/loader/.

Source file: ClasspathClassFileLoaderImpl.java

  17 
vote

/** 
 * <p> Returns all the names of the packages that are contained in the specified jar file. The package list contains the packages that contain classes as well as all parent packages of those. </p>
 * @param jar
 * @return
 * @throws IOException
 */
private String[] getAllPackagesFromJar(File jar){
  Assure.isFile("jar",jar);
  List<String> result=new LinkedList<String>();
  JarFile jarFile=null;
  try {
    jarFile=new JarFile(jar);
  }
 catch (  IOException e) {
    throw new Ant4EclipseException(EcjExceptionCodes.COULD_NOT_CREATE_JAR_FILE_FROM_FILE_EXCEPTION,jar.getAbsolutePath());
  }
  Enumeration<?> enumeration=jarFile.entries();
  while (enumeration.hasMoreElements()) {
    JarEntry jarEntry=(JarEntry)enumeration.nextElement();
    String directoryName=null;
    if (jarEntry.isDirectory()) {
      directoryName=jarEntry.getName();
    }
 else {
      int splitIndex=jarEntry.getName().lastIndexOf('/');
      if (splitIndex != -1) {
        directoryName=jarEntry.getName().substring(0,splitIndex);
      }
    }
    if (directoryName != null) {
      String packageName=directoryName.replace('/','.');
      packageName=packageName.endsWith(".") ? packageName.substring(0,packageName.length() - 1) : packageName;
      String[] packages=allPackages(packageName);
      for (int i=0; i < packages.length; i++) {
        if (!result.contains(packages[i])) {
          result.add(packages[i]);
        }
      }
    }
  }
  return result.toArray(new String[0]);
}
 

Example 28

From project any23, under directory /core/src/main/java/org/apache/any23/util/.

Source file: DiscoveryUtils.java

  17 
vote

/** 
 * Find all classes within a JAR in a given prefix addressed with syntax <code>file:<path/to.jar>!<path/to/package>.
 * @param location package location.
 * @return list of detected classes.
 */
private static List<Class> findClassesInJAR(String location){
  final String[] sections=location.split("!");
  if (sections.length != 2) {
    throw new IllegalArgumentException("Invalid JAR location.");
  }
  final String jarLocation=sections[0].substring(FILE_PREFIX.length());
  final String packagePath=sections[1].substring(1);
  try {
    final JarFile jarFile=new JarFile(jarLocation);
    final Enumeration<JarEntry> entries=jarFile.entries();
    final List<Class> result=new ArrayList<Class>();
    JarEntry current;
    String entryName;
    String clazzName;
    Class clazz;
    while (entries.hasMoreElements()) {
      current=entries.nextElement();
      entryName=current.getName();
      if (StringUtils.isPrefix(packagePath,entryName) && StringUtils.isSuffix(CLASS_SUFFIX,entryName) && !entryName.contains("$")) {
        try {
          clazzName=entryName.substring(0,entryName.length() - CLASS_SUFFIX.length()).replaceAll("/",".");
          clazz=Class.forName(clazzName);
        }
 catch (        ClassNotFoundException cnfe) {
          throw new IllegalStateException("Error while loading detected class.",cnfe);
        }
        result.add(clazz);
      }
    }
    return result;
  }
 catch (  IOException ioe) {
    throw new RuntimeException("Error while opening JAR file.",ioe);
  }
}
 

Example 29

From project BetterMechanics, under directory /src/net/edoxile/bettermechanics/handlers/.

Source file: ConfigHandler.java

  17 
vote

public static void createConfig(BetterMechanics plugin){
  configFile=new File(plugin.getDataFolder(),"config.yml");
  cauldronConfigFile=new File(plugin.getDataFolder(),"cauldron-recipes.yml");
  try {
    JarFile jar=new JarFile(plugin.getJarFile());
    JarEntry entry=jar.getJarEntry("config.yml");
    InputStream is=jar.getInputStream(entry);
    FileOutputStream os=new FileOutputStream(configFile);
    byte[] buf=new byte[(int)entry.getSize()];
    if (is.read(buf,0,(int)entry.getSize()) == (int)entry.getSize()) {
      os.write(buf);
      os.close();
    }
 else {
      BetterMechanics.log("Error while creating new config: buffer overflow",Level.WARNING);
    }
    jar=new JarFile(plugin.getJarFile());
    entry=jar.getJarEntry("cauldron-recipes.yml");
    is=jar.getInputStream(entry);
    os=new FileOutputStream(cauldronConfigFile);
    buf=new byte[(int)entry.getSize()];
    if (is.read(buf,0,(int)entry.getSize()) == (int)entry.getSize()) {
      os.write(buf);
      os.close();
    }
 else {
      BetterMechanics.log("Error while creating new cauldron-config: buffer overflow",Level.WARNING);
    }
  }
 catch (  IOException e) {
    BetterMechanics.log("Couldn't write to config file");
  }
}
 

Example 30

From project big-data-plugin, under directory /src/org/pentaho/di/job/entries/hadoopjobexecutor/.

Source file: JarUtility.java

  17 
vote

public static List<Class<?>> getClassesInJar(String jarUrl,ClassLoader parentClassloader) throws MalformedURLException {
  URL url=new URL(jarUrl);
  URL[] urls=new URL[]{url};
  URLClassLoader loader=new URLClassLoader(urls,parentClassloader);
  ArrayList<Class<?>> classes=new ArrayList<Class<?>>();
  try {
    JarInputStream jarFile=new JarInputStream(new FileInputStream(new File(url.toURI())));
    JarEntry jarEntry;
    while (true) {
      jarEntry=jarFile.getNextJarEntry();
      if (jarEntry == null) {
        break;
      }
      if (jarEntry.getName().endsWith(".class")) {
        String className=jarEntry.getName().substring(0,jarEntry.getName().indexOf(".class")).replaceAll("/","\\.");
        classes.add(loader.loadClass(className));
      }
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return classes;
}
 

Example 31

From project Blitz, under directory /src/com/laxser/blitz/scanning/vfs/.

Source file: JarFileObject.java

  17 
vote

@Override public FileObject[] getChildren() throws IOException {
  List<FileObject> children=new LinkedList<FileObject>();
  Enumeration<JarEntry> e=jarFile.entries();
  String entryName=root == this ? "" : entry.getName();
  while (e.hasMoreElements()) {
    JarEntry entry=e.nextElement();
    if (entry.getName().length() > entryName.length() && entry.getName().startsWith(entryName)) {
      int index=entry.getName().indexOf('/',entryName.length() + 1);
      if (index == -1 || index == entry.getName().length() - 1) {
        children.add(fs.resolveFile(root.urlString + entry.getName()));
      }
    }
  }
  return children.toArray(new FileObject[0]);
}
 

Example 32

From project ceres, under directory /ceres-deploy/src/main/java/com/bc/ceres/deploy/.

Source file: DeployMain.java

  17 
vote

private void copyIntoJar(File baseDir,String basePath,JarOutputStream jarOutputStream) throws IOException {
  String[] fileNames=baseDir.list();
  if (fileNames != null) {
    for (    String fileName : fileNames) {
      String entryName=basePath + (basePath.length() > 0 ? "/" : "") + fileName;
      File file=new File(baseDir,fileName);
      if (file.isDirectory()) {
        copyIntoJar(file,entryName,jarOutputStream);
      }
 else {
        FileInputStream fileInputStream=new FileInputStream(file);
        try {
          JarEntry jarEntry=new JarEntry(entryName);
          jarOutputStream.putNextEntry(jarEntry);
          copy(fileInputStream,jarOutputStream);
          jarOutputStream.closeEntry();
        }
  finally {
          fileInputStream.close();
        }
      }
    }
  }
}
 

Example 33

From project ceylon-module-resolver, under directory /impl/src/main/java/com/redhat/ceylon/cmr/util/.

Source file: JarUtils.java

  17 
vote

public static void finishUpdatingJar(File originalFile,File outputFile,ArtifactContext context,JarOutputStream jarOutputStream,JarEntryFilter filter,RepositoryManager repoManager,boolean verbose,Logger log) throws IOException {
  if (originalFile != null) {
    JarFile jarFile=new JarFile(originalFile);
    Enumeration<JarEntry> entries=jarFile.entries();
    while (entries.hasMoreElements()) {
      JarEntry entry=entries.nextElement();
      if (filter.avoid(entry.getName()))       continue;
      ZipEntry copiedEntry=new ZipEntry(entry.getName());
      copiedEntry.setTime(entry.getTime());
      copiedEntry.setComment(entry.getComment());
      jarOutputStream.putNextEntry(copiedEntry);
      InputStream inputStream=jarFile.getInputStream(entry);
      copy(inputStream,jarOutputStream);
      inputStream.close();
      jarOutputStream.closeEntry();
    }
    jarFile.close();
  }
  jarOutputStream.flush();
  jarOutputStream.close();
  if (verbose) {
    log.info("[done writing to jar: " + outputFile.getPath() + "]");
  }
  File sha1File=ShaSigner.sign(outputFile,log,verbose);
  try {
    context.setForceOperation(true);
    repoManager.putArtifact(context,outputFile);
    ArtifactContext sha1Context=context.getSha1Context();
    sha1Context.setForceOperation(true);
    repoManager.putArtifact(sha1Context,sha1File);
  }
 catch (  RuntimeException x) {
    log.error("Failed to write module to repository: " + x.getMessage());
    throw x;
  }
 finally {
    outputFile.delete();
    sha1File.delete();
  }
}
 

Example 34

From project com.idega.content, under directory /src/java/com/idega/content/themes/business/.

Source file: TemplatesLoader.java

  17 
vote

public void loadJar(File bundleJarFile,JarFile jarFile,String jarPath){
  JarEntry pageTemplatesEntry=jarFile.getJarEntry("resources/templates/" + PAGE_TEMPLATES_XML_FILE_NAME);
  JarEntry siteTemplatesEntry=jarFile.getJarEntry("resources/templates/" + SITE_TEMPLATES_XML_FILE_NAME);
  InputStream stream=null;
  if (pageTemplatesEntry != null) {
    try {
      stream=jarFile.getInputStream(pageTemplatesEntry);
      Document pageDocument=XmlUtil.getJDOMXMLDocument(stream);
      addPageTypesFromDocument(pageDocument);
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
 finally {
      IOUtil.closeInputStream(stream);
    }
  }
  if (siteTemplatesEntry != null) {
    try {
      stream=jarFile.getInputStream(siteTemplatesEntry);
      Document pageDocument=XmlUtil.getJDOMXMLDocument(stream);
      addSiteTemplatesFromDocument(pageDocument);
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
 finally {
      IOUtil.closeInputStream(stream);
    }
  }
}
 

Example 35

From project dolphin, under directory /org.adarsh.jutils/src/com/tan/util/.

Source file: JarSearcher.java

  17 
vote

public void process(boolean searchClass){
  JarFile jarFile=null;
  JarEntry jarEntry=null;
  String name;
  File file;
  Enumeration<JarEntry> entries;
  for (Iterator<File> iter=lists.iterator(); iter.hasNext(); ) {
    file=(File)iter.next();
    try {
      jarFile=new JarFile(file);
    }
 catch (    IOException e) {
      e.printStackTrace();
    }
    if (null != jarFile) {
      entries=jarFile.entries();
      while (entries.hasMoreElements()) {
        jarEntry=(JarEntry)entries.nextElement();
        name=jarEntry.getName();
        name=name.toLowerCase();
        if (searchClass) {
          searchClass(name,file,jarEntry);
        }
 else {
          searchJarContent(name,jarFile,jarEntry);
        }
      }
    }
  }
}
 

Example 36

From project drools-chance, under directory /drools-shapes/drools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/.

Source file: JarModelImpl.java

  17 
vote

public ByteArrayOutputStream buildJar(){
  Date now=new Date();
  Manifest manifest=new Manifest();
  manifest.getMainAttributes().putValue("Manifest-Version","1.0");
  manifest.getMainAttributes().putValue("Manifest-Version","1.0");
  try {
    ByteArrayOutputStream stream=new ByteArrayOutputStream();
    JarOutputStream out=new JarOutputStream(stream,manifest);
    for (    String name : getTraitNames()) {
      JarEntry jarAdd=new JarEntry(getDefaultPackage().replace(".","/") + "/" + name+ ".java");
      jarAdd.setTime(now.getTime());
      out.putNextEntry(jarAdd);
      out.write(((InterfaceHolder)getTrait(name)).getSource().getBytes());
      jarAdd=new JarEntry(getDefaultPackage().replace(".","/") + "/" + name+ ".class");
      jarAdd.setTime(now.getTime());
      out.putNextEntry(jarAdd);
      out.write(getCompiledTrait(name));
    }
    out.close();
    stream.close();
    return stream;
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
  return null;
}
 

Example 37

From project drools-semantics, under directory /src/main/java/org/drools/semantics/builder/model/.

Source file: JarModelImpl.java

  17 
vote

public ByteArrayOutputStream buildJar(){
  Date now=new Date();
  Manifest manifest=new Manifest();
  manifest.getMainAttributes().putValue("Manifest-Version","1.0");
  manifest.getMainAttributes().putValue("Manifest-Version","1.0");
  try {
    ByteArrayOutputStream stream=new ByteArrayOutputStream();
    JarOutputStream out=new JarOutputStream(stream,manifest);
    for (    String name : getTraitNames()) {
      System.out.println("Adding " + name);
      JarEntry jarAdd=new JarEntry(getPackage().replace(".","/") + "/" + name+ ".java");
      jarAdd.setTime(now.getTime());
      out.putNextEntry(jarAdd);
      out.write(((String)getTrait(name)).getBytes());
      jarAdd=new JarEntry(getPackage().replace(".","/") + "/" + name+ ".class");
      jarAdd.setTime(now.getTime());
      out.putNextEntry(jarAdd);
      out.write(getCompiledTrait(name));
    }
    out.close();
    stream.close();
    System.out.println("Adding completed OK");
    return stream;
  }
 catch (  Exception ex) {
    ex.printStackTrace();
    System.out.println("Error: " + ex.getMessage());
  }
  return null;
}
 

Example 38

From project Eclipse, under directory /com.mobilesorcery.sdk.core/src/com/mobilesorcery/sdk/core/.

Source file: Util.java

  17 
vote

private static ZipEntry createZipEntry(String relativePath,boolean isJar){
  relativePath=relativePath.replace('\\','/');
  if (relativePath.length() > 0 && relativePath.charAt(0) == '/') {
    relativePath=relativePath.substring(1);
  }
  return isJar ? new JarEntry(relativePath) : new ZipEntry(relativePath);
}
 

Example 39

From project entando-core-engine, under directory /src/main/java/com/agiletec/apsadmin/system/resource/.

Source file: JapsPluginLabelListener.java

  17 
vote

/** 
 * Fetch all the entries in the given (jar) input stream and look for the plugin directory.
 * @param is the input stream to analyse
 */
private Set<String> discoverJarPlugin(InputStream is){
  Set<String> plugins=new HashSet<String>();
  if (null == is)   return plugins;
  JarEntry je=null;
  try {
    JarInputStream jis=new JarInputStream(is);
    do {
      je=jis.getNextJarEntry();
      if (null != je) {
        String URL=je.toString();
        if (URL.contains(PLUGIN_DIRECTORY) && URL.endsWith(PLUGIN_APSADMIN_PATH)) {
          plugins.add(URL);
        }
      }
    }
 while (je != null);
  }
 catch (  Throwable t) {
    ApsSystemUtils.logThrowable(t,this,"discoverJarPlugin");
  }
  return plugins;
}
 

Example 40

From project esbt, under directory /src/org/scalastuff/osgitools/.

Source file: Osgiify.java

  17 
vote

private static TreeSet<String> findPackages(File file) throws IOException {
  TreeSet<String> result=new TreeSet<String>();
  JarFile jarFile=new JarFile(file);
  try {
    for (Enumeration<JarEntry> e=jarFile.entries(); e.hasMoreElements(); ) {
      JarEntry entry=e.nextElement();
      if (entry.getName().endsWith(".class")) {
        int index=entry.getName().lastIndexOf('/');
        if (index > 0) {
          String packageName=entry.getName().substring(0,index).replace('/','.');
          result.add(packageName);
        }
      }
    }
  }
  finally {
    jarFile.close();
  }
  return result;
}
 

Example 41

From project flapjack, under directory /flapjack-annotation/src/main/java/flapjack/annotation/util/.

Source file: JarFileClassLocator.java

  17 
vote

protected void findClasses(List<Class> classes,URL url,Pattern packageName){
  JarFile jarFile=null;
  try {
    JarURLConnection connection=(JarURLConnection)url.openConnection();
    connection.setUseCaches(false);
    jarFile=connection.getJarFile();
    Enumeration<JarEntry> entries=jarFile.entries();
    while (entries.hasMoreElements()) {
      JarEntry entry=entries.nextElement();
      if (isClass(entry) && isInPackage(entry,packageName)) {
        String fixedPath=entry.getName().replace("/",".");
        classes.add(loadClass(fixedPath.substring(0,fixedPath.lastIndexOf('.'))));
      }
    }
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
catch (  ClassNotFoundException e) {
    throw new RuntimeException(e);
  }
 finally {
    if (jarFile != null) {
      try {
        jarFile.close();
      }
 catch (      IOException e) {
      }
    }
  }
}
 

Example 42

From project Gemini-Blueprint, under directory /io/src/main/java/org/eclipse/gemini/blueprint/io/.

Source file: OsgiBundleResourcePatternResolver.java

  17 
vote

/** 
 * Checks the jar entries from the Bundle-Classpath for the given pattern.
 * @param list
 * @param ur
 */
private void findBundleClassPathMatchingJarEntries(List<String> list,URL url,String pattern) throws IOException {
  JarInputStream jis=new JarInputStream(url.openStream());
  Set<String> result=new LinkedHashSet<String>(8);
  boolean patternWithFolderSlash=pattern.startsWith(FOLDER_SEPARATOR);
  try {
    while (jis.available() > 0) {
      JarEntry jarEntry=jis.getNextJarEntry();
      if (jarEntry != null) {
        String entryPath=jarEntry.getName();
        if (entryPath.startsWith(FOLDER_SEPARATOR)) {
          if (!patternWithFolderSlash) {
            entryPath=entryPath.substring(FOLDER_SEPARATOR.length());
          }
        }
 else {
          if (patternWithFolderSlash) {
            entryPath=FOLDER_SEPARATOR.concat(entryPath);
          }
        }
        if (getPathMatcher().match(pattern,entryPath)) {
          result.add(entryPath);
        }
      }
    }
  }
  finally {
    try {
      jis.close();
    }
 catch (    IOException io) {
    }
  }
  if (logger.isTraceEnabled())   logger.trace("Found in nested jar [" + url + "] matching entries "+ result);
  list.addAll(result);
}
 

Example 43

From project gemini.web.gemini-web-container, under directory /org.eclipse.gemini.web.core/src/main/java/org/eclipse/gemini/web/internal/url/.

Source file: WebBundleScanner.java

  17 
vote

private void scanWarFile() throws IOException {
  JarInputStream jis=new JarInputStream(this.source.openStream());
  try {
    JarEntry entry;
    while ((entry=jis.getNextJarEntry()) != null) {
      String entryName=entry.getName();
      if (entryName.startsWith(LIB_ENTRY_PREFIX) && entryName.endsWith(JAR_SUFFIX)) {
        if (driveCallBackIfNewJarFound(entryName)) {
          JarInputStream nestedJis=new JarInputStream(jis);
          doScanNestedJar(entryName,nestedJis);
        }
      }
 else       if (entryName.startsWith(CLASSES_ENTRY_PREFIX) && entryName.endsWith(CLASS_SUFFIX)) {
        this.callBack.classFound(entry.getName().substring(CLASSES_ENTRY_PREFIX.length()));
      }
    }
  }
  finally {
    IOUtils.closeQuietly(jis);
  }
}
 

Example 44

From project glg2d, under directory /src/test/java/glg2d/misc/.

Source file: InstrumentPaint.java

  17 
vote

/** 
 * I hacked this together with duct tape and wire hangers, along with help from these two sites: <a href= "http://sleeplessinslc.blogspot.com/2008/09/java-instrumentation-with-jdk-16x-class.html" >http://sleeplessinslc.blogspot.com/2008/09/java-instrumentation-with-jdk- 16x-class.html</a> and <a href= "http://sleeplessinslc.blogspot.com/2008/07/java-instrumentation.html" >http://sleeplessinslc.blogspot.com/2008/07/java-instrumentation.html</a>.
 */
private static void instrument0() throws Exception {
  File jarFile=File.createTempFile("agent",".jar");
  jarFile.deleteOnExit();
  Manifest manifest=new Manifest();
  Attributes mainAttributes=manifest.getMainAttributes();
  mainAttributes.put(Attributes.Name.MANIFEST_VERSION,"1.0");
  mainAttributes.put(new Attributes.Name("Agent-Class"),InstrumentPaint.class.getName());
  mainAttributes.put(new Attributes.Name("Can-Retransform-Classes"),"true");
  mainAttributes.put(new Attributes.Name("Can-Redefine-Classes"),"true");
  JarOutputStream jos=new JarOutputStream(new FileOutputStream(jarFile),manifest);
  JarEntry agent=new JarEntry(InstrumentPaint.class.getName().replace('.','/') + ".class");
  jos.putNextEntry(agent);
  CtClass ctClass=ClassPool.getDefault().get(InstrumentPaint.class.getName());
  jos.write(ctClass.toBytecode());
  jos.closeEntry();
  JarEntry snip=new JarEntry("instrumentation.snip");
  jos.putNextEntry(snip);
  jos.write(getInstrumentationCode().getBytes());
  jos.closeEntry();
  jos.close();
  String name=ManagementFactory.getRuntimeMXBean().getName();
  VirtualMachine vm=VirtualMachine.attach(name.substring(0,name.indexOf('@')));
  vm.loadAgent(jarFile.getAbsolutePath());
  vm.detach();
}
 

Example 45

From project GraphLab, under directory /src/graphlab/ui/.

Source file: UI.java

  17 
vote

public static String extractHelpPlugin(BlackBoard blackboard,Plugger plugger,String index,String dest,String filter){
  try {
    File f=new File(dest);
    if (!f.isDirectory())     f.mkdir();
    f=new File(dest + "/" + index);
    if (!f.isFile()) {
      JarFile jarFile=new JarFile(plugger.files.get("help"));
      Enumeration<JarEntry> entries=jarFile.entries();
      while (entries.hasMoreElements()) {
        JarEntry je=entries.nextElement();
        if (!je.getName().startsWith(filter))         continue;
        System.out.println("Extracting " + je.getName());
        String fname=je.getName().substring(filter.length());
        if (je.isDirectory())         (new File(dest + "/" + fname)).mkdir();
 else {
          File efile=new File(dest,fname);
          InputStream in=new BufferedInputStream(jarFile.getInputStream(je));
          OutputStream out=new BufferedOutputStream(new FileOutputStream(efile));
          byte[] buffer=new byte[2048];
          for (; ; ) {
            int nBytes=in.read(buffer);
            if (nBytes <= 0)             break;
            out.write(buffer,0,nBytes);
          }
          out.flush();
          out.close();
          in.close();
        }
      }
    }
    return f.getAbsolutePath();
  }
 catch (  Exception e) {
    StaticUtils.addExceptiontoLog(e,blackboard);
  }
  return null;
}
 

Example 46

From project guvnorng, under directory /guvnorng-showcase/src/main/java/org/drools/guvnor/server/builder/.

Source file: ClassLoaderBuilder.java

  17 
vote

/** 
 * For a given list of Jars, create a class loader.
 */
public MapBackedClassLoader buildClassLoader(){
  MapBackedClassLoader mapBackedClassLoader=getMapBackedClassLoader();
  try {
    for (    JarInputStream jis : jarInputStreams) {
      JarEntry entry=null;
      byte[] buf=new byte[1024];
      int len=0;
      while ((entry=jis.getNextJarEntry()) != null) {
        if (!entry.isDirectory() && !entry.getName().endsWith(".java")) {
          ByteArrayOutputStream out=new ByteArrayOutputStream();
          while ((len=jis.read(buf)) >= 0) {
            out.write(buf,0,len);
          }
          mapBackedClassLoader.addResource(entry.getName(),out.toByteArray());
        }
      }
    }
  }
 catch (  IOException e) {
    throw new RulesRepositoryException(e);
  }
  return mapBackedClassLoader;
}
 

Example 47

From project hama, under directory /core/src/main/java/org/apache/hama/util/.

Source file: RunJar.java

  17 
vote

/** 
 * Unpack a jar file into a directory. 
 */
public static void unJar(File jarFile,File toDir) throws IOException {
  JarFile jar=new JarFile(jarFile);
  try {
    Enumeration<JarEntry> entries=jar.entries();
    while (entries.hasMoreElements()) {
      JarEntry entry=entries.nextElement();
      if (!entry.isDirectory()) {
        InputStream in=jar.getInputStream(entry);
        try {
          File file=new File(toDir,entry.getName());
          file.getParentFile().mkdirs();
          OutputStream out=new FileOutputStream(file);
          try {
            byte[] buffer=new byte[8192];
            int i;
            while ((i=in.read(buffer)) != -1) {
              out.write(buffer,0,i);
            }
          }
  finally {
            out.close();
          }
        }
  finally {
          in.close();
        }
      }
    }
  }
  finally {
    jar.close();
  }
}
 

Example 48

From project hecl, under directory /build-tools/.

Source file: BBJDEVersion.java

  17 
vote

public static void main(String[] args){
  try {
    if (args.length == 0) {
      throw new Exception("Need a jar file to process!");
    }
    JarFile jf=new JarFile(args[0]);
    JarEntry entry=jf.getJarEntry("app.version");
    InputStream is=jf.getInputStream(entry);
    byte[] buf=new byte[4096];
    is.read(buf);
    String sversion=(new String(buf)).trim();
    String[] res=sversion.split("\\.");
    System.out.println(res[0] + "." + res[1]);
    jf.close();
  }
 catch (  Exception e) {
    System.err.println("BBJDEVersion Exception: " + e.toString());
    System.exit(-1);
  }
}
 

Example 49

From project ipdburt, under directory /iddb-cli/src/main/java/iddb/cli/.

Source file: ClassFinder.java

  17 
vote

private void includeJar(File file,Map<URL,String> map){
  if (file.isDirectory())   return;
  URL jarURL=null;
  JarFile jar=null;
  try {
    jarURL=new URL("file:/" + file.getCanonicalPath());
    jarURL=new URL("jar:" + jarURL.toExternalForm() + "!/");
    JarURLConnection conn=(JarURLConnection)jarURL.openConnection();
    jar=conn.getJarFile();
  }
 catch (  Exception e) {
    return;
  }
  if (jar == null || jarURL == null)   return;
  map.put(jarURL,"");
  Enumeration<JarEntry> e=jar.entries();
  while (e.hasMoreElements()) {
    JarEntry entry=e.nextElement();
    if (entry.isDirectory()) {
      if (entry.getName().toUpperCase().equals("META-INF/"))       continue;
      try {
        map.put(new URL(jarURL.toExternalForm() + entry.getName()),packageNameFor(entry));
      }
 catch (      MalformedURLException murl) {
        continue;
      }
    }
  }
}
 

Example 50

From project james-mime4j, under directory /core/src/test/java/org/apache/james/mime4j/parser/.

Source file: MimeStreamParserExampleMessagesTest.java

  17 
vote

private void addTests(String testsFolder) throws URISyntaxException, MalformedURLException, IOException {
  URL resource=MimeStreamParserExampleMessagesTestSuite.class.getResource(testsFolder);
  if (resource != null) {
    if (resource.getProtocol().equalsIgnoreCase("file")) {
      File dir=new File(resource.toURI());
      File[] files=dir.listFiles();
      for (      File f : files) {
        if (f.getName().endsWith(".msg")) {
          addTest(new MimeStreamParserExampleMessagesTest(f.getName(),f.toURI().toURL()));
        }
      }
    }
 else     if (resource.getProtocol().equalsIgnoreCase("jar")) {
      JarURLConnection conn=(JarURLConnection)resource.openConnection();
      JarFile jar=conn.getJarFile();
      for (Enumeration<JarEntry> it=jar.entries(); it.hasMoreElements(); ) {
        JarEntry entry=it.nextElement();
        String s="/" + entry.toString();
        File f=new File(s);
        if (s.startsWith(testsFolder) && s.endsWith(".msg")) {
          addTest(new MimeStreamParserExampleMessagesTest(f.getName(),new URL("jar:file:" + jar.getName() + "!"+ s)));
        }
      }
    }
  }
}
 

Example 51

From project jAPS2, under directory /src/com/agiletec/apsadmin/system/resource/.

Source file: JapsPluginLabelListener.java

  17 
vote

/** 
 * Fetch all the entries in the given (jar) input stream and look for the plugin directory.
 * @param is the input stream to analyse
 */
private Set<String> discoverJarPlugin(InputStream is){
  Set<String> plugins=new HashSet<String>();
  if (null == is)   return plugins;
  JarEntry je=null;
  try {
    JarInputStream jis=new JarInputStream(is);
    do {
      je=jis.getNextJarEntry();
      if (null != je) {
        String URL=je.toString();
        if (URL.contains(PLUGIN_DIRECTORY) && URL.endsWith(PLUGIN_APSADMIN_PATH)) {
          plugins.add(URL);
        }
      }
    }
 while (je != null);
  }
 catch (  Throwable t) {
    ApsSystemUtils.logThrowable(t,this,"discoverJarPlugin");
  }
  return plugins;
}
 

Example 52

From project jarjar-maven-plugin, under directory /src/main/java/com/tonicsystems/jarjar/util/.

Source file: StandaloneJarProcessor.java

  17 
vote

public static void run(File from,File to,JarProcessor proc,boolean ignoreDuplicates) throws IOException {
  byte[] buf=new byte[0x2000];
  JarFile in=new JarFile(from);
  final File tmpTo=File.createTempFile("jarjar",".jar");
  JarOutputStream out=new JarOutputStream(new FileOutputStream(tmpTo));
  Set<String> entries=new HashSet<String>();
  try {
    EntryStruct struct=new EntryStruct();
    Enumeration<JarEntry> e=in.entries();
    while (e.hasMoreElements()) {
      JarEntry entry=e.nextElement();
      struct.name=entry.getName();
      struct.time=entry.getTime();
      ByteArrayOutputStream baos=new ByteArrayOutputStream();
      IoUtil.pipe(in.getInputStream(entry),baos,buf);
      struct.data=baos.toByteArray();
      if (proc.process(struct)) {
        if (entries.add(struct.name)) {
          entry=new JarEntry(struct.name);
          entry.setTime(struct.time);
          entry.setCompressedSize(-1);
          out.putNextEntry(entry);
          out.write(struct.data);
        }
 else         if (struct.name.endsWith("/")) {
        }
 else         if (!ignoreDuplicates) {
          throw new IllegalArgumentException("Duplicate jar entries: " + struct.name);
        }
      }
    }
  }
  finally {
    in.close();
    out.close();
  }
  IoUtil.copyZipWithoutEmptyDirectories(tmpTo,to);
  tmpTo.delete();
}
 

Example 53

From project jbosgi, under directory /testsuite/performance/src/test/java/org/jboss/osgi/test/performance/bundle/arq/.

Source file: TestBundleProviderImpl.java

  17 
vote

static void addToJarRecursively(JarOutputStream jar,File source,String rootDirectory) throws IOException {
  String sourceName=source.getAbsolutePath().replace("\\","/");
  sourceName=sourceName.substring(rootDirectory.length());
  if (sourceName.startsWith("/")) {
    sourceName=sourceName.substring(1);
  }
  if ("META-INF/MANIFEST.MF".equals(sourceName))   return;
  if (source.isDirectory()) {
    for (    File nested : source.listFiles()) {
      addToJarRecursively(jar,nested,rootDirectory);
    }
    return;
  }
  JarEntry entry=new JarEntry(sourceName);
  jar.putNextEntry(entry);
  InputStream is=new FileInputStream(source);
  try {
    BundleInstallAndStartBenchmark.pumpStreams(is,jar);
  }
  finally {
    jar.closeEntry();
    is.close();
  }
}
 

Example 54

From project jboss-modules, under directory /src/main/java/org/jboss/modules/.

Source file: JarFileResourceLoader.java

  17 
vote

public PackageSpec getPackageSpec(final String name) throws IOException {
  final Manifest manifest;
  if (relativePath == null) {
    manifest=jarFile.getManifest();
  }
 else {
    JarEntry jarEntry=getJarEntry("META-INF/MANIFEST.MF");
    if (jarEntry == null) {
      manifest=null;
    }
 else {
      InputStream inputStream=jarFile.getInputStream(jarEntry);
      try {
        manifest=new Manifest(inputStream);
      }
  finally {
        safeClose(inputStream);
      }
    }
  }
  return getPackageSpec(name,manifest,rootUrl);
}
 

Example 55

From project JCL, under directory /JCL/src/xeus/jcl/.

Source file: JarResources.java

  17 
vote

/** 
 * Load the jar contents from InputStream
 * @throws IOException
 */
public void loadJar(InputStream jarStream) throws IOException {
  BufferedInputStream bis=null;
  JarInputStream jis=null;
  try {
    bis=new BufferedInputStream(jarStream);
    jis=new JarInputStream(bis);
    JarEntry jarEntry=null;
    while ((jarEntry=jis.getNextJarEntry()) != null) {
      if (logger.isTraceEnabled())       logger.trace(dump(jarEntry));
      if (jarEntry.isDirectory()) {
        continue;
      }
      if (jarEntryContents.containsKey(jarEntry.getName())) {
        if (!Configuration.supressCollisionException())         throw new JclException("Class/Resource " + jarEntry.getName() + " already loaded");
 else {
          if (logger.isTraceEnabled())           logger.trace("Class/Resource " + jarEntry.getName() + " already loaded; ignoring entry...");
          continue;
        }
      }
      if (logger.isTraceEnabled())       logger.trace("Entry Name: " + jarEntry.getName() + ", "+ "Entry Size: "+ jarEntry.getSize());
      byte[] b=new byte[2048];
      ByteArrayOutputStream out=new ByteArrayOutputStream();
      int len=0;
      while ((len=jis.read(b)) > 0) {
        out.write(b,0,len);
      }
      jarEntryContents.put(jarEntry.getName(),out.toByteArray());
      if (logger.isTraceEnabled())       logger.trace(jarEntry.getName() + ": size=" + out.size()+ " ,csize="+ jarEntry.getCompressedSize());
      out.close();
    }
  }
 catch (  NullPointerException e) {
    if (logger.isTraceEnabled())     logger.trace("Done loading.");
  }
 finally {
    jis.close();
    bis.close();
  }
}
 

Example 56

From project jira-hudson-integration, under directory /hudson-apiv2-plugin/src/main/java/com/marvelution/hudson/plugins/apiv2/wink/.

Source file: HudsonWinkApplication.java

  17 
vote

/** 
 * Get all the classes that are in a  {@link JarFile} and that are in the given package
 * @param jarFile the {@link JarFile} to filter
 * @param resourcePackageName the package to filter with
 * @return {@link Set} of {@link Class} objects
 * @since 4.1.0
 */
private Set<Class<?>> getClassesFromJarFile(JarFile jarFile,String resourcePackageName){
  Set<Class<?>> classes=new HashSet<Class<?>>();
  Enumeration<JarEntry> entries=jarFile.entries();
  while (entries.hasMoreElements()) {
    JarEntry jarEntry=entries.nextElement();
    if (!jarEntry.isDirectory() && jarEntry.getName().endsWith(".class")) {
      String className=jarEntry.getName().substring(0,jarEntry.getName().lastIndexOf('.'));
      className=className.replaceAll("/",".");
      if (className.startsWith(resourcePackageName)) {
        try {
          classes.add(Class.forName(className));
          LOGGER.log(Level.FINE,"Loaded Resource: " + className);
        }
 catch (        ClassNotFoundException e) {
          LOGGER.log(Level.SEVERE,"Failed to load REST Resources: " + className,e);
        }
      }
    }
  }
  return classes;
}
 

Example 57

From project jmd, under directory /src/net/contra/jmd/transformers/allatori/.

Source file: AllatoriTransformer.java

  17 
vote

public AllatoriTransformer(String jarfile,boolean strong) throws Exception {
  logger.log("Allatori Deobfuscator");
  isStrong=strong;
  File jar=new File(jarfile);
  JAR_NAME=jarfile;
  JarFile jf=new JarFile(jar);
  Enumeration<JarEntry> entries=jf.entries();
  while (entries.hasMoreElements()) {
    JarEntry entry=entries.nextElement();
    if (entry == null) {
      break;
    }
    if (entry.getName().endsWith(".class")) {
      ClassGen cg=new ClassGen(new ClassParser(jf.getInputStream(entry),entry.getName()).parse());
      if (isStringClass(cg) || isStringClassB(cg)) {
        ALLATORI_CLASS=cg;
        logger.debug("Allatori Class: " + ALLATORI_CLASS.getClassName());
      }
      cgs.put(cg.getClassName(),cg);
    }
 else {
      NonClassEntries.add(entry,jf.getInputStream(entry));
    }
  }
}
 

Example 58

From project jspwiki, under directory /src/org/apache/wiki/ui/.

Source file: TemplateManager.java

  17 
vote

/** 
 * List all installed i18n language properties
 * @param pageContext
 * @return map of installed Languages (with help of Juan Pablo Santos Rodriguez)
 * @since 2.7.x
 */
public Map listLanguages(PageContext pageContext){
  LinkedHashMap<String,String> resultMap=new LinkedHashMap<String,String>();
  String clientLanguage=((HttpServletRequest)pageContext.getRequest()).getLocale().toString();
  JarInputStream jarStream=null;
  try {
    JarEntry entry;
    InputStream inputStream=pageContext.getServletContext().getResourceAsStream(I18NRESOURCE_PATH);
    jarStream=new JarInputStream(inputStream);
    while ((entry=jarStream.getNextJarEntry()) != null) {
      String name=entry.getName();
      if (!entry.isDirectory() && name.startsWith(I18NRESOURCE_PREFIX) && name.endsWith(I18NRESOURCE_SUFFIX)) {
        name=name.substring(I18NRESOURCE_PREFIX.length(),name.lastIndexOf(I18NRESOURCE_SUFFIX));
        Locale locale=new Locale(name.substring(0,2),((name.indexOf("_") == -1) ? "" : name.substring(3,5)));
        String defaultLanguage="";
        if (clientLanguage.startsWith(name)) {
          defaultLanguage=LocaleSupport.getLocalizedMessage(pageContext,I18NDEFAULT_LOCALE);
        }
        resultMap.put(name,locale.getDisplayName(locale) + " " + defaultLanguage);
      }
    }
  }
 catch (  IOException ioe) {
    if (log.isDebugEnabled())     log.debug("Could not search jar file '" + I18NRESOURCE_PATH + "'for properties files due to an IOException: \n"+ ioe.getMessage());
  }
 finally {
    if (jarStream != null) {
      try {
        jarStream.close();
      }
 catch (      IOException e) {
      }
    }
  }
  return resultMap;
}
 

Example 59

From project jsword, under directory /src/main/java/org/crosswire/common/util/.

Source file: NetUtil.java

  17 
vote

public static long getLastModified(URI uri,String proxyHost,Integer proxyPort){
  try {
    if (uri.getScheme().equals(PROTOCOL_HTTP)) {
      WebResource resource=new WebResource(uri,proxyHost,proxyPort);
      long time=resource.getLastModified();
      resource.shutdown();
      return time;
    }
    URLConnection urlConnection=uri.toURL().openConnection();
    long time=urlConnection.getLastModified();
    if (urlConnection instanceof JarURLConnection) {
      JarURLConnection jarConnection=(JarURLConnection)urlConnection;
      JarEntry jarEntry=jarConnection.getJarEntry();
      time=jarEntry.getTime();
    }
    return time;
  }
 catch (  IOException ex) {
    log.warn("Failed to get modified time",ex);
    return new Date().getTime();
  }
}
 

Example 60

From project knime-scripting, under directory /groovy4knime/src/de/mpicbg/tds/knime/scripting/util/.

Source file: PluginClassLoader.java

  17 
vote

private List<URL> collectDependcyJarURLs(URL pluginJarURL){
  List<URL> dependencyURLs=new ArrayList<URL>();
  try {
    JarFile jar=new JarFile(new File(pluginJarURL.toURI()));
    Enumeration<JarEntry> jarentries=jar.entries();
    while (jarentries.hasMoreElements()) {
      JarEntry jarEntry=jarentries.nextElement();
      String jarEntryName=jarEntry.getName();
      if (jarEntryName.endsWith(".jar")) {
        String pluginInDepUrl="jar:jarjar:" + pluginJarURL.toString() + "^/"+ jarEntryName+ "!/";
        dependencyURLs.add(new URL(pluginInDepUrl));
      }
    }
  }
 catch (  Throwable t) {
    throw new RuntimeException(t);
  }
  return dependencyURLs;
}
 

Example 61

From project l2jserver2, under directory /l2jserver2-gameserver/l2jserver2-gameserver-core/src/main/java/com/l2jserver/service/game/scripting/impl/ecj/.

Source file: EclipseCompilerScriptClassLoader.java

  17 
vote

/** 
 * AddsLibrary jar
 * @param file jar file to add
 * @throws IOException if any I/O error occur
 */
@Override public void addLibrary(File file) throws IOException {
  URL fileURL=file.toURI().toURL();
  addURL(fileURL);
  JarFile jarFile=new JarFile(file);
  Enumeration<JarEntry> entries=jarFile.entries();
  while (entries.hasMoreElements()) {
    JarEntry entry=entries.nextElement();
    String name=entry.getName();
    if (name.endsWith(".class")) {
      name=name.substring(0,name.length() - 6);
      name=name.replace('/','.');
      libraryClasses.add(name);
    }
  }
  jarFile.close();
}
 

Example 62

From project la-clojure, under directory /src/org/jetbrains/plugins/clojure/config/.

Source file: ClojureConfigUtil.java

  17 
vote

/** 
 * Return value of Implementation-Version attribute in jar manifest <p/>
 * @param jarPath  path to jar file
 * @param propPath path to properties file in jar file
 * @return value of Implementation-Version attribute, null if not found
 */
public static String getClojureJarVersion(String jarPath,String propPath){
  try {
    File file=new File(jarPath);
    if (!file.exists()) {
      return null;
    }
    JarFile jarFile=new JarFile(file);
    JarEntry jarEntry=jarFile.getJarEntry(propPath);
    if (jarEntry == null) {
      return null;
    }
    Properties properties=new Properties();
    properties.load(jarFile.getInputStream(jarEntry));
    String version=properties.getProperty(VERSION_PROPERTY_KEY);
    jarFile.close();
    return version;
  }
 catch (  Exception e) {
    return null;
  }
}
 

Example 63

From project m2e-apt, under directory /org.jboss.tools.maven.apt.core/src/org/jboss/tools/maven/apt/internal/utils/.

Source file: AnnotationServiceLocator.java

  17 
vote

/** 
 * Given a JAR file, get the names of any auto-loadable Java 5-style or Java 6-style annotation processor implementations provided by the JAR. The information is based on the Sun <a href="http://java.sun.com/j2se/1.5.0/docs/guide/jar/jar.html#Service%20Provider"> Jar Service Provider spec</a>: the jar file contains a META-INF/services directory; that directory contains text files named according to the desired interfaces; and each file contains the names of the classes implementing the specified service. The files may also contain whitespace (which is to be ignored). The '#' character indicates the beginning of a line comment, also to be ignored. Implied but not stated in the spec is that this routine also ignores anything after the first nonwhitespace token on a line.
 * @param jar the <code>.jar</code> {@link File} to inspect for annotation processor services
 * @return the {@link Set} of auto-loadable Java 5-style or Java 6-style annotation processor {@link ServiceEntry}s provided by the specified JAR, or an empty  {@link Set} if no such {@link ServiceEntry}s are found
 */
public static Set<ServiceEntry> getAptServiceEntries(File jar) throws IOException {
  if (jar == null)   throw new IllegalArgumentException(String.format("Null %s.",File.class));
  if (!jar.exists())   throw new IllegalArgumentException(String.format("Specified file does not exist: %s",jar.getAbsolutePath()));
  if (!jar.canRead())   throw new IllegalArgumentException(String.format("Specified file not readable: %s",jar.getAbsolutePath()));
  Set<ServiceEntry> serviceEntries=new HashSet<ServiceEntry>();
  JarFile jarFile=null;
  try {
    jarFile=new JarFile(jar);
    for (    String serviceName : APT_SERVICES) {
      String providerName="META-INF/services/" + serviceName;
      JarEntry provider=jarFile.getJarEntry(providerName);
      if (provider == null) {
        continue;
      }
      InputStream is=jarFile.getInputStream(provider);
      Set<ServiceEntry> serviceFileEntries=readServiceProvider(serviceName,is);
      serviceEntries.addAll(serviceFileEntries);
    }
    return serviceEntries;
  }
  finally {
    try {
      if (jarFile != null)       jarFile.close();
    }
 catch (    IOException ioe) {
    }
  }
}
 

Example 64

From project m2eclipse-extras, under directory /org.sonatype.m2e.discovery.publisher.maven-plugin/src/main/java/org/sonatype/m2e/discovery/publisher/.

Source file: M2eDiscoveryMetadataGeneratorMojo.java

  17 
vote

private boolean processBundle(File bundleJar,LifecycleMappingMetadataSource mergedLifecycleMappingMetadataSource,Xpp3Dom mergedPluginXmlDom) throws IOException, XmlPullParserException {
  boolean hasLifecycleMappings=false;
  FileInputStream fis=null;
  JarInputStream jis=null;
  try {
    fis=new FileInputStream(bundleJar);
    jis=new JarInputStream(fis);
    JarEntry jarEntry=jis.getNextJarEntry();
    while (jarEntry != null) {
      if (LifecycleMappingFactory.LIFECYCLE_MAPPING_METADATA_SOURCE_NAME.equals(jarEntry.getName())) {
        byte[] jarEntryContent=getByteContent(jis);
        mergeLifecycleMappingMetadata(jarEntryContent,mergedLifecycleMappingMetadataSource);
        hasLifecycleMappings=true;
      }
 else       if ("plugin.xml".equals(jarEntry.getName())) {
        byte[] jarEntryContent=getByteContent(jis);
        mergePluginXml(jarEntryContent,mergedPluginXmlDom);
      }
      jarEntry=jis.getNextJarEntry();
    }
    return hasLifecycleMappings;
  }
  finally {
    IOUtil.close(fis);
    IOUtil.close(jis);
  }
}
 

Example 65

From project masa, under directory /plugins/maven-aapt-plugin/src/main/java/org/jvending/masa/plugin/aapt/.

Source file: LibraryResourceProcessorMojo.java

  17 
vote

private void unjar(JarFile jarFile,File outputDirectory) throws IOException {
  for (Enumeration en=jarFile.entries(); en.hasMoreElements(); ) {
    JarEntry entry=(JarEntry)en.nextElement();
    if (entry.getName().contains("META-INF")) {
      continue;
    }
    File entryFile=new File(outputDirectory,entry.getName());
    if (!entryFile.getParentFile().exists() && !entry.getName().startsWith("META-INF")) {
      entryFile.getParentFile().mkdirs();
    }
    if (entry.isDirectory()) {
      new File(entry.getName()).mkdirs();
    }
 else {
      final InputStream in=jarFile.getInputStream(entry);
      try {
        final OutputStream out=new FileOutputStream(entryFile);
        try {
          IOUtil.copy(in,out);
        }
  finally {
          closeQuietly(out);
        }
      }
  finally {
        closeQuietly(in);
      }
    }
  }
}
 

Example 66

From project maven-android-plugin, under directory /src/main/java/com/jayway/maven/plugins/android/common/.

Source file: JarHelper.java

  17 
vote

/** 
 * Unjars the specified jar file into the the specified directory
 * @param jarFile
 * @param outputDirectory
 * @param unjarListener
 * @throws IOException
 */
public static void unjar(JarFile jarFile,File outputDirectory,UnjarListener unjarListener) throws IOException {
  for (Enumeration en=jarFile.entries(); en.hasMoreElements(); ) {
    JarEntry entry=(JarEntry)en.nextElement();
    File entryFile=new File(outputDirectory,entry.getName());
    if (unjarListener.include(entry)) {
      if (!entryFile.getParentFile().exists()) {
        if (!entryFile.getParentFile().mkdirs()) {
          throw new IOException("Error creating output directory: " + entryFile.getParentFile());
        }
      }
      if (!entry.isDirectory()) {
        final InputStream in=jarFile.getInputStream(entry);
        try {
          final OutputStream out=new FileOutputStream(entryFile);
          try {
            IOUtil.copy(in,out);
          }
  finally {
            IOUtils.closeQuietly(out);
          }
        }
  finally {
          IOUtils.closeQuietly(in);
        }
      }
    }
  }
}
 

Example 67

From project maven-surefire, under directory /maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/.

Source file: ForkConfiguration.java

  17 
vote

/** 
 * Create a jar with just a manifest containing a Main-Class entry for BooterConfiguration and a Class-Path entry for all classpath elements.
 * @param classPath List&lt;String> of all classpath elements.
 * @return The file pointint to the jar
 * @throws java.io.IOException When a file operation fails.
 */
public File createJar(List<String> classPath) throws IOException {
  File file=File.createTempFile("surefirebooter",".jar",tempDirectory);
  if (!debug) {
    file.deleteOnExit();
  }
  FileOutputStream fos=new FileOutputStream(file);
  JarOutputStream jos=new JarOutputStream(fos);
  jos.setLevel(JarOutputStream.STORED);
  JarEntry je=new JarEntry("META-INF/MANIFEST.MF");
  jos.putNextEntry(je);
  Manifest man=new Manifest();
  String cp="";
  for (  String el : classPath) {
    cp+=UrlUtils.getURL(new File(el)).toExternalForm() + " ";
  }
  man.getMainAttributes().putValue("Manifest-Version","1.0");
  man.getMainAttributes().putValue("Class-Path",cp.trim());
  man.getMainAttributes().putValue("Main-Class",ForkedBooter.class.getName());
  man.write(jos);
  jos.close();
  return file;
}
 

Example 68

From project MineQuest-2-Core, under directory /src/main/java/com/theminequest/MineQuest/.

Source file: I18NMessage.java

  17 
vote

private void copyFromJar(File localefile,String localename){
  JarFile file=null;
  try {
    file=new JarFile(MineQuest.getFileReference());
    JarEntry jarentry=file.getJarEntry("i18n/" + localename + ".dict");
    if (jarentry == null) {
      Managers.log(Level.SEVERE,"[i18n] Can't find locale " + localename + "; using en_US");
      jarentry=file.getJarEntry("i18n/en_US.dict");
    }
    IOUtils.copyAndClose(file.getInputStream(jarentry),new FileOutputStream(localefile));
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
 finally {
    if (file != null) {
      try {
        file.close();
      }
 catch (      IOException e) {
        Managers.log(Level.SEVERE,"Resource Leak! i18n");
        e.printStackTrace();
      }
    }
  }
}
 

Example 69

From project ig-undx, under directory /src/main/java/org/illegalaccess/undx/.

Source file: ClassHandler.java

  16 
vote

private void dump(JavaClass jc,JarOutputStream out) throws IOException {
  String classFile=jc.getClassName().replace('.',File.separatorChar).concat(".class");
  OutputStream stream=null;
  if (out == null) {
    File file=new File(outpref,classFile);
    File directory=file.getParentFile();
    if (directory != null) {
      boolean b=directory.mkdirs();
      if (b) {
        jlog.info(directory + " was created");
      }
    }
    stream=new FileOutputStream(file);
  }
 else {
    out.putNextEntry(new JarEntry(classFile));
    stream=out;
  }
  jlog.log(Level.FINE,classFile + " dumped");
  final ByteArrayOutputStream thisout=new ByteArrayOutputStream(2048);
  jc.dump(thisout);
  thisout.writeTo(stream);
}
 

Example 70

From project karaf, under directory /kar/core/src/main/java/org/apache/karaf/kar/internal/.

Source file: KarServiceImpl.java

  16 
vote

private void copyResourceToJar(JarOutputStream jos,URI location,Map<URI,Integer> locationMap){
  if (locationMap.containsKey(location)) {
    return;
  }
  try {
    String noPrefixLocation=location.toString().substring(location.toString().lastIndexOf(":") + 1);
    Parser parser=new Parser(noPrefixLocation);
    InputStream is=location.toURL().openStream();
    String path="repository/" + parser.getArtifactPath();
    jos.putNextEntry(new JarEntry(path));
    Kar.copyStream(is,jos);
    is.close();
    locationMap.put(location,1);
  }
 catch (  Exception e) {
    LOGGER.error("Error adding " + location,e);
  }
}
 

Example 71

From project bndtools, under directory /bndtools.jareditor/src/bndtools/jareditor/internal/.

Source file: JARContentTreePart.java

  15 
vote

public void inputChanged(Viewer viewer,Object oldInput,Object newInput){
  entryMap=new TreeMap<String,ZipTreeNode>();
  URI uri=null;
  if (newInput instanceof IFileEditorInput) {
    uri=((IFileEditorInput)newInput).getFile().getLocationURI();
  }
 else   if (newInput instanceof IURIEditorInput) {
    uri=((IURIEditorInput)newInput).getURI();
  }
  if (uri != null) {
    JarFile jarFile=null;
    try {
      File ioFile=new File(uri);
      jarFile=new JarFile(ioFile);
      Enumeration<JarEntry> entries=jarFile.entries();
      while (entries.hasMoreElements()) {
        ZipTreeNode.addEntry(entryMap,entries.nextElement());
      }
    }
 catch (    IOException e) {
      Status status=new Status(IStatus.ERROR,PluginConstants.PLUGIN_ID,0,"I/O error reading JAR file contents",e);
      ErrorDialog.openError(managedForm.getForm().getShell(),"Error",null,status);
    }
 finally {
      try {
        if (jarFile != null) {
          jarFile.close();
        }
      }
 catch (      IOException e) {
      }
    }
  }
}
 

Example 72

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/hicc/.

Source file: HiccWebServer.java

  15 
vote

public List<String> getResourceListing(String path) throws URISyntaxException, IOException {
  ClassLoader contextClassLoader=Thread.currentThread().getContextClassLoader();
  URL dirURL=contextClassLoader.getResource(path);
  if (dirURL == null) {
    dirURL=contextClassLoader.getResource(path);
  }
  if (dirURL.getProtocol().equals("jar")) {
    String jarPath=dirURL.getPath().substring(5,dirURL.getPath().indexOf("!"));
    JarFile jar=new JarFile(jarPath);
    Enumeration<JarEntry> entries=jar.entries();
    List<String> result=new ArrayList<String>();
    while (entries.hasMoreElements()) {
      String name=entries.nextElement().getName();
      if (name.startsWith(path)) {
        String entry=name.substring(path.length());
        int checkSubdir=entry.indexOf("/");
        if (checkSubdir == 0 && entry.length() > 1) {
          result.add(name);
        }
      }
    }
    return result;
  }
  throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}
 

Example 73

From project CloudReports, under directory /src/main/java/cloudreports/utils/.

Source file: FileIO.java

  15 
vote

/** 
 * List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. Works for regular files and also JARs.
 * @author Greg Briggs
 * @param clazz Any java class that lives in the same place as the resources you want.
 * @param path Should end with "/", but not start with one.
 * @return Just the name of each member item, not the full paths.
 * @throws URISyntaxException 
 * @throws IOException 
 */
public static String[] getResourceListing(Class clazz,String path) throws URISyntaxException, IOException {
  URL dirURL=clazz.getClassLoader().getResource(path);
  if (dirURL != null && dirURL.getProtocol().equals("file")) {
    return new File(dirURL.toURI()).list();
  }
  if (dirURL == null) {
    String me=clazz.getName().replace(".","/") + ".class";
    dirURL=clazz.getClassLoader().getResource(me);
  }
  if (dirURL.getProtocol().equals("jar")) {
    String jarPath=dirURL.getPath().substring(5,dirURL.getPath().indexOf("!"));
    JarFile jar=new JarFile(URLDecoder.decode(jarPath,"UTF-8"));
    Enumeration<JarEntry> entries=jar.entries();
    Set<String> result=new HashSet<String>();
    while (entries.hasMoreElements()) {
      String name=entries.nextElement().getName();
      if (name.startsWith(path)) {
        String entry=name.substring(path.length());
        int checkSubdir=entry.indexOf("/");
        if (checkSubdir >= 0) {
          entry=entry.substring(0,checkSubdir);
        }
        result.add(entry);
      }
    }
    return result.toArray(new String[result.size()]);
  }
  throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}
 

Example 74

From project crash, under directory /shell/core/src/main/java/org/crsh/vfs/spi/jarurl/.

Source file: JarURLDriver.java

  15 
vote

public JarURLDriver(ClassLoader loader,JarURLConnection conn) throws IOException {
  JarFile file=conn.getJarFile();
  Map<String,Handle> handles=new HashMap<String,Handle>();
  handles.put("",root=new Handle(this,""));
  for (  JarEntry entry : Collections.list(file.entries())) {
    Handle handle=get(this,handles,entry.getName());
    handle.entry=entry;
  }
  this.jarURL=conn.getJarFileURL();
  this.loader=loader;
}
 

Example 75

From project flyway, under directory /flyway-core/src/main/java/com/googlecode/flyway/core/util/scanner/.

Source file: JarFileLocationScanner.java

  15 
vote

/** 
 * Finds all the resource names contained in this directory within this jar file.
 * @param jarFileName The name of the jar file.
 * @param directory   The directory to look under.
 * @return The resource names.
 * @throws java.io.IOException when reading the jar file failed.
 */
private Set<String> findResourceNamesFromJarFile(String jarFileName,String directory) throws IOException {
  Set<String> resourceNames=new TreeSet<String>();
  JarFile jarFile=new JarFile(jarFileName);
  Enumeration<JarEntry> entries=jarFile.entries();
  while (entries.hasMoreElements()) {
    String entryName=entries.nextElement().getName();
    if (entryName.startsWith(directory)) {
      resourceNames.add(entryName);
    }
  }
  return resourceNames;
}
 

Example 76

From project guice-automatic-injection, under directory /scanner/asm/src/main/java/de/devsurf/injection/guice/scanner/asm/.

Source file: ASMClasspathScanner.java

  15 
vote

private void _visitJar(JarFile jarFile) throws IOException {
  Enumeration<JarEntry> jarEntries=jarFile.entries();
  for (JarEntry jarEntry=null; jarEntries.hasMoreElements(); ) {
    count++;
    jarEntry=jarEntries.nextElement();
    String name=jarEntry.getName();
    if (!jarEntry.isDirectory() && matches(name)) {
      if (!visited.contains(name)) {
        visitClass(jarFile.getInputStream(jarEntry));
        visited.add(name);
      }
    }
  }
}
 

Example 77

From project HiTune_1, under directory /chukwa-hitune-dist/src/java/org/apache/hadoop/chukwa/hicc/.

Source file: HiccWebServer.java

  15 
vote

public List<String> getResourceListing(String path) throws URISyntaxException, IOException {
  ClassLoader contextClassLoader=Thread.currentThread().getContextClassLoader();
  URL dirURL=contextClassLoader.getResource(path);
  if (dirURL == null) {
    dirURL=contextClassLoader.getResource(path);
  }
  if (dirURL.getProtocol().equals("jar")) {
    String jarPath=dirURL.getPath().substring(5,dirURL.getPath().indexOf("!"));
    JarFile jar=new JarFile(jarPath);
    Enumeration<JarEntry> entries=jar.entries();
    List<String> result=new ArrayList<String>();
    while (entries.hasMoreElements()) {
      String name=entries.nextElement().getName();
      if (name.startsWith(path)) {
        String entry=name.substring(path.length());
        int checkSubdir=entry.indexOf("/");
        if (checkSubdir == 0 && entry.length() > 1) {
          result.add(name);
        }
      }
    }
    return result;
  }
  throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}