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:com.bfd.harpc.common.configure.ResourceUtils.java

private static URL[] load1(String locationPattern) throws IOException, URISyntaxException {
    String location = locationPattern.substring(ResourceConstants.CLASSPATH_ALL_URL_PREFIX.getValue().length());
    if (location.startsWith(ResourceConstants.FOLDER_SEPARATOR.getValue())) {
        location = location.substring(1);
    }/*from w  w w. jav  a2s .  com*/

    Enumeration<URL> resourceUrls = getDefaultClassLoader().getResources(location);
    Set<URL> result = new LinkedHashSet<URL>(16);
    while (resourceUrls.hasMoreElements()) {
        URL url = resourceUrls.nextElement();
        result.add(PathUtils.cleanPath(url));
    }
    return result.toArray(new URL[result.size()]);
}

From source file:com.vaadin.tests.tb3.PrivateTB3Configuration.java

/**
 * Tries to automatically determine the IP address of the machine the test
 * is running on./*  ww w .  ja va 2s  .  c o m*/
 * 
 * @return An IP address of one of the network interfaces in the machine.
 * @throws RuntimeException
 *             if there was an error or no IP was found
 */
private static String findAutoHostname() {
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface nwInterface = interfaces.nextElement();
            if (!nwInterface.isUp() || nwInterface.isLoopback() || nwInterface.isVirtual()) {
                continue;
            }
            Enumeration<InetAddress> addresses = nwInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                if (address.isLoopbackAddress()) {
                    continue;
                }
                if (address.isSiteLocalAddress()) {
                    return address.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException("Could not enumerate ");
    }

    throw new RuntimeException("No compatible (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) ip address found.");
}

From source file:gov.llnl.lc.smt.command.about.SmtAbout.java

protected static ArrayList<SmtAboutRecord> getRecordsFromFile(Object obj, String fileName) {
    ArrayList<SmtAboutRecord> records = new ArrayList<SmtAboutRecord>();

    try {/* ww w .  ja v a 2 s.  com*/
        Enumeration<URL> resources = obj.getClass().getClassLoader().getResources(fileName);
        while (resources.hasMoreElements()) {
            Manifest man = new Manifest(resources.nextElement().openStream());
            SmtAboutRecord r = new SmtAboutRecord(man);
            if ((r != null) && r.isValid())
                records.add(r);
        }
    } catch (IOException E) {
        // handle
    }
    return records;
}

From source file:Utilities.java

/**
 * Converts the specified <code>Hashtable</code> into a string by putting
 * each key and value on a separate line (separated by '\n') and an arrow
 * (" -> ") between them./*from w  w w.jav  a 2  s  .  c  om*/
 */

public static String hashtableToString(Hashtable hashtable) {
    StringBuffer buf = new StringBuffer();
    Enumeration keys = hashtable.keys();
    while (keys.hasMoreElements()) {
        Object key = keys.nextElement();
        Object value = hashtable.get(key);
        buf.append(key.toString());
        buf.append(" -> ");
        buf.append(value.toString());
        buf.append("\n");
    }

    return buf.toString();
}

From source file:com.stimulus.archiva.domain.EmailID.java

public static synchronized String generateUniqueID(Email email) {
    try {//from w  w w  . j  av a  2s.co m
        MimeMessage raw = email;
        // we need a backup plan here
        if (raw == null) {
            return DateUtil.convertDatetoString(new Date());
        }
        Enumeration<Header> headers = raw.getAllHeaders();
        LinkedList<String> orderedHeaders = new LinkedList<String>();
        while (headers.hasMoreElements()) {
            Header header = headers.nextElement();

            if (Compare.equalsIgnoreCase(header.getName(), "Date")
                    || Compare.equalsIgnoreCase(header.getName(), "CC")
                    || Compare.equalsIgnoreCase(header.getName(), "BCC")
                    || Compare.equalsIgnoreCase(header.getName(), "Subject")
                    || Compare.equalsIgnoreCase(header.getName(), "To")
                    || Compare.equalsIgnoreCase(header.getName(), "From"))
                orderedHeaders.add(header.getName() + header.getValue());

        }
        Collections.sort(orderedHeaders);
        StringBuffer allHeaders = new StringBuffer();
        for (String header : orderedHeaders)
            allHeaders.append(header);
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] bytes = allHeaders.toString().getBytes();
        InputStream is = new ByteArrayInputStream(bytes);
        DigestInputStream dis = new DigestInputStream(is, sha);
        while (dis.read() != -1)
            ;
        dis.close();
        byte[] digest = sha.digest();
        return toHex(digest);
    } catch (Exception e) {
        logger.error("failed to generate a uniqueid for a message");
        return null;
    }
}

From source file:in.xebia.poc.FileUploadUtils.java

