Example usage for java.util Enumeration nextElement

List of usage examples for java.util Enumeration nextElement

Introduction

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

Prototype

E nextElement();

Source Link

Document

Returns the next element of this enumeration if this enumeration object has at least one more element to provide.

Usage

From source file:Main.java

public static NetworkInterface getActiveNetworkInterface() {

    Enumeration<NetworkInterface> interfaces = null;
    try {/*from   ww  w.ja  v a2  s .c  o m*/
        interfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        return null;
    }

    while (interfaces.hasMoreElements()) {
        NetworkInterface iface = interfaces.nextElement();
        Enumeration<InetAddress> inetAddresses = iface.getInetAddresses();

        /* Check if we have a non-local address. If so, this is the active
         * interface.
         *
         * This isn't a perfect heuristic: I have devices which this will
         * still detect the wrong interface on, but it will handle the
         * common cases of wifi-only and Ethernet-only.
         */
        while (inetAddresses.hasMoreElements()) {
            InetAddress addr = inetAddresses.nextElement();

            if (!(addr.isLoopbackAddress() || addr.isLinkLocalAddress())) {
                return iface;
            }
        }
    }

    return null;
}

From source file:net.kungfoo.grizzly.proxy.impl.ProxyAdapter.java

private static HttpRequest convert(String method, String uri, Request request) {
    HttpRequest req;/*from w w  w  .  j av  a 2  s .c  om*/
    final int len = request.getContentLength();
    if (len > 0) {
        req = new BasicHttpEntityEnclosingRequest(method, uri);
        final BasicHttpEntity httpEntity = new BasicHttpEntity();
        httpEntity.setContentLength(len);
        //      httpEntity.setContent(((InternalInputBuffer) request.getInputBuffer()).getInputStream());
        ((BasicHttpEntityEnclosingRequest) req).setEntity(httpEntity);
    } else {
        req = new BasicHttpRequest(method, uri);
    }
    final MimeHeaders mimeHeaders = request.getMimeHeaders();
    final Enumeration names = mimeHeaders.names();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        req.addHeader(name, mimeHeaders.getHeader(name));
    }
    return req;
}

From source file:com.groupon.odo.proxylib.Utils.java

/**
 * This function returns the first external IP address encountered
 *
 * @return IP address or null//w w w  .  ja va 2  s  .  c  o  m
 * @throws Exception
 */
