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

public static void unzip(URL _url, URL _dest, boolean _remove_top) {
    int BUFFER_SZ = 2048;
    File file = new File(_url.getPath());

    String dest = _dest.getPath();
    new File(dest).mkdir();

    try {//  w ww  .  jav  a 2  s. c om
        ZipFile zip = new ZipFile(file);
        Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();

        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();

            if (_remove_top)
                currentEntry = currentEntry.substring(currentEntry.indexOf('/'), currentEntry.length());

            File destFile = new File(dest, currentEntry);
            //destFile = new File(newPath, destFile.getName());
            File destinationParent = destFile.getParentFile();

            // create the parent directory structure if needed
            destinationParent.mkdirs();

            if (!entry.isDirectory()) {
                BufferedInputStream is;
                is = new BufferedInputStream(zip.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte data[] = new byte[BUFFER_SZ];

                // write the current file to disk
                FileOutputStream fos = new FileOutputStream(destFile);
                BufferedOutputStream dst = new BufferedOutputStream(fos, BUFFER_SZ);

                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, BUFFER_SZ)) != -1) {
                    dst.write(data, 0, currentByte);
                }
                dst.flush();
                dst.close();
                is.close();
            }
            /*
            if (currentEntry.endsWith(".zip"))
            {
            // found a zip file, try to open
            extractFolder(destFile.getAbsolutePath());
            }*/
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

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

/**
 * <p>/* www . j a  va  2s .  c o 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:com.chinamobile.bcbsp.fault.tools.Zip.java

/**
 * Uncompress *.zip files.// www  . j  a v a  2s  .  co m
 * @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:hudson.matrix.Axis.java

/**
 * Parses the submitted form (where possible values are
 * presented as a list of checkboxes) and creates an axis
 *//*from  w  w  w .j  a  v a  2 s .c o m*/
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: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.
 * /*ww  w .j  av a2s  .  c om*/
 * @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:org.openo.nfvo.jujuvnfmadapter.common.DownloadCsarManager.java

/**
 * unzip CSAR packge//from   w  ww .  jav  a 2s . c om
 * @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:com.ibm.util.merge.CompareArchives.java

/**
 * @param archive//from ww  w.  j  a  v a2 s  . c o m
 * @return
 * @throws IOException
 */
private static final HashMap<String, ZipEntry> getMembers(ZipFile archive) throws IOException {
    HashMap<String, ZipEntry> map = new HashMap<>();
    @SuppressWarnings("unchecked")
    Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) archive.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        map.put(entry.getName(), entry);
    }
    return map;
}

From source file:Main.java

/**
 * Given an Object, and a key (index), returns the value associated with
 * that key in the Object. The following checks are made:
 * <ul>/*from   ww w .j a  va  2s .co m*/
 * <li>If obj is a Map, use the index as a key to get a value. If no match continue.
 * <li>Check key is an Integer. If not, return the object passed in.
 * <li>If obj is a Map, get the nth value from the <b>keySet</b> iterator.
 *     If the Map has fewer than n entries, return an empty Iterator.
 * <li>If obj is a List or an array, get the nth value, throwing IndexOutOfBoundsException,
 *     ArrayIndexOutOfBoundsException, resp. if the nth value does not exist.
 * <li>If obj is an iterator, enumeration or Collection, get the nth value from the iterator,
 *     returning an empty Iterator (resp. Enumeration) if the nth value does not exist.
 * <li>Return the original obj.
 * </ul>
 *
 * @param obj  the object to get an index of
 * @param index  the index to get
 * @return the object at the specified index
 * @throws IndexOutOfBoundsException
 * @throws ArrayIndexOutOfBoundsException
 *
 * @deprecated use {@link #get(Object, int)} instead. Will be removed in v4.0
 */
public static Object index(Object obj, Object index) {
    if (obj instanceof Map) {
        Map map = (Map) obj;
        if (map.containsKey(index)) {
            return map.get(index);
        }
    }
    int idx = -1;
    if (index instanceof Integer) {
        idx = ((Integer) index).intValue();
    }
    if (idx < 0) {
        return obj;
    } else if (obj instanceof Map) {
        Map map = (Map) obj;
        Iterator iterator = map.keySet().iterator();
        return index(iterator, idx);
    } else if (obj instanceof List) {
        return ((List) obj).get(idx);
    } else if (obj instanceof Object[]) {
        return ((Object[]) obj)[idx];
    } else if (obj instanceof Enumeration) {
        Enumeration it = (Enumeration) obj;
        while (it.hasMoreElements()) {
            idx--;
            if (idx == -1) {
                return it.nextElement();
            } else {
                it.nextElement();
            }
        }
    } else if (obj instanceof Iterator) {
        return index((Iterator) obj, idx);
    } else if (obj instanceof Collection) {
        Iterator iterator = ((Collection) obj).iterator();
        return index(iterator, idx);
    }
    return obj;
}

From source file:com.norconex.commons.lang.ClassFinder.java

private static List<String> findSubTypesFromJar(File jarFile, Class<?> superClass) {

    List<String> classes = new ArrayList<String>();
    ClassLoader loader = getClassLoader(jarFile);
    if (loader == null) {
        return classes;
    }/*from www.j av  a2s. co m*/
    JarFile jar = null;
    try {
        jar = new JarFile(jarFile);
    } catch (IOException e) {
        LOG.error("Invalid JAR: " + jarFile, e);
        return classes;
    }
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String className = entry.getName();
        className = resolveName(loader, className, superClass);
        if (className != null) {
            classes.add(className);
        }
    }
    try {
        jar.close();
    } catch (IOException e) {
        LOG.error("Could not close JAR.", e);
    }
    return classes;
}

From source file:com.dv.util.DataViewerZipUtil.java

public static void doUnzipFile(ZipFile zipFile, File dest) throws IOException {
    if (!dest.exists()) {
        FileUtils.forceMkdir(dest);// w  w  w .  j  av  a  2 s  . c o  m
    }
    Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File file = new File(dest, entry.getName());
        if (entry.getName().endsWith(File.separator)) {
            FileUtils.forceMkdir(file);
        } else {
            OutputStream out = FileUtils.openOutputStream(file);
            InputStream in = zipFile.getInputStream(entry);
            try {
                IOUtils.copy(in, out);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(out);
            }
        }
    }
    zipFile.close();
}