Example usage for java.util ArrayList iterator

List of usage examples for java.util ArrayList iterator

Introduction

In this page you can find the example usage for java.util ArrayList iterator.

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this list in proper sequence.

Usage

From source file:fr.iphc.grid.jobmonitor.CeList.java

public static void BilanCe(String OutDir, ArrayList<URL> serviceURL, String TableSql)
        throws ParserConfigurationException, SAXException, IOException, DOMException, ParseException {
    File directory = new File(OutDir);
    ArrayList<CeDefinition> bilan = new ArrayList<CeDefinition>();
    Iterator<URL> i = serviceURL.iterator();

    //      XPathExpression expr = null;
    Document doc = null;// w ww.  j  a  va  2  s  .co  m
    CeDefinition ce = null;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    while (i.hasNext()) {
        URL url = i.next();
        String file = url.getHost() + "_" + url.getPath().replaceAll("/cream-", "");
        File entry = new File(directory, file + ".out");
        if (entry.exists()) {
            doc = builder.parse(entry);
            ce = new CeDefinition();
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("CeHost");
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    ce.setDate(
                            dateFormat.parse(eElement.getElementsByTagName("Start").item(0).getTextContent()));
                    // System.out.println("Start : " +
                    // eElement.getElementsByTagName("Start").item(0).getTextContent());
                    ce.setCe(eElement.getElementsByTagName("Ce").item(0).getTextContent());
                    ce.setPath(eElement.getElementsByTagName("Path").item(0).getTextContent());
                    ce.setJobid(eElement.getElementsByTagName("Jobid").item(0).getTextContent());
                    ce.setState(eElement.getElementsByTagName("Status").item(0).getTextContent());
                    ce.setTemps(
                            Integer.parseInt(eElement.getElementsByTagName("Time").item(0).getTextContent()));
                    ce.setMsg(eElement.getElementsByTagName("Desc").item(0).getTextContent());
                }
            }
            if (ce != null)
                bilan.add(ce);
        }
        entry = new File(directory, file + ".err");
        if (entry.exists()) {
            doc = builder.parse(entry);
            ce = new CeDefinition();
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("CeHost");
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    ce.setDate(
                            dateFormat.parse(eElement.getElementsByTagName("Start").item(0).getTextContent()));
                    ce.setCe(eElement.getElementsByTagName("Ce").item(0).getTextContent());
                    ce.setPath(eElement.getElementsByTagName("Path").item(0).getTextContent());
                    ce.setState(eElement.getElementsByTagName("Status").item(0).getTextContent());
                    ce.setTemps(
                            Integer.parseInt(eElement.getElementsByTagName("Time").item(0).getTextContent()));
                    ce.setMsg(eElement.getElementsByTagName("Desc").item(0).getTextContent());
                }
            }
            if (ce != null)
                bilan.add(ce);
        }
        entry = new File(directory, file + ".lock");
        ce = new CeDefinition();
        if (entry.exists()) {
            doc = builder.parse(entry);
            ce = new CeDefinition();
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("CeHost");
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    ce.setDate(
                            dateFormat.parse(eElement.getElementsByTagName("Start").item(0).getTextContent()));
                    ce.setCe(eElement.getElementsByTagName("Ce").item(0).getTextContent());
                    ce.setPath(eElement.getElementsByTagName("Path").item(0).getTextContent());
                    ce.setState(eElement.getElementsByTagName("Status").item(0).getTextContent());
                    ce.setTemps(
                            Integer.parseInt(eElement.getElementsByTagName("Time").item(0).getTextContent()));
                    ce.setMsg(eElement.getElementsByTagName("Desc").item(0).getTextContent());
                }
            }
            if (ce != null)
                bilan.add(ce);
        }
    }
    MySQLAccess sql = new MySQLAccess();
    sql.connectDataBase();
    Iterator<CeDefinition> k = bilan.iterator();
    while (k.hasNext()) {
        ce = k.next();
        // System.out.println(ce.getCe() + "\t" + ce.getPath() + "\t" +
        // ce.getDate()
        // + "\t" + ce.getState() + "\t" + ce.getTemps() + "\t" +
        // ce.getMsg()
        // + "\t" + ce.getImplementation());
        sql.writeDataBase(ce, TableSql);
    }
    sql.closeDataBase();
}

