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:Main.java

@SuppressWarnings("unchecked")
public static <T extends Collection<K>, K> T toCollection(Class<?> clazz, Enumeration<K> enumeration) {
    if (clazz == null) {
        throw new RuntimeException("Class cannot be null.");
    }/*w  w w. j a  va2 s.  c  o  m*/
    try {
        T collection = (T) clazz.newInstance();

        if (enumeration != null) {
            while (enumeration.hasMoreElements()) {
                collection.add(enumeration.nextElement());
            }
        }

        return collection;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.autentia.tnt.util.JPivotUtils.java

/**
 * Ejecuta una query MDX sobre un cubo OLAP utilizando el datasource por defecto. <br>
 * El resultado lo almacena en el contexto de sesin para que pueda ser recogido y pintado por las etiquetas de JPivot.
 * //  w  w  w. java 2s  .com
 * @param mdxQuery query a ejecutar
 * @param cubeSchema URL del que representa el cubo OLAP
 * @return
 * @throws SAXException
 * @throws IOException
 * @throws OlapException
 */
public static OlapModel executeOlapQuery(String mdxQuery, URL schema, HttpSession session)
        throws SAXException, IOException, OlapException {

    final RequestContext context = RequestContext.instance();

    // final URL schema = JpivotUtils.class.getResource(cubeSchema);//new URL("file:///"+cubeSchema);//

    final MondrianModelFactory.Config cfg = new MondrianModelFactory.Config();
    cfg.setMdxQuery(mdxQuery);
    cfg.setSchemaUrl(schema.toExternalForm());
    cfg.setDataSource(DATA_SOURCE);

    final MondrianModel mondrianModel = MondrianModelFactory.instance(cfg);
    final OlapModel olapModel = (OlapModel) mondrianModel.getTopDecorator();
    olapModel.setLocale(context.getLocale());
    // olapModel.setLocale(FacesContext.getCurrentInstance().getViewRoot().getLocale());
    olapModel.setServletContext(context.getSession().getServletContext());
    // olapModel.setServletContext((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext());

    // olapModel.
    olapModel.initialize();

    if (log.isDebugEnabled()) {
        java.util.Enumeration attributeNames = session.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String name = (String) attributeNames.nextElement();
            log.debug("--- name: " + name + "; type:" + session.getAttribute(name).getClass() + " ---");
        }
    }

    // borramos de la sesion los datos que ha metido JPivot
    // y el model de la consulta que volveremos a meter
    // Esto es necesario porque los tags de JPivot no machacan los
    // valores si ya estn en sesin; por lo que al cambiar de informe
    // sigue mostrando el informe selecionado previamente
    session.removeAttribute(JPivotUtils.QUERY_SESSION_NAME);
    session.removeAttribute(JPivotUtils.TABLE_SESSION_NAME);
    session.removeAttribute(JPivotUtils.NAVI_SESSION_NAME);
    session.removeAttribute(JPivotUtils.SORTFORM_SESSION_NAME);
    session.removeAttribute(JPivotUtils.PRINT_SESSION_NAME);
    session.removeAttribute(JPivotUtils.PRINTFORM_SESSION_NAME);
    session.removeAttribute(JPivotUtils.CHART_SESSION_NAME);
    session.removeAttribute(JPivotUtils.CHARTFORM_SESSION_NAME);
    session.removeAttribute(JPivotUtils.TOOLBAR_SESSION_NAME);

    session.setAttribute(JPivotUtils.QUERY_SESSION_NAME, olapModel);
    return olapModel;
}

From source file:com.mc.printer.model.utils.ZipHelper.java

/**
 * jar????//from   ww w.ja  v  a  2s.  c o m
 *
 * @param jar ????jar
 * @param subDir jar???????
 * @param loc ????
 * @param force ????
 * @return
 */
public static boolean unZip(String jar, String subDir, String loc, boolean force) {
    try {
        File base = new File(loc);
        if (!base.exists()) {
            base.mkdirs();
        }

        ZipFile zip = new ZipFile(new File(jar));
        Enumeration<? extends ZipEntry> entrys = zip.entries();
        while (entrys.hasMoreElements()) {
            ZipEntry entry = entrys.nextElement();
            String name = entry.getName();
            if (!name.startsWith(subDir)) {
                continue;
            }
            //subDir
            name = name.replace(subDir, "").trim();
            if (name.length() < 2) {
                log.debug(name + "  < 2");
                continue;
            }
            if (entry.isDirectory()) {
                File dir = new File(base, name);
                if (!dir.exists()) {
                    dir.mkdirs();
                    log.debug("create directory");
                } else {
                    log.debug("the directory is existing.");
                }
                log.debug(name + " is a directory");
            } else {
                File file = new File(base, name);
                if (file.exists() && force) {
                    file.delete();
                }
                if (!file.exists()) {
                    InputStream in = zip.getInputStream(entry);
                    FileUtils.copyInputStreamToFile(in, file);
                    log.debug("create file.");
                    in.close();
                } else {
                    log.debug("the file is existing");
                }
                log.debug(name + " is not a directory");
            }
        }
        zip.close();
    } catch (ZipException ex) {
        ex.printStackTrace();
        log.error("file unzip failed.", ex);
        return false;
    } catch (IOException ex) {
        ex.printStackTrace();
        log.error("file IO failed", ex);
        return false;
    }
    return true;
}

From source file:com.netflix.config.ClasspathPropertiesConfiguration.java

private static void loadResources(ClassLoader loader, String resourceName) throws Exception {
    Enumeration<URL> resources = loader.getResources(resourceName);
    boolean loadedResources = false;
    while (resources.hasMoreElements()) {
        URL from = resources.nextElement();
        /* Properties props = loadProperties(from);
        String configName = getConfigName(props, from);
        containerConfiguration.addConfiguration(
              new PropertiesConfiguration(from), configName); */
        ConfigurationManager.loadPropertiesFromResources(from.getPath());
        log.debug("Added properties from:" + from + from.getPath());
        loadedResources = true;/* w w w.  j a v a2  s.  c  o m*/
    }
    if (!loadedResources) {
        log.debug("Did not find any properties resource in the classpath with name:"
                + propertiesResourceRelativePath);
    }
}

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

/**
 * Create a chart representing an arbitrary collection of name/value pairs. 
 * The data is passed in as a hashtable where the key is the name and the  
 * value is the number items. //  w w  w.java  2  s . c o  m
 */
public static final JFreeChart getBarChart(Hashtable<String, Integer> data, String title, String nameLabel,
        String valueLabel) {
    JFreeChart chart = null;

    // Sort the data by name
    Vector<String> names = new Vector<String>();
    Enumeration nameList = data.keys();
    while (nameList.hasMoreElements()) {
        names.add((String) nameList.nextElement());
    }
    Collections.sort(names);

    // Populate the dataset with data
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    Iterator keyIter = names.iterator();
    while (keyIter.hasNext()) {
        String name = (String) keyIter.next();
        Integer value = data.get(name);
        dataset.addValue(value, valueLabel, name);
    }

    // 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.vaadin.tests.tb3.PrivateTB3Configuration.java

/**
 * Tries to automatically determine the IP address of the machine the test
 * is running on.//from   w  w  w. j a  v a2s .c  om
 * 
 * @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:com.chinamobile.bcbsp.fault.tools.Zip.java

/**
 * Uncompress *.zip files.//from  w  w  w .  jav  a  2  s . c om
 * @param fileName
 *        : file to be uncompress
 */
@SuppressWarnings("unchecked")
public static void decompress(String fileName) {
    File sourceFile = new File(fileName);
    String filePath = sourceFile.getParent() + "/";
    try {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        ZipFile zipFile = new ZipFile(fileName);
        Enumeration en = zipFile.entries();
        byte[] data = new byte[BUFFER];
        while (en.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) en.nextElement();
            if (entry.isDirectory()) {
                new File(filePath + entry.getName()).mkdirs();
                continue;
            }
            bis = new BufferedInputStream(zipFile.getInputStream(entry));
            File file = new File(filePath + entry.getName());
            File parent = file.getParentFile();
            if (parent != null && (!parent.exists())) {
                parent.mkdirs();
            }
            bos = new BufferedOutputStream(new FileOutputStream(file));
            int count;
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                bos.write(data, 0, count);
            }
            bis.close();
            bos.close();
        }
        zipFile.close();
    } catch (IOException e) {
        //LOG.error("[compress]", e);
        throw new RuntimeException("[compress]", e);
    }
}