public static String getPublicIPAddress() throws Exception {
    final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";

    String ipAddr = null;
    Enumeration e = NetworkInterface.getNetworkInterfaces();
    while (e.hasMoreElements()) {
        NetworkInterface n = (NetworkInterface) e.nextElement();
        Enumeration ee = n.getInetAddresses();
        while (ee.hasMoreElements()) {
            InetAddress i = (InetAddress) ee.nextElement();

            // Pick the first non loop back address
            if ((!i.isLoopbackAddress() && i.isSiteLocalAddress()) || i.getHostAddress().matches(IPV4_REGEX)) {
                ipAddr = i.getHostAddress();
                break;
            }
        }
        if (ipAddr != null) {
            break;
        }
    }

    return ipAddr;
}

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 {/*from   w  w  w.  j a va  2 s  .  co  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.glaf.core.config.ViewProperties.java

public static void reload() {
    if (!loading.get()) {
        InputStream inputStream = null;
        try {/*from   w  w w  .  j  av  a 2s  .c  o m*/
            loading.set(true);
            String config = SystemProperties.getConfigRootPath() + "/conf/props/views";
            File directory = new File(config);
            if (directory.exists() && directory.isDirectory()) {
                String[] filelist = directory.list();
                if (filelist != null) {
                    for (int i = 0, len = filelist.length; i < len; i++) {
                        String filename = config + "/" + filelist[i];
                        File file = new File(filename);
                        if (file.isFile() && file.getName().endsWith(".properties")) {
                            inputStream = new FileInputStream(file);
                            Properties p = PropertiesUtils.loadProperties(inputStream);
                            if (p != null) {
                                Enumeration<?> e = p.keys();
                                while (e.hasMoreElements()) {
                                    String key = (String) e.nextElement();
                                    String value = p.getProperty(key);
                                    properties.setProperty(key, value);
                                    properties.setProperty(key.toLowerCase(), value);
                                    properties.setProperty(key.toUpperCase(), value);
                                }
                            }
                            IOUtils.closeStream(inputStream);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            loading.set(false);
            IOUtils.closeStream(inputStream);
        }
    }
}

From source file:ie.deri.unlp.javaservices.topicextraction.topicextractor.gate.TopicExtractorGate.java

/**
 * //from   w  w  w  .  ja v a 2 s .  c  o m
 * Extract a directory in a JAR on the classpath to an output folder.
 * 
 * Note: User's responsibility to ensure that the files are actually in a JAR.
 * 
 * @param classInJar A class in the JAR file which is on the classpath
 * @param resourceDirectory Path to resource directory in JAR
 * @param outputDirectory Directory to write to  
 * @return String containing the path to the outputDirectory
 * @throws IOException
 */
private static String extractDirectoryFromClasspathJAR(Class<?> classInJar, String resourceDirectory,
        String outputDirectory) throws IOException {

    resourceDirectory = StringUtils.strip(resourceDirectory, "\\/") + File.separator;

    URL jar = classInJar.getProtectionDomain().getCodeSource().getLocation();
    JarFile jarFile = new JarFile(new File(jar.getFile()));

    byte[] buf = new byte[1024];
    Enumeration<JarEntry> jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = jarEntries.nextElement();
        if (jarEntry.isDirectory() || !jarEntry.getName().startsWith(resourceDirectory)) {
            continue;
        }

        String outputFileName = FilenameUtils.concat(outputDirectory, jarEntry.getName());
        //Create directories if they don't exist
        new File(FilenameUtils.getFullPath(outputFileName)).mkdirs();

        //Write file
        FileOutputStream fileOutputStream = new FileOutputStream(outputFileName);
        int n;
        InputStream is = jarFile.getInputStream(jarEntry);
        while ((n = is.read(buf, 0, 1024)) > -1) {
            fileOutputStream.write(buf, 0, n);
        }
        is.close();
        fileOutputStream.close();
    }
    jarFile.close();

    String fullPath = FilenameUtils.concat(outputDirectory, resourceDirectory);
    return fullPath;
}

From source file:io.card.development.recording.Recording.java

public static Recording[] parseRecordings(InputStream recordingStream) throws IOException, JSONException {
    Hashtable<String, byte[]> recordingFiles = unzipFiles(recordingStream);
    Hashtable<String, byte[]> manifestFiles = findManifestFiles(recordingFiles);

    int recordingIndex = 0;
    Recording[] recordings = new Recording[manifestFiles.size()];
    Enumeration<String> manifestFilenames = manifestFiles.keys();
    while (manifestFilenames.hasMoreElements()) {
        String manifestFilename = manifestFilenames.nextElement();
        String manifestDirName = manifestFilename.substring(0, manifestFilename.lastIndexOf("/"));
        byte[] manifestData = manifestFiles.get(manifestFilename);

        ManifestEntry[] manifestEntries = buildManifest(manifestDirName, manifestData, recordingFiles);
        recordings[recordingIndex] = new Recording(manifestEntries);
        recordingIndex++;//from ww  w  .j  a  v  a  2 s. c o  m
    }

    return recordings;
}

From source file:com.bluexml.xforms.messages.MsgPool.java

/**
 * Tests whether a key exists in the properties file.
 * //w  ww  . j av a2  s  .c o m
 * @param theKey
 *            the reference key text being tested
 * @return
 */
private static boolean hasProperty(String theKey) {
    getInstance();
    Enumeration<?> properties = MsgPool.getPool().propertyNames();
    while (properties.hasMoreElements()) {
        String aKey = (String) properties.nextElement();
        if (StringUtils.equals(theKey, aKey)) {
            return true;
        }
    }
    return false;
}

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

/**
 * /* www .j  av 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: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. )
 * //  w ww. j a  v a2  s  .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();
    }

}