Example usage for java.util Enumeration hasMoreElements

List of usage examples for java.util Enumeration hasMoreElements

Introduction

In this page you can find the example usage for java.util Enumeration hasMoreElements.

Prototype

boolean hasMoreElements();

Source Link

Document

Tests if this enumeration contains more elements.

Usage

From source file:Main.java

public static List<String> getDexEntries() {
    try {//from ww w  .j a va  2s. c o  m
        Object app = Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
        Object codePath = Class.forName("android.app.Application").getMethod("getPackageCodePath").invoke(app);
        Class<?> dexFileClass = Class.forName("dalvik.system.DexFile");
        Object dexFile = dexFileClass.getConstructor(String.class).newInstance(codePath);
        Enumeration<String> entries = (Enumeration<String>) dexFileClass.getMethod("entries").invoke(dexFile);
        List<String> dexEntries = new LinkedList<String>();
        while (entries.hasMoreElements()) {
            String entry = entries.nextElement();
            entry = entry.replace('.', '/') + ".class";
            dexEntries.add(entry);
        }
        dexFileClass.getMethod("close").invoke(dexFile);
        return dexEntries;
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.virgo.snaps.SnapsTagTests.java

private static final String[] toArray(Enumeration<?> enumeration) {
    List<String> list = new ArrayList<String>();
    while (enumeration.hasMoreElements()) {
        String element = enumeration.nextElement().toString();
        list.add(element);// www.ja  va  2  s  . c o m
    }
    return list.toArray(new String[list.size()]);
}

From source file:io.fabric8.vertx.maven.plugin.utils.WebJars.java

public static void extract(final AbstractVertxMojo mojo, File in, File out, boolean stripVersion)
        throws IOException {
    ZipFile file = new ZipFile(in);
    try {/* w ww. ja  v  a2s. c o  m*/
        Enumeration<? extends ZipEntry> entries = file.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getName().startsWith(WEBJAR_LOCATION) && !entry.isDirectory()) {
                // Compute destination.
                File output = new File(out, entry.getName().substring(WEBJAR_LOCATION.length()));
                if (stripVersion) {
                    String path = entry.getName().substring(WEBJAR_LOCATION.length());
                    Matcher matcher = WEBJAR_INTERNAL_PATH_REGEX.matcher(path);
                    if (matcher.matches()) {
                        output = new File(out, matcher.group(1) + "/" + matcher.group(3));
                    } else {
                        mojo.getLog().warn(path
                                + " does not match the regex - did not strip the version for this" + " file");
                    }
                }
                InputStream stream = null;
                try {
                    stream = file.getInputStream(entry);
                    output.getParentFile().mkdirs();
                    org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, output);
                } catch (IOException e) {
                    mojo.getLog().error("Cannot unpack " + entry.getName() + " from " + file.getName(), e);
                    throw e;
                } finally {
                    IOUtils.closeQuietly(stream);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(file);
    }
}

From source file:Main.java

public static void unzip(String strZipFile) {

    try {// w  w w.  j  ava2  s.  c o m
        /*
         * STEP 1 : Create directory with the name of the zip file
         * 
         * For e.g. if we are going to extract c:/demo.zip create c:/demo directory where we can extract all the zip entries
         */
        File fSourceZip = new File(strZipFile);
        String zipPath = strZipFile.substring(0, strZipFile.length() - 4);
        File temp = new File(zipPath);
        temp.mkdir();
        System.out.println(zipPath + " created");

        /*
         * STEP 2 : Extract entries while creating required sub-directories
         */
        ZipFile zipFile = new ZipFile(fSourceZip);
        Enumeration<? extends ZipEntry> e = zipFile.entries();

        while (e.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            File destinationFilePath = new File(zipPath, entry.getName());

            // create directories if required.
            destinationFilePath.getParentFile().mkdirs();

            // if the entry is directory, leave it. Otherwise extract it.
            if (entry.isDirectory()) {
                continue;
            } else {
                // System.out.println("Extracting " + destinationFilePath);

                /*
                 * Get the InputStream for current entry of the zip file using
                 * 
                 * InputStream getInputStream(Entry entry) method.
                 */
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));

                int b;
                byte buffer[] = new byte[1024];

                /*
                 * read the current entry from the zip file, extract it and write the extracted file.
                 */
                FileOutputStream fos = new FileOutputStream(destinationFilePath);
                BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);

                while ((b = bis.read(buffer, 0, 1024)) != -1) {
                    bos.write(buffer, 0, b);
                }

                // flush the output stream and close it.
                bos.flush();
                bos.close();

                // close the input stream.
                bis.close();
            }

        }
        zipFile.close();
    } catch (IOException ioe) {
        System.out.println("IOError :" + ioe);
    }

}

From source file:io.fabric8.vertx.maven.plugin.utils.WebJars.java

/**
 * Checks whether the given file is a WebJar or not (http://www.webjars.org/documentation).
 * The check is based on the presence of {@literal META-INF/resources/webjars/} directory in the jar file.
 *
 * @param file the file.// w  w  w  .  j a v  a  2  s. c o m
 * @return {@literal true} if it's a bundle, {@literal false} otherwise.
 */
public static boolean isWebJar(Log log, File file) {
    if (file == null) {
        return false;
    }
    Set<String> found = new LinkedHashSet<>();
    if (file.isFile() && file.getName().endsWith(".jar")) {
        JarFile jar = null;
        try {
            jar = new JarFile(file);

            // Fast return if the base structure is not there
            if (jar.getEntry(WEBJAR_LOCATION) == null) {
                return false;
            }

            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                Matcher matcher = WEBJAR_REGEX.matcher(entry.getName());
                if (matcher.matches()) {
                    found.add(matcher.group(1) + "-" + matcher.group(2));
                }
            }
        } catch (IOException e) {
            log.error("Cannot check if the file " + file.getName() + " is a webjar, cannot open it", e);
            return false;
        } finally {
            final JarFile finalJar = jar;
            IOUtils.closeQuietly(() -> {
                if (finalJar != null) {
                    finalJar.close();
                }
            });
        }

        for (String lib : found) {
            log.info("Web Library found in " + file.getName() + " : " + lib);
        }

        return !found.isEmpty();
    }

    return false;
}

