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:de.knowwe.core.user.UserContextUtil.java

/**
 * Returns a Map<String, String> with all parameters of a http request. This
 * is necessary because the parameter map of the http request is locked.
 * /*from  w ww . j a  v  a2 s.  c o  m*/
 * @created Mar 9, 2011
 * @param request the http request
 * @return map containing the parameters of the http request.
 */
public static Map<String, String> getParameters(HttpServletRequest request) {
    Map<String, String> parameters = new HashMap<>();
    if (request != null) {
        Enumeration<?> iter = request.getParameterNames();
        boolean decode = checkForFlowChart(request.getParameter("action"));
        while (iter.hasMoreElements()) {
            String key = (String) iter.nextElement();
            String value = request.getParameter(key);
            parameters.put(key, decode ? Strings.decodeURL(value) : value);
        }
        if (request.getMethod() != null && request.getMethod().equals("POST")) {

            // do not handle file uploads, leave this to the action
            if (!ServletFileUpload.isMultipartContent(request)) {

                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));

                    String line;
                    StringBuilder bob = new StringBuilder();

                    while ((line = br.readLine()) != null) {
                        bob.append(line).append("\n");
                    }

                    parameters.put("data", bob.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return parameters;
}

From source file:Main.java

public static List<Class<?>> getClassesForPackage(final String iPackageName, final ClassLoader iClassLoader)
        throws ClassNotFoundException {
    // This will hold a list of directories matching the pckgname.
    // There may be more than one if a package is split over multiple jars/paths
    List<Class<?>> classes = new ArrayList<Class<?>>();
    ArrayList<File> directories = new ArrayList<File>();
    try {//from  w w  w  .  j  av  a2  s  . c o  m
        // Ask for all resources for the path
        final String packageUrl = iPackageName.replace('.', '/');
        Enumeration<URL> resources = iClassLoader.getResources(packageUrl);
        if (!resources.hasMoreElements()) {
            resources = iClassLoader.getResources(packageUrl + CLASS_EXTENSION);
            if (resources.hasMoreElements()) {
                throw new IllegalArgumentException(
                        iPackageName + " does not appear to be a valid package but a class");
            }
        } else {
            while (resources.hasMoreElements()) {
                URL res = resources.nextElement();
                if (res.getProtocol().equalsIgnoreCase("jar")) {
                    JarURLConnection conn = (JarURLConnection) res.openConnection();
                    JarFile jar = conn.getJarFile();
                    for (JarEntry e : Collections.list(jar.entries())) {

                        if (e.getName().startsWith(iPackageName.replace('.', '/'))
                                && e.getName().endsWith(CLASS_EXTENSION) && !e.getName().contains("$")) {
                            String className = e.getName().replace("/", ".").substring(0,
                                    e.getName().length() - 6);
                            classes.add(Class.forName(className));
                        }
                    }
                } else
                    directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            }
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                iPackageName + " does not appear to be " + "a valid package (Null pointer exception)");
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                iPackageName + " does not appear to be " + "a valid package (Unsupported encoding)");
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying " + "to get all resources for " + iPackageName);
    }

    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (directory.exists()) {
            // Get the list of the files contained in the package
            File[] files = directory.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    classes.addAll(findClasses(file, iPackageName));
                } else {
                    String className;
                    if (file.getName().endsWith(CLASS_EXTENSION)) {
                        className = file.getName().substring(0,
                                file.getName().length() - CLASS_EXTENSION.length());
                        classes.add(Class.forName(iPackageName + '.' + className));
                    }
                }
            }
        } else {
            throw new ClassNotFoundException(
                    iPackageName + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    return classes;
}

From source file:com.aliyun.odps.local.common.utils.ArchiveUtils.java

@SuppressWarnings("rawtypes")
public static void unJar(File jarFile, File toDir) throws IOException {
    JarFile jar = new JarFile(jarFile);
    try {// w ww  .  ja v a  2s.com
        Enumeration entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream in = jar.getInputStream(entry);
                try {
                    File file = new File(toDir, entry.getName());
                    if (!file.getParentFile().mkdirs()) {
                        if (!file.getParentFile().isDirectory()) {
                            throw new IOException("Mkdirs failed to create " + file.getParentFile().toString());
                        }
                    }
                    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();
    }
}

From source file:com.google.enterprise.connector.otex.LivelinkConnectorFactory.java

public static LivelinkConnector getConnector(String prefix) throws RepositoryException {
    Map<String, String> p = new HashMap<String, String>();
    p.putAll(emptyProperties);//from   w w  w. j  a  v  a2 s  .c  o m

    Properties system = System.getProperties();
    Enumeration<?> names = system.propertyNames();
    boolean prefixFound = false;

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        if (name.startsWith(prefix)) {
            prefixFound = true;
            LOGGER.config("PROPERTY: " + name);
            p.put(name.substring(prefix.length()), system.getProperty(name));
        }
    }

    // If there is no connector configured by this name, bail early.
    if (!prefixFound) {
        throw new RepositoryException("No javatest." + prefix + "* properties specified for connector.");
    }

    return (LivelinkConnector) instance.makeConnector(p);
}

From source file:com.twosigma.beakerx.kernel.magic.command.ClasspathAddMvnDepsCellMagicCommandTest.java

private static void unzipRepo() {
    try {/*from   w w w.j a  va 2  s  .  com*/
        ZipFile zipFile = new ZipFile(BUILD_PATH + "/testMvnCache.zip");
        Enumeration<?> enu = zipFile.entries();
        while (enu.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enu.nextElement();
            String name = BUILD_PATH + "/" + zipEntry.getName();
            File file = new File(name);
            if (name.endsWith("/")) {
                file.mkdirs();
                continue;
            }

            File parent = file.getParentFile();
            if (parent != null) {
                parent.mkdirs();
            }

            InputStream is = zipFile.getInputStream(zipEntry);
            FileOutputStream fos = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = is.read(bytes)) >= 0) {
                fos.write(bytes, 0, length);
            }
            is.close();
            fos.close();

        }
        zipFile.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * Sets the background color for the specified <code>ButtonGroup</code> and
 * all the JCheckBox, JComboBox, JButton, and JRadioButton components that 
 * it contains to the same color.//from ww w  .j av a 2s.com
 * 
 * @param buttons the button group to set the background for.
 * @param bg the background color.
 */
public static void setBackground(ButtonGroup buttons, Color bg) {
    Enumeration<?> children = buttons.getElements();
    if (children == null) {
        return;
    }
    Component child;

    if (bg != null) {
        while (children.hasMoreElements()) {
            child = (Component) children.nextElement();
            if (!bg.equals(child.getBackground())
                    && ((child instanceof JCheckBox) || (child instanceof JComboBox)
                            || (child instanceof JButton) || (child instanceof JRadioButton))) {
                child.setBackground(bg);
            }
        }
    }
}

From source file:com.redhat.rhn.common.util.ServletUtils.java

/**
 * Creates a encoded URL query string with the parameters from the given request. If the
 * request is a GET, then the returned query string will simply consist of the query
 * string from the request. If the request is a POST, the returned query string will
 * consist of the form variables./*w  w w.  j  av  a  2s  .  c o  m*/
 *
 * <br/><br/>
 *
 * <strong>Note</strong>: This method does not support multi-value parameters.
 *
 * @param request The request for which the query string will be generated.
 *
 * @return An encoded URL query string with the parameters from the given request.
 */
public static String requestParamsToQueryString(ServletRequest request) {

    StringBuffer queryString = new StringBuffer();

    String paramName = null;
    String paramValue = null;

    Enumeration paramNames = request.getParameterNames();

    while (paramNames.hasMoreElements()) {
        paramName = (String) paramNames.nextElement();
        paramValue = request.getParameter(paramName);

        queryString.append(encode(paramName)).append("=").append(encode(paramValue)).append("&");
    }

    if (endsWith(queryString, '&')) {
        queryString.deleteCharAt(queryString.length() - 1);
    }

    return queryString.toString();
}

From source file:de.lazyzero.kkMulticopterFlashTool.utils.Zip.java

public static File unzipFile(File zipFile, File file) {
    System.out.println("path to zipFile: " + zipFile.getPath());
    System.out.println("file to extract: " + file.getPath());
    String fileName = null;/*w ww .j  av a2 s.c o m*/

    try {
        zipFile.mkdir();
        BufferedOutputStream dest = null;
        BufferedInputStream is = null;
        ZipEntry entry;
        ZipFile zipfile = new ZipFile(zipFile);
        Enumeration e = zipfile.entries();
        while (e.hasMoreElements()) {
            entry = (ZipEntry) e.nextElement();
            // System.out.println(entry.getName());
            if (entry.getName().substring(entry.getName().indexOf("/") + 1).equals(file.getName())) {
                //   if (entry.getName().contains(file.getName())){
                System.out.println("firmware to extract found.");

                String tempFolder = System.getProperty("user.dir") + File.separatorChar + "tmp"
                        + File.separatorChar;
                if (System.getProperty("os.name").toLowerCase().contains("mac")) {
                    tempFolder = System.getProperty("user.home")
                            + "/Library/Preferences/kkMulticopterFlashTool/";
                }

                String newDir;
                if (entry.getName().indexOf("/") == -1) {
                    newDir = zipFile.getName().substring(0, zipFile.getName().indexOf("."));
                } else {
                    newDir = entry.getName().substring(0, entry.getName().indexOf("/"));
                }
                String folder = tempFolder + newDir;
                System.out.println("Create folder: " + folder);
                if ((new File(folder).mkdir())) {
                    System.out.println("Done.");
                    ;
                }

                System.out.println("Extracting: " + entry);
                is = new BufferedInputStream(zipfile.getInputStream(entry));
                int count;
                byte data[] = new byte[2048];
                fileName = tempFolder + entry.getName();
                FileOutputStream fos = new FileOutputStream(tempFolder + entry.getName());
                dest = new BufferedOutputStream(fos, 2048);
                while ((count = is.read(data, 0, 2048)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
                is.close();
                break;
            }
        }
    } catch (ZipException e) {
        zipFile.delete();
        kk.err(Translatrix._("error.zipfileDamaged"));
        kk.err(Translatrix._("reportProblem"));
    } catch (Exception e) {
        e.printStackTrace();
    }

    return new File(fileName);
}

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  w  ww  .ja v  a 2 s  .c o  m
    }

    return recordings;
}

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

/**
 * This function returns the first external IP address encountered
 *
 * @return IP address or null//from ww w .  j a v  a 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;
}