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:com.glaf.core.config.MessageProperties.java

public static void reload() {
    if (!loading.get()) {
        InputStream inputStream = null;
        try {//from   w ww  .  java  2s .  c  o m
            loading.set(true);
            String config = SystemProperties.getConfigRootPath() + "/conf/props/messages";
            File directory = new File(config);
            if (directory.exists() && directory.isDirectory()) {
                File[] filelist = directory.listFiles();
                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);
                        }
                    }
                }
            }

            ISystemPropertyService systemPropertyService = ContextFactory.getBean("systemPropertyService");
            List<SystemProperty> list = systemPropertyService.getAllSystemProperties();
            if (list != null && !list.isEmpty()) {
                for (SystemProperty p : list) {
                    properties.put(p.getName(), p);
                }
            }

        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            loading.set(false);
            IOUtils.closeStream(inputStream);
        }
    }
}

From source file:com.google.code.pentahoflashcharts.charts.PentahoOFC4JChartHelper.java

@SuppressWarnings("unchecked")
private static Map createChartFactoryMap() {
    Properties chartFactories = new Properties();
    // First, get known chart factories...
    try {/*from w  w w  . j a  v a  2 s . c  o  m*/
        ResourceBundle pluginBundle = ResourceBundle.getBundle(PLUGIN_BUNDLE_NAME);
        if (pluginBundle != null) { // Copy the bundle here...
            Enumeration keyEnum = pluginBundle.getKeys();
            String bundleKey = null;
            while (keyEnum.hasMoreElements()) {
                bundleKey = (String) keyEnum.nextElement();
                chartFactories.put(bundleKey, pluginBundle.getString(bundleKey));
            }
        }
    } catch (Exception ex) {
        logger.warn(Messages.getString("PentahoOFC4JChartHelper.WARN_NO_CHART_FACTORY_PROPERTIES_BUNDLE")); //$NON-NLS-1$
    }
    // Get overrides...
    //
    // Note - If the override wants to remove an existing "known" plugin, 
    // simply adding an empty value will cause the "known" plugin to be removed.
    //
    if (PentahoSystem.getObjectFactory() == null
            || !PentahoSystem.getObjectFactory().objectDefined(ISolutionRepository.class.getSimpleName())) {
        // this is ok
        return chartFactories;
    }
    ISolutionRepository solutionRepository = PentahoSystem.get(ISolutionRepository.class,
            new StandaloneSession("system")); //$NON-NLS-1$
    try {
        if (solutionRepository.resourceExists(SOLUTION_PROPS)) {
            InputStream is = solutionRepository.getResourceInputStream(SOLUTION_PROPS, false);
            Properties overrideChartFactories = new Properties();
            overrideChartFactories.load(is);
            chartFactories.putAll(overrideChartFactories); // load over the top of the known properties
        }
    } catch (FileNotFoundException ignored) {
        logger.warn(Messages.getString("PentahoOFC4JChartHelper.WARN_NO_CHART_FACTORY_PROPERTIES")); //$NON-NLS-1$
    } catch (IOException ignored) {
        logger.warn(Messages.getString("PentahoOFC4JChartHelper.WARN_BAD_CHART_FACTORY_PROPERTIES"), ignored); //$NON-NLS-1$
    }

    return chartFactories;
}

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

/** taken from: http://stackoverflow.com/questions/3060240/how-do-you-flush-a-buffered-log4j-fileappender */
public static void flushAllLogs() {
    try {/*from   www. ja va  2 s  . c  om*/
        Set<FileAppender> flushedFileAppenders = new LinkedHashSet<FileAppender>();
        Enumeration currentLoggers = LogManager.getLoggerRepository().getCurrentLoggers();
        while (currentLoggers.hasMoreElements()) {
            Object nextLogger = currentLoggers.nextElement();
            if (nextLogger instanceof Logger) {
                Logger currentLogger = (Logger) nextLogger;
                Enumeration allAppenders = currentLogger.getAllAppenders();
                while (allAppenders.hasMoreElements()) {
                    Object nextElement = allAppenders.nextElement();
                    if (nextElement instanceof FileAppender) {
                        FileAppender fileAppender = (FileAppender) nextElement;
                        if (!flushedFileAppenders.contains(fileAppender) && !fileAppender.getImmediateFlush()) {
                            flushedFileAppenders.add(fileAppender);
                            //log.info("Appender "+fileAppender.getName()+" is not doing immediateFlush ");
                            fileAppender.setImmediateFlush(true);
                            currentLogger
                                    .info("Flushing appender: " + fileAppender.getName() + "\n" + fileAppender);
                            fileAppender.setImmediateFlush(false);
                        } else {
                            //log.info("fileAppender"+fileAppender.getName()+" is doing immediateFlush");
                        }
                    }
                }
            }
        }
    } catch (RuntimeException e) {
        log.error("Failed flushing logs", e);
    }
}