From source file:ReflectUtils.java

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

From source file:com.littcore.io.util.ZipUtils.java

public static void unzip(File srcZipFile, File targetFilePath, boolean isDelSrcFile) throws IOException {
    if (!targetFilePath.exists()) //?
        targetFilePath.mkdirs();//from  w w  w.ja va2 s  . co  m
    ZipFile zipFile = new ZipFile(srcZipFile);

    Enumeration fileList = zipFile.getEntries();
    ZipEntry zipEntry = null;
    while (fileList.hasMoreElements()) {
        zipEntry = (ZipEntry) fileList.nextElement();
        if (zipEntry.isDirectory()) //?
        {
            File subFile = new File(targetFilePath, zipEntry.getName());
            if (!subFile.exists()) //??
                subFile.mkdir();
            continue;
        } else //?
        {
            File targetFile = new File(targetFilePath, zipEntry.getName());
            if (logger.isDebugEnabled()) {
                logger.debug("" + targetFile.getName());
            }

            if (!targetFile.exists()) {
                File parentPath = new File(targetFile.getParent());
                if (!parentPath.exists()) //????????
                    parentPath.mkdirs();
                //targetFile.createNewFile();
            }

            InputStream in = zipFile.getInputStream(zipEntry);
            FileOutputStream out = new FileOutputStream(targetFile);
            int len;
            byte[] buf = new byte[BUFFERED_SIZE];
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            out.close();
            in.close();
        }
    }
    zipFile.close();
    if (isDelSrcFile) {
        boolean isDeleted = srcZipFile.delete();
        if (isDeleted) {
            if (logger.isDebugEnabled()) {
                logger.debug("");
            }
        }
    }
}

From source file:com.isomorphic.maven.util.ArchiveUtils.java

/**
 * Unzips the <code>source</code> file to the <code>target</code> directory.
 * /*from  w w  w.  ja  v a2  s  . c  om*/
 * @param source The file to be unzipped
 * @param target The directory to which the source file should be unzipped
 * @throws IOException
 */
public static void unzip(File source, File target) throws IOException {

    ZipFile zip = new ZipFile(source);
    Enumeration<? extends ZipEntry> entries = zip.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File file = new File(target, entry.getName());
        FileUtils.copyInputStreamToFile(zip.getInputStream(entry), file);
    }
}