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:org.sakuli.actions.environment.CipherUtil.java

/**
 * Determines a valid network interfaces.
 *
 * @return ethernet interface name//from   www . j  a  v  a  2  s  .co m
 * @throws Exception
 */
static String autodetectValidInterfaceName() throws Exception {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface anInterface = interfaces.nextElement();
        if (anInterface.getHardwareAddress() != null && anInterface.getHardwareAddress().length == 6) {
            return anInterface.getName();
        }
    }
    throw new Exception("No network interface with a MAC address is present, please check your os settings!");
}

From source file:Main.java

public static String GetWantedIPAdress_JAVA() {
    String wantedIP = "";
    Enumeration<NetworkInterface> e = null;

    try {//  w  ww  .j  a v a  2s .co m
        e = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e1) {
        e1.printStackTrace();
    }

    if (e != null) {
        while (e.hasMoreElements()) {
            NetworkInterface n = (NetworkInterface) e.nextElement();
            Enumeration<InetAddress> ee = n.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress i = (InetAddress) ee.nextElement();
                if (i.getHostAddress().toString().contains("192.168.")
                        || i.getHostAddress().toString().startsWith("10.")) {
                    wantedIP = i.getHostAddress();
                    break;
                }
            }
        }
    }

    return wantedIP;
}

From source file:net.siegmar.japtproxy.JaptProxyServlet.java

/**
 * Logs the header of the incoming request.
 *
 * @param req the HttpServletRequest object
 *///from   w  w  w .j  a v a2s.  c  o m
private static void logHeader(final HttpServletRequest req) {
    final Enumeration<String> headers = req.getHeaderNames();
    final StringBuilder sb = new StringBuilder();
    while (headers.hasMoreElements()) {
        final String headerName = headers.nextElement();
        sb.append(headerName);
        sb.append('=');
        sb.append(req.getHeader(headerName));
        if (headers.hasMoreElements()) {
            sb.append(',');
        }
    }
    LOG.debug("Request header: {}", sb);
}

From source file:org.shept.util.JarUtils.java

/**
 * Copy resources from a classPath, typically within a jar file 
 * to a specified destination, typically a resource directory in
 * the projects webApp directory (images, sounds, e.t.c. )
 * /*from  w w  w.  j a  v a  2s .c o  m*/
 * Copies resources only if the destination file does not exist and
 * the specified resource is available.
 * 
 * The ClassPathResource will be scanned for all resources in the path specified by the resource.
 * For example  a path like:
 *    new ClassPathResource("resource/images/pager/", SheptBaseController.class);
 * takes all the resources in the path 'resource/images/pager' (but not in sub-path)
 * from the specified clazz 'SheptBaseController'
 * 
 * @param cpr ClassPathResource specifying the source location on the classPath (maybe within a jar)
 * @param webAppDestPath Full path String to the fileSystem destination directory   
 * @throws IOException when copying on copy error
 * @throws URISyntaxException 
 */
public static void copyResources(ClassPathResource cpr, String webAppDestPath)
        throws IOException, URISyntaxException {
    String dstPath = webAppDestPath; //  + "/" + jarPathInternal(cpr.getURL());
    File dir = new File(dstPath);
    dir.mkdirs();

    URL url = cpr.getURL();
    // jarUrl is the URL of the containing lib, e.g. shept.org in this case
    URL jarUrl = ResourceUtils.extractJarFileURL(url);
    String urlFile = url.getFile();
    String resPath = "";
    int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
    if (separatorIndex != -1) {
        // just copy the the location path inside the jar without leading separators !/
        resPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
    } else {
        return; // no resource within jar to copy
    }

    File f = new File(ResourceUtils.toURI(jarUrl));
    JarFile jf = new JarFile(f);

    Enumeration<JarEntry> entries = jf.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String path = entry.getName();
        if (path.startsWith(resPath) && entry.getSize() > 0) {
            String fileName = path.substring(path.lastIndexOf("/"));
            File dstFile = new File(dstPath, fileName); //  (StringUtils.applyRelativePath(dstPath, fileName));
            Resource fileRes = cpr.createRelative(fileName);
            if (!dstFile.exists() && fileRes.exists()) {
                FileOutputStream fos = new FileOutputStream(dstFile);
                FileCopyUtils.copy(fileRes.getInputStream(), fos);
                logger.info("Successfully copied file " + fileName + " from " + cpr.getPath() + " to "
                        + dstFile.getPath());
            }
        }
    }

    if (jf != null) {
        jf.close();
    }

}

From source file:com.limegroup.gnutella.gui.LanguageUtils.java

/**
 * Returns the languages as found from the classpath in messages.jar
 *//*  w w w.  ja v a 2 s. c  om*/