From source file:com.clematis.jsmodify.JSExecutionTracer.java

/**
 * This method parses the JSON file containing the trace objects and extracts the objects
 *//*from  w ww  .j  a  v a  2s. co  m*/
public static void extraxtTraceObjects() {
    try {
        ObjectMapper mapper = new ObjectMapper();
        // Register the module that serializes the Guava Multimap
        mapper.registerModule(new GuavaModule());

        Multimap<String, TraceObject> traceMap = mapper.<Multimap<String, TraceObject>>readValue(
                new File("clematis-output/ftrace/function.trace"),
                new TypeReference<TreeMultimap<String, TraceObject>>() {
                });

        Collection<TraceObject> timingTraces = traceMap.get("TimingTrace");
        Collection<TraceObject> domEventTraces = traceMap.get("DOMEventTrace");
        Collection<TraceObject> XHRTraces = traceMap.get("XHRTrace");
        Collection<TraceObject> functionTraces = traceMap.get("FunctionTrace");

        Iterator<TraceObject> it3 = domEventTraces.iterator();
        TraceObject next2;
        ArrayList<TraceObject> removeus = new ArrayList<TraceObject>();
        /**    while (it3.hasNext()) {
        next2 = it3.next();
                
        if (next2 instanceof DOMEventTrace
                && (((DOMEventTrace) next2).getEventType().equals("mouseover") 
                        || (((DOMEventTrace) next2).getEventType().equals("mousemove"))
                        || (((DOMEventTrace) next2).getEventType().equals("mouseout"))
                        || (((DOMEventTrace) next2).getEventType().equals("mousedown"))
                        || (((DOMEventTrace) next2).getEventType().equals("mouseup")))) {
            removeus.add(next2);
                
        }
            }*/
        domEventTraces.removeAll(removeus);

        story = new Story(domEventTraces, functionTraces, timingTraces, XHRTraces);
        story.setOrderedTraceList(sortTraceObjects());

        System.out.println(timingTraces.size());
        Iterator<TraceObject> it = timingTraces.iterator();
        TraceObject next;

        while (it.hasNext()) {
            next = it.next();
            System.out.println("=======");
            System.out.println(next.getCounter());
        }

        /*
         * ArrayList<TraceObject> bookmarkTraceObjects = new ArrayList<TraceObject>(); for
         * (TraceObject to : story.getOrderedTraceList()) { if (to instanceof DOMEventTrace) {
         * if (((DOMEventTrace)to).getEventType().equals("_BOOKMARK_")) {
         * bookmarkTraceObjects.add(to);
         * System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); } } }
         */

        story.setEpisodes(buildEpisodes());

        ArrayList<Episode> ss = story.getEpisodes();
        Iterator<Episode> it2 = ss.iterator();
        System.out.println("hhhmmm");

        while (it2.hasNext()) {
            System.out.println("--------");
            System.out.println(it2.next().getSource().getClass());
        }

        System.out.println("# of trace objects: " + story.getOrderedTraceList().size());
        System.out.println("# of episodes: " + story.getEpisodes().size());
        /*
         * for (int i = 0; i < story.getEpisodes().size(); i ++) { Episode episode =
         * story.getEpisodes().get(i); if (episode.getSource() instanceof DOMEventTrace) {
         * DOMEventTrace source = (DOMEventTrace)episode.getSource();
         * if(source.getTargetElement().contains("bookmarkButton")) {
         * System.out.println("***********"); if (i + 1 < story.getEpisodes().size()) {
         * story.getEpisodes().get(i).getSource().setIsBookmarked(true); // move isbookmarked to
         * episode System.out.println("* " + story.getEpisodes().get(i).getSource().toString());
         * } } } }
         */
        /*
         * for (int i = 0; i < story.getEpisodes().size(); i ++) { Episode episode =
         * story.getEpisodes().get(i); ArrayList<TraceObject> bookmarkObjects = new
         * ArrayList<TraceObject>(); for (int j = 0; j < episode.getTrace().getTrace().size(); j
         * ++) { if (episode.getTrace().getTrace().get(j) instanceof DOMEventTrace) {
         * DOMEventTrace domEventTrace = (DOMEventTrace)episode.getTrace().getTrace().get(j); if
         * (domEventTrace.getEventType().equals("_BOOKMARK_")) {
         * bookmarkObjects.add(domEventTrace); System.out.println("bookmark"); if (i + 1 <
         * story.getEpisodes().size()) { story.getEpisodes().get(i +
         * 1).getSource().setIsBookmarked(true); } } } }
         * episode.getTrace().getTrace().removeAll(bookmarkObjects); } for (Episode e :
         * story.getEpisodes()) { boolean bookmarkNextEpisode = false; // if
         * (e.getSource().getIsBookmarked()) System.out.println("============ " +
         * e.getSource().getIsBookmarked()); for (TraceObject to : e.getTrace().getTrace()) { if
         * (to instanceof DOMEventTrace) { if
         * (((DOMEventTrace)to).getEventType().equals("_BOOKMARK_"))
         * System.out.println("bookmark"); } } }
         */
        /*
         * for (Episode episode : story.getEpisodes()) { if (episode.getSource() instanceof
         * DOMEventTrace) { if
         * (((DOMEventTrace)episode.getSource()).getTargetElement().contains("bookmarkButton"))
         * { System.out.print("**** " + ((DOMEventTrace)episode.getSource()).getEventType() +
         * " * "); } System.out.println("---- " +
         * ((DOMEventTrace)episode.getSource()).getTargetElement()); } }
         */// TODO TODO TODO project specific for photo gallery. eliminate unwanted episodes
        story.removeUselessEpisodes();

        ss = story.getEpisodes();
        it2 = ss.iterator();
        System.out.println("hhhmmm2");

        while (it2.hasNext()) {
            System.out.println("--------");
            System.out.println(it2.next().getSource().getClass());
        }

        ArrayList<Episode> bookmarkEpisodes = new ArrayList<Episode>();

        for (int i = 0; i < story.getEpisodes().size(); i++) {
            Episode episode = story.getEpisodes().get(i);
            if (episode.getSource() instanceof DOMEventTrace) {
                DOMEventTrace source = (DOMEventTrace) episode.getSource();
                if (source.getTargetElement().contains("bookmarkButton")) {
                    bookmarkEpisodes.add(episode);
                    if (i + 1 < story.getEpisodes().size()) {
                        story.getEpisodes().get(i + 1).setIsBookmarked(true);
                        // story.getEpisodes().get(i).getSource().setIsBookmarked(true); // move
                        // isbookmarked to episode
                        System.out.println("* episode # " + (i + 1) + " bookmarked");
                    }
                }
            }

        }

        story.removeUselessEpisodes(bookmarkEpisodes);

        //    story.removeToolbarEpisodes();

        System.out.println("# of episodes after trimming: " + story.getEpisodes().size());

        DateFormat dateFormat = new SimpleDateFormat("EEE,d,MMM,HH-mm");
        Date date = new Date();
        System.out.println(dateFormat.format(date));
        // dateFormat.format(date).toString()
        theTime = new String(dateFormat.format(date).toString());
        System.out.println(theTime);

        // JavaScript episodes for JSUML2
        Helper.directoryCheck(outputFolder + "/sequence_diagrams/");
        PrintStream JSepisodes = new PrintStream(outputFolder + "/sequence_diagrams/allEpisodes.js");

        for (Episode e : story.getEpisodes()) {
            // Create pic files for each episode's sequence diagram
            designSequenceDiagram(e, JSepisodes);
        }

        // Once all episodes have been saved to JS file, close
        JSepisodes.close();

        // Create graph containing all episodes with embedded sequence diagrams
        EpisodeGraph eg = new EpisodeGraph(getOutputFolder(), story.getEpisodes());
        eg.createGraph();
        writeStoryToDisk();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.posterita.businesslogic.performanceanalysis.CustomPOSReportManager.java

public static TabularReport generateTabularReport(Properties ctx, String title, String subtitle, int account_id,
        Timestamp fromDate, Timestamp toDate, String salesGroup, String priceQtyFilter)
        throws OperationException {
    String sql = SalesAnalysisReportManager.getTabularDataSetSQL(ctx, account_id, fromDate, toDate, salesGroup);
    ArrayList<Object[]> tmpData = ReportManager.getReportData(ctx, sql, true);
    String currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol();

    ArrayList<Object[]> reportData = new ArrayList<Object[]>();
    //copying data from tmpData to reportData

    NumberFormat formatter = new DecimalFormat("###,###,##0.00");

    Iterator<Object[]> iter = tmpData.iterator();

    Object[] data = null;// ww  w .  j av a  2s . c  o m
    Object[] headers = null;
    BigDecimal b, c = null;

    boolean isTaxDue = (account_id == Constants.TAX_DUE.intValue());
    boolean isTaxCredit = (account_id == Constants.TAX_CREDIT.intValue());

    if (isTaxCredit || isTaxDue) {
        //copying header
        headers = iter.next();

        reportData.add(new Object[] { headers[0] + "(" + currency + ")", });

        while (iter.hasNext()) {
            data = iter.next();

            if (data.length == 1) {
                b = (BigDecimal) data[0];
                data[0] = formatter.format(b.doubleValue());
            }

            reportData.add(data);
        }
    } else {
        //copying header
        headers = iter.next();

        reportData.add(new Object[] { headers[0], headers[1], headers[2] + "(" + currency + ")", headers[3] });

        double totalAmt = 0.0d;
        BigDecimal totalQty = Env.ZERO;

        while (iter.hasNext()) {
            data = iter.next();

            if (data.length > 2) {
                b = (BigDecimal) data[2];
                c = (BigDecimal) data[3];

                data[2] = formatter.format(b.doubleValue());

                totalAmt += b.doubleValue();
                totalQty = totalQty.add(c);

            }

            reportData.add(data);
        }

        reportData.add(new Object[] { "Total", "", formatter.format(totalAmt) + "", totalQty + "" });

    }

    //style for table
    String tableStyle = "display";
    //style for columns        
    String[] styles = new String[] { "string", "date", "currency", "numeric" };

    if (isTaxCredit || isTaxDue) {
        styles = new String[] { "numeric" };
    }

    //constructing the table
    TabularReport tReport = new TabularReport(reportData);
    //tReport.setSortable(true);
    tReport.setHeaderStyle(styles);
    tReport.setStyle(tableStyle);
    tReport.setTitle(title);
    tReport.setSubtitle(subtitle);
    tReport.createReport();

    return tReport;
}

From source file:fr.inria.oak.paxquery.common.datamodel.metadata.NestedMetadataUtils.java

private static ArrayList append(ArrayList v1, ArrayList v2) {
    ArrayList v3 = new ArrayList();

    Iterator it1 = v1.iterator();
    while (it1.hasNext()) {
        v3.add(it1.next());//from  w w  w .j  av  a2s .  c om
    }
    Iterator it2 = v2.iterator();
    while (it2.hasNext()) {
        v3.add(it2.next());
    }
    return v3;
}

From source file:com.verisignlabs.dnssec.cl.SignZone.java

/**
 * Load keysets (which contain delegation point security info).
 * // w  w  w. j a v a2 s .c  o m
 * @param inDirectory
 *          the directory to look for the keyset files (may be null, in
 *          which
 *          case it defaults to looking in the current working directory).
 * @param zonename
 *          the name of the zone we are signing, so we can ignore keysets
 *          that
 *          do not belong in the zone.
 * @return a list of {@link org.xbill.DNS.Record}s found in the keyset
 *         files.
 */
private static List<Record> getKeysets(File inDirectory, Name zonename) throws IOException {
    if (inDirectory == null) {
        inDirectory = new File(".");
    }

    // get the list of "keyset-" files.
    FileFilter filter = new KeysetFileFilter();
    File[] files = inDirectory.listFiles(filter);

    // read in all of the records
    ArrayList<Record> keysetRecords = new ArrayList<Record>();
    for (int i = 0; i < files.length; i++) {
        List<Record> l = ZoneUtils.readZoneFile(files[i].getAbsolutePath(), zonename);
        keysetRecords.addAll(l);
    }

    // discard records that do not belong to the zone in question.
    for (Iterator<Record> i = keysetRecords.iterator(); i.hasNext();) {
        Record r = i.next();
        if (!r.getName().subdomain(zonename)) {
            i.remove();
        }
    }

    return keysetRecords;
}

From source file:org.posterita.businesslogic.performanceanalysis.CustomPOSReportManager.java

public static TabularReport generateTabularReportGroupByDate(Properties ctx, String title, String subtitle,
        int account_id, Timestamp fromDate, Timestamp toDate, String salesGroup, String priceQtyFilter)
        throws OperationException {
    boolean isTaxDue = (account_id == Constants.TAX_DUE.intValue());
    boolean isTaxCredit = (account_id == Constants.TAX_CREDIT.intValue());

    NumberFormat formatter = new DecimalFormat("###,###,##0.00");

    String sql = SalesAnalysisReportManager.getTabularDataSetSQL(ctx, account_id, fromDate, toDate, salesGroup);
    ArrayList<Object[]> tmpData = ReportManager.getReportData(ctx, sql, true);
    String currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol();

    ArrayList<Object[]> reportData = new ArrayList<Object[]>();
    Object[] data = null;/*from   w ww  .  jav a 2  s .com*/
    BigDecimal b = null;

    if (isTaxCredit || isTaxDue) {
        reportData.add(tmpData.remove(0));
        Iterator<Object[]> iter = tmpData.iterator();

        while (iter.hasNext()) {
            data = iter.next();

            if (data.length == 1) {
                b = (BigDecimal) data[0];
                data[0] = formatter.format(b.doubleValue());
            }

            reportData.add(data);
        }
    } else {
        //----------------------------------------------------------------------------------------------------------------------------------------------------------
        TreeMap<String, TabularReportRecordBean> map = new TreeMap<String, TabularReportRecordBean>();

        String productName = null;
        BigDecimal price = null;
        BigDecimal qty = null;

        TabularReportRecordBean bean = null;

        ArrayList<Object[]> reportData2 = new ArrayList<Object[]>();
        Object[] headers = tmpData.remove(0);

        //adding headers
        reportData2.add(new Object[] { headers[0],
                //headers[1],
                headers[2] + "(" + currency + ")", headers[3] });

        double totalAmt = 0.0d;
        int totalQty = 0;

        for (Object[] record : tmpData) {
            productName = (String) record[0];
            price = (BigDecimal) record[2];
            qty = (BigDecimal) record[3];

            totalAmt += price.doubleValue();
            totalQty += qty.intValue();

            bean = map.get(productName);

            if (bean == null) {
                bean = new TabularReportRecordBean();

                bean.setProductName(productName);
                bean.setDate("");
                bean.setPrice(price);
                bean.setQty(qty);
            } else {
                bean.setPrice(bean.getPrice().add(price));
                bean.setQty(bean.getQty().add(qty));
            }

            map.put(productName, bean);

        } //for 

        Collection<TabularReportRecordBean> c = map.values();

        for (TabularReportRecordBean tbean : c) {
            Object[] obj = new Object[] { tbean.getProductName(), tbean.getPrice(), tbean.getQty() };

            reportData2.add(obj);
        }

        reportData.add(reportData2.remove(0));

        Iterator<Object[]> iter = reportData2.iterator();

        while (iter.hasNext()) {
            data = iter.next();

            if (data.length > 2) {
                b = (BigDecimal) data[1];
                data[1] = formatter.format(b.doubleValue());
            }

            reportData.add(data);
        }

        reportData.add(new Object[] { "Total", "" + formatter.format(totalAmt), totalQty + "" });

    }

    //style for table
    String tableStyle = "display";
    //style for columns        
    String[] styles = new String[] { "string", "currency", "numeric" };

    if (isTaxCredit || isTaxDue) {
        styles = new String[] { "numeric" };
    }

    //constructing the table
    TabularReport tReport = new TabularReport(reportData);
    //tReport.setSortable(true);
    tReport.setHeaderStyle(styles);
    tReport.setStyle(tableStyle);
    tReport.setTitle(title);
    tReport.setSubtitle(subtitle);
    tReport.createReport();

    return tReport;
}

From source file:com.microsoft.tfs.core.clients.build.internal.utils.XamlHelper.java

public static String updateProperties(final String originalXaml, final Properties properties) {
    final ArrayList keys = new ArrayList(properties.keySet());

    final Document document = DOMCreateUtils.parseString(originalXaml);
    final Element root = document.getDocumentElement();

    // first update any properties that we already have
    final NodeList nodes = root.getElementsByTagName("x:String"); //$NON-NLS-1$
    for (int i = 0; i < nodes.getLength(); i++) {
        final Element element = (Element) nodes.item(i);
        final String key = element.getAttribute("x:Key"); //$NON-NLS-1$
        element.getFirstChild().getNodeValue();

        if (properties.containsKey(key)) {
            keys.remove(key);//  w  w  w.  j  a  va  2s .c  om
            element.getFirstChild().setNodeValue(properties.getProperty(key));
        }
    }

    // now add any new properties to the xaml
    for (final Iterator it = keys.iterator(); it.hasNext();) {
        final String key = (String) it.next();
        final Element element = DOMUtils.appendChild(root, "x:String"); //$NON-NLS-1$
        element.setAttributeNS(XAML_NAMESPACE, "x:Key", key); //$NON-NLS-1$
        element.setAttributeNS(XML_NAMESPACE, "xml:space", "preserve"); //$NON-NLS-1$ //$NON-NLS-2$
        DOMUtils.appendText(element, properties.getProperty(key));
    }

    return DOMSerializeUtils.toString(root, DOMSerializeUtils.INDENT).trim();
}

From source file:edu.jhuapl.bsp.detector.OpenMath.java

public static double percentile(double[] x, double p) {
    ArrayList<Double> intermediate = new ArrayList<Double>(x.length);
    for (int i = 0; i < x.length; i++) {
        if (!Double.isInfinite(x[i]) && !Double.isNaN(x[i])) {
            intermediate.add(x[i]);/*from www . j  av a 2s. c om*/
        }
    }
    Iterator<Double> iter = intermediate.iterator();
    double[] xcopy = new double[intermediate.size()];
    int index = 0;
    while (iter.hasNext()) {
        xcopy[index] = iter.next();
        index++;
    }
    Arrays.sort(xcopy);
    double minprctile = 100 * ((.5) / xcopy.length), maxprctile = 100 * ((xcopy.length - .5) / xcopy.length);
    if (p >= maxprctile) {
        return xcopy[xcopy.length - 1];
    } else if (p <= minprctile) {
        return xcopy[0];
    }
    double[] xprctile = new double[xcopy.length];
    for (int i = 0; i < xprctile.length; i++) {
        xprctile[i] = 100 * (((xprctile.length - (xprctile.length - i - 1)) - .5) / xprctile.length);
    }
    LinearInterpolation LI = new LinearInterpolation(xprctile, xcopy);
    return LI.interpolatedValue(p);
}

From source file:com.ms.commons.file.service.ImageUtil.java

/**
 * //  w  ww.j a  va2s  .  c  om
 */
public static Map<String, Integer> getImageWH(String imageFilePath) {
    // create operation
    IMOperation op = new IMOperation();
    op.ping();
    // op.format("%m\n%w\n%h\n%g\n%W\n%H\n%G\n%z\n%r\n%Q");
    op.format("%w\n%h");
    op.addImage(imageFilePath);

    try {
        // execute ...
        IdentifyCmd identify = new IdentifyCmd();
        ArrayListOutputConsumer output = new ArrayListOutputConsumer();
        identify.setOutputConsumer(output);
        identify.run(op);

        // ... and parse result
        ArrayList<String> cmdOutput = output.getOutput();
        Iterator<String> iter = cmdOutput.iterator();
        Map<String, Integer> map = new Hashtable<String, Integer>();

        map.put(IMAGE_WIDTH, parseInt(iter.next()));
        map.put(IMAGE_HEIGHT, parseInt(iter.next()));
        return map;
    } catch (Exception ex) {
        return Collections.emptyMap();
    }
}

From source file:com.ms.commons.file.service.ImageUtil.java

/**
 * ?:?,?// ww  w.j a v a  2  s. c  om
 * 
 * <pre>
 *    %b   file size of image read in
 *    %c   comment property
 *    %d   directory component of path
 *    %e   filename extension or suffix
 *    %f   filename (including suffix)
 *    %g   layer canvas page geometry   ( = %Wx%H%X%Y )
 *    %h   current image height in pixels
 *    %i   image filename (note: becomes output filename for "info:")
 *    %k   number of unique colors
 *    %l   label property
 *    %m   image file format (file magic)
 *    %n   exact number of images in current image sequence
 *    %o   output filename  (used for delegates)
 *    %p   index of image in current image list
 *    %q   quantum depth (compile-time constant)
 *    %r   image class and colorspace
 *    %s   scene number (from input unless re-assigned)
 *    %t   filename without directory or extension (suffix)
 *    %u   unique temporary filename (used for delegates)
 *    %w   current width in pixels
 *    %x   x resolution (density)
 *    %y   y resolution (density)
 *    %z   image depth (as read in unless modified, image save depth)
 *    %A   image transparency channel enabled (true/false)
 *    %C   image compression type
 *    %D   image dispose method
 *    %G   image size ( = %wx%h )
 *    %H   page (canvas) height
 *    %M   Magick filename (original file exactly as given,  including read mods)
 *    %O   page (canvas) offset ( = %X%Y )
 *    %P   page (canvas) size ( = %Wx%H )
 *    %Q   image compression quality ( 0 = default )
 *    %S   ?? scenes ??
 *    %T   image time delay
 *    %W   page (canvas) width
 *    %X   page (canvas) x offset (including sign)
 *    %Y   page (canvas) y offset (including sign)
 *    %Z   unique filename (used for delegates)
 *    %@   bounding box
 *    %#   signature
 *    %%   a percent sign
 *    \n   newline
 *    \r   carriage return
 * </pre>
 * 
 * @param imageFilePath 
 * @return Map?,Map
 */
public static Map<String, String> getImageBasicInfo(String imageFilePath) {
    // create operation
    IMOperation op = new IMOperation();
    op.ping();
    // op.format("%m\n%w\n%h\n%g\n%W\n%H\n%G\n%z\n%r\n%Q");
    op.format("%m\n%w\n%h\n%Q");
    op.addImage(imageFilePath);

    try {
        // execute ...
        IdentifyCmd identify = new IdentifyCmd();
        ArrayListOutputConsumer output = new ArrayListOutputConsumer();
        identify.setOutputConsumer(output);
        identify.run(op);

        // ... and parse result
        ArrayList<String> cmdOutput = output.getOutput();
        Iterator<String> iter = cmdOutput.iterator();
        Map<String, String> map = new Hashtable<String, String>();
        map.put(IMAGE_FORMAT, iter.next());
        map.put(IMAGE_WIDTH, iter.next());
        map.put(IMAGE_HEIGHT, iter.next());
        map.put(IMAGE_QUALITY, iter.next());
        return map;
    } catch (Exception ex) {
        return Collections.emptyMap();
    }
}