public static boolean parseFileUploadRequest(HttpServletRequest request, File outputFile,
        Map<String, String> params) throws Exception {
    log.debug("Request class? " + request.getClass().toString());
    log.debug("Request is multipart? " + ServletFileUpload.isMultipartContent(request));
    log.debug("Request method: " + request.getMethod());
    log.debug("Request params: ");
    for (Object key : request.getParameterMap().keySet()) {
        log.debug((String) key);//from ww  w.  jav  a 2  s . c om
    }
    log.debug("Request attribute names: ");

    boolean filedataInAttributes = false;
    Enumeration attrNames = request.getAttributeNames();
    while (attrNames.hasMoreElements()) {
        String attrName = (String) attrNames.nextElement();
        log.debug(attrName);
        if ("filedata".equals(attrName)) {
            filedataInAttributes = true;
        }
    }

    if (filedataInAttributes) {
        log.debug("Found filedata in request attributes, getting it out...");
        log.debug("filedata class? " + request.getAttribute("filedata").getClass().toString());
        FileItem item = (FileItem) request.getAttribute("filedata");
        item.write(outputFile);
        for (Object key : request.getParameterMap().keySet()) {
            params.put((String) key, request.getParameter((String) key));
        }
        return true;
    }

    /*ServletFileUpload upload = new ServletFileUpload();
    //upload.setSizeMax(Globals.MAX_UPLOAD_SIZE);
    FileItemIterator iter = upload.getItemIterator(request);
    while(iter.hasNext()){
       FileItemStream item = iter.next();
       InputStream stream = item.openStream();
               
       //If this item is a file
       if(!item.isFormField()){
             
     log.debug("Found non form field in upload request with field name = " + item.getFieldName());
             
     String name = item.getName();
     if(name == null){
         throw new Exception("File upload did not have filename specified");
     }
             
        // Some browsers, including IE, return the full path so trim off everything but the file name
        name = getFileNameFromPath(name);
                 
    //Enforce required file extension, if present
    if(!name.toLowerCase().endsWith( ".zip" )){
       throw new Exception("File uploaded did not have required extension .zip");
    }
            
      bufferedCopyStream(stream, new FileOutputStream(outputFile));
       }
       else {
    params.put(item.getFieldName(), Streams.asString(stream));
       }
    }
    return true;*/

    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request
    List /* FileItem */ items = upload.parseRequest(request);

    // Process the uploaded items
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            log.debug("Found non form field in upload request with field name = " + item.getFieldName());

            String name = item.getName();
            if (name == null) {
                throw new Exception("File upload did not have filename specified");
            }

            // Some browsers, including IE, return the full path so trim off everything but the file name
            name = getFileNameFromPath(name);

            item.write(outputFile);
        } else {
            params.put(item.getFieldName(), item.getString());
        }
    }
    return true;
}

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

public static Class[] findAnnotatedClasses(String packageName, Class annotation)
        throws IOException, ClassNotFoundException {
    String path = packageName.replace('.', '/');
    Enumeration<URL> resources = loader.getResources(path);
    Set<File> dirs = new HashSet<File>();
    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        dirs.add(new File(resource.getFile()));
    }//from ww  w  .ja  v  a2  s . c  o  m
    for (URL url : loader.getURLs()) {
        dirs.add(new File(url.getFile()));
    }

    ArrayList<Class> classes = new ArrayList<Class>();
    for (File directory : dirs) {
        classes.addAll(findClasses(directory, packageName, annotation));
    }

    return classes.toArray(new Class[classes.size()]);
}

From source file:de.anycook.db.mysql.DBHandler.java

public static void closeSource() {
    try {/*from w ww. ja  v a2  s  .c o  m*/
        dataSource.close();
        dataSource = null;
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            DriverManager.deregisterDriver(drivers.nextElement());
        }
    } catch (SQLException e) {
        sLogger.error(e);
    }
}

From source file:de.rub.syssec.saaf.analysis.steps.extract.ApkUnzipper.java

/**
 * Extracts the given archive into the given destination directory
 * /* ww  w  . j  a va  2  s.  c  om*/
 * @param archive
 *            - the file to extract
 * @param dest
 *            - the destination directory
 * @throws Exception
 */
public static void extractArchive(File archive, File destDir) throws IOException {

    if (!destDir.exists()) {
        destDir.mkdir();
    }

    ZipFile zipFile = new ZipFile(archive);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    byte[] buffer = new byte[16384];
    int len;
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();

        String entryFileName = entry.getName();

        File dir = buildDirectoryHierarchyFor(entryFileName, destDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        if (!entry.isDirectory()) {

            File file = new File(destDir, entryFileName);

            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));

            BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));

            while ((len = bis.read(buffer)) > 0) {
                bos.write(buffer, 0, len);
            }

            bos.flush();
            bos.close();
            bis.close();
        }
    }
    zipFile.close();
}