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:io.apiman.test.common.mock.EchoServlet.java

/**
 * Create an echo response from the inbound information in the http server
 * request.//  w  ww. j  av a2 s.c om
 * @param request the request
 * @param withBody if request is with body
 * @return a new echo response
 */
public static EchoResponse response(HttpServletRequest request, boolean withBody) {
    EchoResponse response = new EchoResponse();
    response.setMethod(request.getMethod());
    if (request.getQueryString() != null) {
        String[] normalisedQueryString = request.getQueryString().split("&");
        Arrays.sort(normalisedQueryString);
        response.setResource(
                request.getRequestURI() + "?" + SimpleStringUtils.join("&", normalisedQueryString));
    } else {
        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");
            byte[] data = new byte[1024];
            int read;
            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:gov.llnl.lc.smt.command.about.SmtAbout.java

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

    try {//w  ww . j  a v  a 2  s  .  c o m
        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:com.feedzai.fos.server.remote.impl.RemoteInterfacesTest.java

/**
 * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
 *
 * @param packageName The base package// ww w . java2 s. c  o m
 * @return The classes
 * @throws ClassNotFoundException
 * @throws java.io.IOException
 */
private static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    assert classLoader != null;
    String path = packageName.replace('.', '/');
    Enumeration<URL> resources = classLoader.getResources(path);
    List<File> dirs = new ArrayList<>();
    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        dirs.add(new File(resource.getFile()));
    }
    ArrayList<Class> classes = new ArrayList<>();
    for (File directory : dirs) {
        classes.addAll(findClasses(directory, packageName));
    }
    return classes.toArray(new Class[classes.size()]);
}

From source file:org.openo.nfvo.jujuvnfmadapter.common.DownloadCsarManager.java

/**
 * unzip CSAR packge/*from   w w  w. ja  va  2  s.c o  m*/
 * @param fileName filePath
 * @return
 */
public static int unzipCSAR(String fileName, String filePath) {
    final int BUFFER = 2048;
    int status = 0;

    try {
        ZipFile zipFile = new ZipFile(fileName);
        Enumeration emu = zipFile.entries();
        int i = 0;
        while (emu.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) emu.nextElement();
            //read directory as file first,so only need to create directory
            if (entry.isDirectory()) {
                new File(filePath + entry.getName()).mkdirs();
                continue;
            }
            BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
            File file = new File(filePath + entry.getName());
            //Because that is random to read zipfile,maybe the file is read first
            //before the directory is read,so we need to create directory first.
            File parent = file.getParentFile();
            if (parent != null && (!parent.exists())) {
                parent.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);

            int count;
            byte data[] = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                bos.write(data, 0, count);
            }
            bos.flush();
            bos.close();
            bis.close();

            if (entry.getName().endsWith(".zip")) {
                File subFile = new File(filePath + entry.getName());
                if (subFile.exists()) {
                    int subStatus = unzipCSAR(filePath + entry.getName(), subFile.getParent() + "/");
                    if (subStatus != 0) {
                        LOG.error("sub file unzip fail!" + subFile.getName());
                        status = Constant.UNZIP_FAIL;
                        return status;
                    }
                }
            }
        }
        status = Constant.UNZIP_SUCCESS;
        zipFile.close();
    } catch (Exception e) {
        status = Constant.UNZIP_FAIL;
        e.printStackTrace();
    }
    return status;
}

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