From source file:io.galeb.router.sync.HttpClient.java

private static String localIpsEncoded() {
    final List<String> ipList = new ArrayList<>();
    try {//from w  w  w.j ava2  s.co m
        Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces();
        while (ifs.hasMoreElements()) {
            NetworkInterface localInterface = ifs.nextElement();
            if (!localInterface.isLoopback() && localInterface.isUp()) {
                Enumeration<InetAddress> ips = localInterface.getInetAddresses();
                while (ips.hasMoreElements()) {
                    InetAddress ipaddress = ips.nextElement();
                    if (ipaddress instanceof Inet4Address) {
                        ipList.add(ipaddress.getHostAddress());
                        break;
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
    String ip = String.join("-", ipList);
    if (ip == null || "".equals(ip)) {
        ip = "undef-" + System.currentTimeMillis();
    }
    return ip.replaceAll("[:%]", "");
}

From source file:edu.stanford.muse.util.Log4JUtils.java

/** adds a new file appender to the root logger. expects root logger to have at least a console appender from which it borrows the layout */
private static void addLogFileAppender(String filename) {
    try {//from   w  ww  .  j a  v  a 2s . c  o  m
        Logger rootLogger = LogManager.getLoggerRepository().getRootLogger();
        Enumeration allAppenders = rootLogger.getAllAppenders();
        while (allAppenders.hasMoreElements()) {
            Object next = allAppenders.nextElement();
            if (next instanceof ConsoleAppender) {
                Layout layout = ((ConsoleAppender) next).getLayout();
                RollingFileAppender rfa = new RollingFileAppender(layout, filename);
                rfa.setMaxFileSize("10MB");
                rfa.setMaxBackupIndex(10); // do we
                rfa.setEncoding("UTF-8");
                rootLogger.addAppender(rfa);
            }
        }
    } catch (Exception e) {
        log.error("Failed creating log appender in " + filename);
        System.err.println("Failed creating log appender in " + filename);
    }
}

From source file:com.stevpet.sonar.plugins.dotnet.mscover.codecoverage.command.ZipUtils.java

/**
 * Extracts the specified folder from the specified archive, into the supplied output directory.
 * //from   w ww. jav a2 s.co  m
 * @param archivePath
 *          the archive Path
 * @param folderToExtract
 *          the folder to extract
 * @param outputDirectory
 *          the output directory
 * @return the extracted folder path
 * @throws IOException
 *           if a problem occurs while extracting
 */
public static File extractArchiveFolderIntoDirectory(String archivePath, String folderToExtract,
        String outputDirectory) throws IOException {
    File destinationFolder = new File(outputDirectory);
    destinationFolder.mkdirs();

    ZipFile zip = null;
    try {
        zip = new ZipFile(new File(archivePath));
        Enumeration<?> zipFileEntries = zip.entries();
        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            if (currentEntry.startsWith(folderToExtract)) {
                File destFile = new File(destinationFolder, currentEntry);
                destFile.getParentFile().mkdirs();
                if (!entry.isDirectory()) {
                    BufferedInputStream is = null;
                    BufferedOutputStream dest = null;
                    try {
                        is = new BufferedInputStream(zip.getInputStream(entry));
                        int currentByte;
                        // establish buffer for writing file
                        byte data[] = new byte[BUFFER_SIZE];

                        // write the current file to disk
                        FileOutputStream fos = new FileOutputStream(destFile);
                        dest = new BufferedOutputStream(fos, BUFFER_SIZE);

                        // read and write until last byte is encountered
                        while ((currentByte = is.read(data, 0, BUFFER_SIZE)) != -1) {
                            dest.write(data, 0, currentByte);
                        }
                    } finally {
                        if (dest != null) {
                            dest.flush();
                        }
                        IOUtils.closeQuietly(dest);
                        IOUtils.closeQuietly(is);
                    }
                }
            }
        }
    } finally {
        if (zip != null) {
            zip.close();
        }
    }

    return new File(destinationFolder, folderToExtract);
}

From source file:kilim.tools.FlowAnalyzer.java

public static void analyzeJar(String jarFile, Detector detector) {
    try {// w  ww.  j a  v a2  s. c om
        Enumeration<JarEntry> e = new JarFile(jarFile).entries();
        while (e.hasMoreElements()) {
            ZipEntry en = (ZipEntry) e.nextElement();
            String n = en.getName();
            if (!n.endsWith(".class"))
                continue;
            n = n.substring(0, n.length() - 6).replace('/', '.');
            analyzeClass(n, detector);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static String findAppropriateIp() {
    String result = "unknown";

    Enumeration<NetworkInterface> e;
    try {//from  w w w  .j  a  v a2 s  . com
        e = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e1) {
        return result;
    }
    while (e.hasMoreElements()) {
        NetworkInterface n = (NetworkInterface) e.nextElement();
        Enumeration<InetAddress> ee = n.getInetAddresses();
        while (ee.hasMoreElements()) {
            InetAddress inetAddr = ee.nextElement();
            String ipAddr = inetAddr.getHostAddress();

            Matcher m = ipAddrPattern.matcher(ipAddr);
            if (m.matches()) {
                if (!m.group(1).equals("127")) {
                    result = ipAddr;
                }
            }
        }
    }

    return result;
}