static void addLocalesFromJar(List<Locale> locales, File jar) {
    ZipFile zip = null;
    try {
        zip = new ZipFile(jar);
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            String name = entries.nextElement().getName();
            if (!name.startsWith(BUNDLE_PREFIX) || !name.endsWith(BUNDLE_POSTFIX) || name.indexOf("$") != -1) {
                continue;
            }

            String iso = name.substring(BUNDLE_PREFIX.length(), name.length() - BUNDLE_POSTFIX.length());
            List<String> tokens = new ArrayList<String>(Arrays.asList(iso.split("_", 3)));
            if (tokens.size() < 1) {
                continue;
            }
            while (tokens.size() < 3) {
                tokens.add("");
            }

            Locale locale = new Locale(tokens.get(0), tokens.get(1), tokens.get(2));
            locales.add(locale);
        }
    } catch (IOException e) {
        LOG.warn("Could not determine locales", e);
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:dk.itst.oiosaml.configuration.SAMLConfiguration.java

public static Configuration getCommonConfiguration() throws IOException {
    CompositeConfiguration conf = new CompositeConfiguration();
    Enumeration<URL> resources = SAMLConfiguration.class.getClassLoader()
            .getResources("oiosaml-common.properties");
    while (resources.hasMoreElements()) {
        URL u = resources.nextElement();
        log.debug("Loading config from " + u);
        try {/*  w w w . java  2 s.c o m*/
            conf.addConfiguration(new PropertiesConfiguration(u));
        } catch (ConfigurationException e) {
            log.error("Cannot load the configuration file", e);
            throw new WrappedException(Layer.DATAACCESS, e);
        }
    }

    return conf;
}

From source file:com.pieframework.runtime.utils.Zipper.java

public static void unzip(String zipFile, String toDir) throws ZipException, IOException {

    int BUFFER = 2048;
    File file = new File(zipFile);

    ZipFile zip = new ZipFile(file);
    String newPath = toDir;//  w ww  .  j av  a2s  . c  o  m

    File toDirectory = new File(newPath);
    if (!toDirectory.exists()) {
        toDirectory.mkdir();
    }
    Enumeration zipFileEntries = zip.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

        String currentEntry = entry.getName();
        File destFile = new File(newPath, FilenameUtils.separatorsToSystem(currentEntry));
        //System.out.println(currentEntry);
        File destinationParent = destFile.getParentFile();

        // create the parent directory structure if needed
        destinationParent.mkdirs();
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
            int currentByte;
            // establish buffer for writing file
            byte data[] = new byte[BUFFER];

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

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

}

From source file:com.us.util.FileHelper.java

/**
 * //from   ww w  . j  a  v  a  2 s .c  om
 * 
 * @param packName ??
 * @param fileName ??
 * @return
 */
public static InputStream getFileInPackage(String packName, String fileName) {
    try {
        String packdir = packName.replace('.', '/');
        Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(packdir);
        while (dirs.hasMoreElements()) {
            URL url = dirs.nextElement();
            if (url.getProtocol().equals("file")) {
                String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                return new FileInputStream(filePath + "/" + fileName);
            } else if (url.getProtocol().equals("jar")) {
                return FileHelper.class.getClassLoader()
                        .getResourceAsStream(packdir.concat("/").concat(fileName));
            }
        }
    } catch (IOException e) {
        throw UsMsgException.newInstance(String.format(":%s.%s", packName, fileName), e);
    }
    return null;
}

From source file:info.dolezel.fatrat.plugins.helpers.NativeHelpers.java

private static Set<Class> findClasses(File directory, String packageName, Class annotation)
        throws ClassNotFoundException, IOException {
    Set<Class> classes = new HashSet<Class>();
    if (!directory.exists()) {

        String fullPath = directory.toString();
        String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
        JarFile jarFile = new JarFile(jarPath);
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entryName = entry.getName();
            if (entryName.endsWith(".class") && !entryName.contains("$")) {
                String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
                Class cls = loader.loadClass(className);

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);//from w  ww  .j  a va  2 s .c o m
            }
        }
    } else {
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName(), annotation));
            } else if (file.getName().endsWith(".class")) {
                Class cls = loader.loadClass(
                        packageName + '.' + file.getName().substring(0, file.getName().length() - 6));

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);
            }
        }
    }
    return classes;
}

From source file:net.ontopia.topicmaps.webed.impl.utils.ReqParamUtils.java

/**
 * INTERNAL: Builds the Parameters object from an HttpServletRequest
 * object./*from   w  w  w  .jav  a2 s . com*/
 * @since 2.0
 */
public static Parameters decodeParameters(HttpServletRequest request, String charenc)
        throws ServletException, IOException {

    String ctype = request.getHeader("content-type");
    log.debug("Content-type: " + ctype);
    Parameters params = new Parameters();

    if (ctype != null && ctype.startsWith("multipart/form-data")) {
        // special file upload request, so use FileUpload to decode
        log.debug("Decoding with FileUpload; charenc=" + charenc);
        try {
            FileUpload upload = new FileUpload(new DefaultFileItemFactory());
            Iterator iterator = upload.parseRequest(request).iterator();
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                log.debug("Reading: " + item);
                if (item.isFormField()) {
                    if (charenc != null)
                        params.addParameter(item.getFieldName(), item.getString(charenc));
                    else
                        params.addParameter(item.getFieldName(), item.getString());
                } else
                    params.addParameter(item.getFieldName(), new FileParameter(item));
            }
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }

    } else {
        // ordinary web request, so retrieve info and stuff into Parameters object
        log.debug("Normal parameter decode, charenc=" + charenc);
        if (charenc != null)
            request.setCharacterEncoding(charenc);
        Enumeration enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String param = (String) enumeration.nextElement();
            params.addParameter(param, request.getParameterValues(param));
        }
    }

    return params;
}