public static void closeSource() {
    try {//from  ww  w. ja  va 2  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:hudson.matrix.Axis.java

/**
 * Parses the submitted form (where possible values are
 * presented as a list of checkboxes) and creates an axis
 *//*from  w ww  .  ja va2 s  .  c  om*/
public static Axis parsePrefixed(StaplerRequest req, String name) {
    List<String> values = new ArrayList<String>();
    String prefix = name + '.';

    Enumeration e = req.getParameterNames();
    while (e.hasMoreElements()) {
        String paramName = (String) e.nextElement();
        if (paramName.startsWith(prefix))
            values.add(paramName.substring(prefix.length()));
    }
    if (values.isEmpty())
        return null;
    return new Axis(name, values);
}

From source file:net.openkoncept.vroom.VroomUtilities.java

/**
 * <p>//from ww  w. ja v a2s .  co  m
 * This useful method converts a map to JSONObject.
 * </p>
 *
 * @param bundle - ResourceBundle (preferrably with key/value pairs)
 * @return - JSON object.
 */
public static JSONObject bundleToJSONObject(ResourceBundle bundle) {
    JSONObject jo = new JSONObject();
    if (bundle != null) {
        Enumeration e = bundle.getKeys();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            try {
                jo.append(key, bundle.getString(key));
            } catch (JSONException ex) {
                // Not required!
            }
        }
    }
    return jo;
}

From source file:Main.java

/**
 * Wraps an {@link Enumeration} as an instance of {@link Iterable} so that
 * it can be passed into a "for each" logical construct.
 * /*from  w  ww  .  ja v  a 2 s.  c o  m*/
 * @param <T>
 * @param enumeration
 * @return An Iterable representation of the enumeration parameter.
 */
public static <T> Iterable<T> toIterable(final Enumeration<T> enumeration) {

    return new Iterable<T>() {
        public Iterator<T> iterator() {
            return new Iterator<T>() {

                public boolean hasNext() {
                    return enumeration.hasMoreElements();
                }

                public T next() {
                    return enumeration.nextElement();
                }

                public void remove() {
                    throw new UnsupportedOperationException();
                }
            };

        }
    };

}

From source file:com.modeln.build.ctrl.charts.CMnPatchCountChart.java

/**
 * Create a chart representing the number patches grouped by time interval.
 * The data passed in the hashtable is a list of the time intervals and
 * the value is the number of patch requests for each interval.
 *
 * @param  data   Hashtable cnotaining the time intervals and corresponding counts
 * @param  label  Count label// w ww  .  j av  a2  s.co  m
 *
 * @return Bar chart representing the interval and count information
 */
public static final JFreeChart getPatchesByIntervalChart(Hashtable<CMnTimeInterval, Integer> data,
        String label) {
    JFreeChart chart = null;

    String title = "Patches per " + label;
    String nameLabel = label;
    String valueLabel = "Patches";

    // Sort the data by date
    Vector<CMnTimeInterval> intervals = new Vector<CMnTimeInterval>();
    Enumeration intervalList = data.keys();
    while (intervalList.hasMoreElements()) {
        intervals.add((CMnTimeInterval) intervalList.nextElement());
    }
    Collections.sort(intervals);

    // Populate the dataset with data
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    Iterator keyIter = intervals.iterator();
    while (keyIter.hasNext()) {
        CMnTimeInterval interval = (CMnTimeInterval) keyIter.next();
        Integer value = data.get(interval);
        dataset.addValue(value, valueLabel, interval.getName());
    }

    // Create the chart
    chart = ChartFactory.createBarChart(title, /*title*/
            nameLabel, /*categoryAxisLabel*/
            valueLabel, /*valueAxisLabel*/
            dataset, /*dataset*/
            PlotOrientation.VERTICAL, /*orientation*/
            false, /*legend*/
            false, /*tooltips*/
            false /*urls*/
    );

    // get a reference to the plot for further customization...
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    //chartFormatter.formatMetricChart(plot, "min");

    // Set the chart colors
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);

    // set the range axis to display integers only...
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    // disable bar outlines...
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);
    renderer.setShadowVisible(false);
    final GradientPaint gp = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, Color.blue);
    renderer.setSeriesPaint(0, gp);

    // Set the label orientation
    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

    return chart;
}

From source file:com.tesora.dve.common.PELogUtils.java

private static Attributes readManifestFile() throws PEException {
    try {// w w w.  ja v  a2  s .  c om
        Enumeration<URL> resources = PELogUtils.class.getClassLoader().getResources(MANIFEST_FILE_NAME);

        Attributes attrs = new Attributes();
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            if (url.toString().contains(CORE_PROJECT_NAME)) {
                Manifest manifest = new Manifest(url.openStream());
                attrs = manifest.getMainAttributes();
                break;
            }
        }
        return attrs;
    } catch (Exception e) {
        throw new PEException("Error retrieving build manifest", e);
    }
}