From source file:io.apiman.test.common.mock.EchoResponse.java

/**
 * Create an echo response from the inbound information in the http server
 * request./*from ww  w .  ja  v  a  2  s . c o  m*/
 * @param request
 * @param withBody 
 * @return a new echo response
 */
public static EchoResponse from(HttpServletRequest request, boolean withBody) {
    EchoResponse response = new EchoResponse();
    response.setMethod(request.getMethod());
    response.setResource(request.getRequestURI());
    response.setUri(request.getRequestURI());
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        String value = request.getHeader(name);
        response.getHeaders().put(name, value);
    }
    if (withBody) {
        long totalBytes = 0;
        InputStream is = null;
        try {
            is = request.getInputStream();
            MessageDigest sha1 = MessageDigest.getInstance("SHA1"); //$NON-NLS-1$
            byte[] data = new byte[1024];
            int read = 0;
            while ((read = is.read(data)) != -1) {
                sha1.update(data, 0, read);
                totalBytes += read;
            }
            ;

            byte[] hashBytes = sha1.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < hashBytes.length; i++) {
                sb.append(Integer.toString((hashBytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            String fileHash = sb.toString();

            response.setBodyLength(totalBytes);
            response.setBodySha1(fileHash);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    return response;
}

From source file:net.big_oh.common.web.WebUtil.java

/**
 * //from w w w.  j av  a 2 s.co m
 * Calculate an <b>approximation</b> of the memory consumed by the objects
 * stored under each attribute of a user's {@link HttpSession}. The estimate
 * will often be greater than the actual value because of "double counting"
 * objects that appear multiple times in the attribute value's object graph.
 * 
 * @param session
 *            An HttpSession object from any web application.
 * @return An <b>approximation</b> of the memory consumed for each attribute
 *         <b>name</b> in the session.
 */
public static Map<String, Integer> getSessionAttributeNameToApproxSizeInBytesMap(HttpSession session) {

    // Use an IdentityHashMap because we don't want to miss distinct objects
    // that are equivalent according to equals(..) method.
    Map<String, Integer> sessionAttributeNameToApproxSizeInBytesMap = new IdentityHashMap<String, Integer>();

    Enumeration<?> enumeration = session.getAttributeNames();
    while (enumeration.hasMoreElements()) {
        String attributeName = (String) enumeration.nextElement();
        session.getAttribute(attributeName);

        try {
            sessionAttributeNameToApproxSizeInBytesMap.put(attributeName,
                    new Integer(approximateObjectSize(attributeName)));
        } catch (IOException ioe) {
            logger.error("Failed to approximate size of session attribute name: "
                    + attributeName.getClass().getName(), ioe);
            sessionAttributeNameToApproxSizeInBytesMap.put(attributeName, new Integer(0));
        }

    }

    return sessionAttributeNameToApproxSizeInBytesMap;

}

From source file:com.katsu.dwm.reflection.JarUtils.java

/**
 * Return a list of resources inside the jar file that their URL start with path
 * @param jar/*w w  w  .jav  a  2s  . c  om*/
 * @param path
 * @return 
 */
public static List<JarEntry> getJarContent(File jar, String path) {
    try {
        JarFile jf = new JarFile(jar);
        Enumeration<JarEntry> enu = jf.entries();
        List<JarEntry> result = new ArrayList<JarEntry>();
        while (enu.hasMoreElements()) {
            JarEntry je = enu.nextElement();
            if (je.getName().startsWith(path))
                result.add(je);
        }
        return result;
    } catch (Exception e) {
        logger.error(e);
    }
    return null;
}

From source file:edu.utah.further.i2b2.hook.further.web.ServletUtil.java

/**
 * @param request//from w  ww  . j av a  2  s  .c  o  m
 */
public static void printRequestParameters(final HttpServletRequest request) {
    log.debug("Request parameters:");
    final Enumeration<?> parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        final String name = (String) parameterNames.nextElement();
        log.debug(name + " = " + request.getParameter(name));
    }
}

From source file:edu.utah.further.i2b2.hook.further.web.ServletUtil.java

/**
 * @param request//from w w w.  ja v  a  2s  . c o m
 */
public static void printRequestAttributes(final HttpServletRequest request) {
    log.debug("Request attributes:");
    final Enumeration<?> attributeNames = request.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        final String name = (String) attributeNames.nextElement();
        log.debug(name + " = " + request.getAttribute(name));
    }
}

From source file:aiai.apps.commons.utils.ZipUtils.java

/**
 * Unzips a zip file into the given destination directory.
 *
 * The archive file MUST have a unique "root" folder. This root folder is
 * skipped when unarchiving./*ww w. j ava  2 s  . c  o m*/
 *
 */
public static void unzipFolder(File archiveFile, File zipDestinationFolder) {

    log.debug("Start unzipping archive file");
    log.debug("'\tzip archive file: {}", archiveFile.getAbsolutePath());
    log.debug("'\t\tis exist: {}", archiveFile.exists());
    log.debug("'\t\tis writable: {}", archiveFile.canWrite());
    log.debug("'\t\tis readable: {}", archiveFile.canRead());
    log.debug("'\ttarget dir: {}", zipDestinationFolder.getAbsolutePath());
    log.debug("'\t\tis exist: {}", zipDestinationFolder.exists());
    log.debug("'\t\tis writable: {}", zipDestinationFolder.canWrite());
    try (MyZipFile zipFile = new MyZipFile(archiveFile)) {

        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry zipEntry = entries.nextElement();
            log.debug("'\t\tzip entry: {}, is directory: {}", zipEntry.getName(), zipEntry.isDirectory());

            String name = zipEntry.getName();
            if (zipEntry.isDirectory()) {
                if (name.endsWith("/") || name.endsWith("\\")) {
                    name = name.substring(0, name.length() - 1);
                }

                File newDir = new File(zipDestinationFolder, name);
                log.debug("'\t\t\tcreate dirs in {}", newDir.getAbsolutePath());
                if (!newDir.mkdirs()) {
                    throw new RuntimeException("Creation of target dir was failed, target dir: "
                            + zipDestinationFolder + ", entity: " + name);
                }
            } else {
                File destinationFile = DirUtils.createTargetFile(zipDestinationFolder, name);
                if (destinationFile == null) {
                    throw new RuntimeException("Creation of target file was failed, target dir: "
                            + zipDestinationFolder + ", entity: " + name);
                }
                if (!destinationFile.getParentFile().exists()) {
                    destinationFile.getParentFile().mkdirs();
                }
                log.debug("'\t\t\tcopy content of zip entry to file {}", destinationFile.getAbsolutePath());
                FileUtils.copyInputStreamToFile(zipFile.getInputStream(zipEntry), destinationFile);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Unzip failed:", e);
    }
}

From source file:Main.java

public static NetworkInterface getActiveNetworkInterface() {

    Enumeration<NetworkInterface> interfaces = null;
    try {//from w w  w.j a v a  2  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.
         */
        if (iface.getName().startsWith("w")) {
            //this is a perfect hack for getting wifi alone

            while (inetAddresses.hasMoreElements()) {
                InetAddress addr = inetAddresses.nextElement();

                if (!(addr.isLoopbackAddress() || addr.isLinkLocalAddress())) {
                    Log.d("LSSDP", "DisplayName" + iface.getDisplayName() + " Name " + iface.getName());

                    return iface;
                }
            }
        }
    }

    return null;
}