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:de.uni_hannover.dcsec.siafu.model.World.java

/**
 * Creates a place for each black pixel in the images contained in the
 * simulation data. The place type is the name of the image.
 * //from   ww  w. j  a  v a 2 s  . c o  m
 * @return a list of places generated from the images in the simulation
 *         data.
 */
protected ArrayList<Place> createPlacesFromImages() {
    Place.initialize(this);
    ArrayList<Place> placesFromImg = new ArrayList<Place>();
    Map<String, InputStream> fileList = simData.getPlaceFiles();
    Iterator<String> listIt = fileList.keySet().iterator();

    int total = 0;

    while (listIt.hasNext()) {
        String type = (String) listIt.next();
        ArrayList<Position> placePoints = readPlacePoints(fileList.get(type));
        Iterator<Position> it = placePoints.iterator();
        total += placePoints.size();
        Controller.getProgress().reportPlacesFound(type, placePoints.size());

        while (it.hasNext()) {
            Position pos = (Position) it.next();
            Place place;
            try {
                place = new Place(type, pos, this, type + "-" + getFloorFor(pos).getLevel() + "-" + pos, null);
            } catch (PositionOnAWallException e) {
                throw new RuntimeException("One of your \"" + type + "\" places, at " + pos + " is on a wall");
            }
            Controller.getProgress().reportPlaceCreated(type);
            placesFromImg.add(place);
        }
    }

    return placesFromImg;
}

From source file:logdruid.util.DataMiner.java

public static FileMineResult fileMine(FileRecord fileRecord, Repository repo, Source source, boolean stats,
        boolean timings) {
    ExtendedTimeSeries ts = null;//ww  w .  j a v a2 s .c om
    PatternCache patternCache = new PatternCache();
    Date startDate = null;
    Date endDate = null;

    DecimalFormat decimalFormat = new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.US));

    FastDateFormat fastDateFormat = null;
    FileReader flstr = null;
    BufferedReader buf1st;
    Matcher matcher;
    Matcher matcher2;
    FixedMillisecond fMS = null;
    Boolean successMatch = false;
    DateFormat df = null;
    int statHit = 0;
    int statMatch = 0;
    int eventHit = 0;
    int eventMatch = 0;
    long[] arrayBefore;
    Map<Recording, String> recMatch = new HashMap<Recording, String>();
    Map<String, ExtendedTimeSeries> statMap = new HashMap<String, ExtendedTimeSeries>();
    Map<String, ExtendedTimeSeries> eventMap = new HashMap<String, ExtendedTimeSeries>();
    Map<String, Map<Date, FileLine>> RIFileLineDateMap = new HashMap<String, Map<Date, FileLine>>();
    Map<String, long[]> matchTimings = new HashMap<String, long[]>();

    long recordingMatchStart = 0;
    long recordingMatchEnd = 0;
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("++file: " + repo.getBaseSourcePath() + " + "
                    + (String) fileRecord.getCompletePath().toString());
        }
        flstr = new FileReader(fileRecord.getCompletePath());
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    buf1st = new BufferedReader(flstr);
    String line;
    try {
        recMatch = getRegexp(repo, source);
        int lineCount = 1;
        while ((line = buf1st.readLine()) != null) {
            // check against one Recording pattern at a tim
            // if (logger.isDebugEnabled()) {
            // logger.debug("line " + line);
            // }
            Iterator recMatchIte = recMatch.entrySet().iterator();
            while (recMatchIte.hasNext()) {
                if (timings) {
                    recordingMatchStart = ManagementFactory.getThreadMXBean()
                            .getThreadCpuTime(Thread.currentThread().getId());
                }
                Map.Entry me = (Map.Entry) recMatchIte.next();
                Recording rec = (Recording) me.getKey();
                matcher = patternCache.getPattern((String) (rec.getRegexp())).matcher(line);
                if (matcher.find()) {
                    Boolean isStatRecording = rec.getClass().equals(StatRecording.class);
                    if (stats) {
                        if (isStatRecording) {
                            statMatch++;
                        } else {
                            eventMatch++;
                        }
                    }
                    // logger.info("1**** matched: " + line);
                    ArrayList<RecordingItem> recordingItem = ((Recording) rec).getRecordingItem();
                    int cnt = 0;
                    matcher2 = patternCache.getPattern((String) me.getValue()).matcher(line);
                    successMatch = false;
                    if (matcher2.find()) {
                        if (stats) {
                            if (isStatRecording) {
                                statHit++;
                            } else {
                                eventHit++;
                            }
                        }
                        int count = 1;
                        Date date1 = null;

                        // handling capture for each recording item
                        Iterator<RecordingItem> recItemIte2 = recordingItem.iterator();
                        while (recItemIte2.hasNext()) {
                            RecordingItem recItem2 = recItemIte2.next();
                            // logger.info("3A**** " +
                            // recItem2.getType());
                            if (recItem2.getType().equals("date")) {
                                try {
                                    df = repo.getDateFormat(rec.getDateFormatID());
                                    if (logger.isDebugEnabled())
                                        logger.debug("4**** rec name" + rec.getName() + " df: " + df.getId());
                                    fastDateFormat = FastDateFormat.getInstance(df.getDateFormat());
                                    date1 = fastDateFormat.parse(matcher2.group(count));
                                    if (logger.isDebugEnabled())
                                        logger.debug(
                                                "4b**** " + df.getDateFormat() + " date: " + date1.toString());
                                    // logger.info("4**** " +
                                    // date1.toString());
                                } catch (ParseException e) {
                                    // TODO Auto-generated catch
                                    // block
                                    e.printStackTrace();
                                }
                            } else if (date1 != null) {
                                if (recItem2.isSelected()) {
                                    if (logger.isDebugEnabled()) {
                                        logger.debug("FileRecord: " + fileRecord.getFile().getName()
                                                + ", Source: " + source.getSourceName() + ", "
                                                + recItem2.getName() + ", " + fileRecord.getFile().getName()
                                                + ", " + lineCount);
                                    }
                                    // recording line of match in file in map RIFileLineDateMap - note the FileLine object use an int to identify the files to save memory 
                                    Map<Date, FileLine> dateFileLineMap = null;
                                    if (RIFileLineDateMap.containsKey(recItem2.getName())) {
                                        dateFileLineMap = RIFileLineDateMap.get(recItem2.getName());
                                    } else {
                                        dateFileLineMap = new HashMap<Date, FileLine>();
                                    }
                                    dateFileLineMap.put(date1, new FileLine(fileRecord.getId(), lineCount));
                                    if (logger.isDebugEnabled()) {
                                        logger.debug(fileRecord.getFile().getName() + " dateFileLineMap put: "
                                                + date1 + "fileLine: "
                                                + new FileLine(fileRecord.getId(), lineCount));
                                        logger.debug(fileRecord.getFile().getName() + " FileRecord: "
                                                + fileRecord.getFile().getName() + ", RIFileLineDateMap.put: "
                                                + recItem2.getName() + ", line: " + lineCount
                                                + " RIFileLineDateMap size: " + RIFileLineDateMap.size()
                                                + " dateFileLineMap size: " + dateFileLineMap.size());
                                    }
                                    RIFileLineDateMap.put(recItem2.getName(), dateFileLineMap);

                                    if (startDate == null) {
                                        startDate = date1;
                                    }
                                    if (endDate == null) {
                                        endDate = date1;
                                    }
                                    if (date1.after(startDate)) {
                                        endDate = date1;
                                    } else if (date1.before(startDate)) {
                                        startDate = date1;
                                    }

                                    if (isStatRecording) {
                                        if (statMap.containsKey(recItem2.getName())) {
                                            ts = statMap.get(recItem2.getName());
                                        } else {
                                            ts = new ExtendedTimeSeries(recItem2.getName(),
                                                    FixedMillisecond.class);
                                            if (logger.isDebugEnabled())
                                                logger.debug(
                                                        "5**** Adding record to Map: " + recItem2.getName());
                                        }
                                        fMS = new FixedMillisecond(date1);
                                        if (matcher2.group(count) == null) {
                                            logger.info("null in match on " + recItem2.getName() + " at "
                                                    + fileRecord.getFile().getName() + " line cnt:"
                                                    + lineCount);
                                            logger.info("line : " + line);
                                        }
                                        try {

                                            if (recItem2.getType().equals("long")) {
                                                ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(fMS,
                                                        Long.valueOf((String) matcher2.group(count)))));
                                            } else {
                                                ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(fMS,
                                                        Double.parseDouble(String.valueOf(decimalFormat
                                                                .parse((String) matcher2.group(count)))))));
                                            }
                                        } catch (ParseException e) {
                                            // TODO Auto-generated catch
                                            // block
                                            e.printStackTrace();
                                        }
                                        if (stats) {
                                            //int[] array = { statMatch, statHit };
                                            int[] array = ts.getStat();
                                            array[1] = array[1] + 1;
                                            array[0] = array[0] + 1;
                                            ts.setStat(array);
                                            if (logger.isDebugEnabled())
                                                logger.debug("stats " + array[0] + " " + array[1]);
                                        }

                                        statMap.put(recItem2.getName(), ts);
                                        // performance: add the
                                        // TmeSeriesDataItem to the
                                        // TimeSeries instead of updating
                                        // the TimeSeries in the Map

                                    } else { // rec.getClass().equals(EventRecording.class)
                                        if (eventMap.containsKey(recItem2.getName())) {
                                            ts = eventMap.get(recItem2.getName());
                                        } else {
                                            ts = new ExtendedTimeSeries(recItem2.getName(),
                                                    FixedMillisecond.class);
                                            if (logger.isDebugEnabled())
                                                logger.debug(
                                                        "5**** Adding record to Map: " + recItem2.getName());
                                        }
                                        fMS = new FixedMillisecond(date1);

                                        if (((RecordingItem) recItem2).getProcessingType()
                                                .equals("occurrences")) {
                                            TimeSeriesDataItem t = ts.getTimeSeries().getDataItem(fMS);
                                            if (t != null) {
                                                ts.getTimeSeries()
                                                        .addOrUpdate((new TimeSeriesDataItem(fMS, 101))); // +
                                                // (double)t.getValue()
                                                // need some way to show several occurrences
                                            } else {
                                                ts.getTimeSeries().add((new TimeSeriesDataItem(fMS, 100)));
                                            }

                                        } else if (((RecordingItem) recItem2).getProcessingType()
                                                .equals("sum")) {
                                            TimeSeriesDataItem t = ts.getTimeSeries().getDataItem(fMS);
                                            if (t != null) {
                                                if (!recItem2.getType().equals("date")) {
                                                    try {
                                                        ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(
                                                                fMS,
                                                                Double.parseDouble(String
                                                                        .valueOf(decimalFormat
                                                                                .parse(matcher2.group(count)))
                                                                        + ts.getTimeSeries().getDataItem(fMS)
                                                                                .getValue()))));
                                                        logger.info(
                                                                ts.getTimeSeries().getDataItem(fMS).getValue());
                                                    } catch (ParseException e) {
                                                        // TODO
                                                        // Auto-generated
                                                        // catch block
                                                        e.printStackTrace();
                                                    }
                                                }
                                            } else {
                                                try {
                                                    ts.getTimeSeries()
                                                            .add((new TimeSeriesDataItem(fMS, Double
                                                                    .parseDouble(String.valueOf(decimalFormat
                                                                            .parse(matcher2.group(count)))))));
                                                } catch (ParseException e) {
                                                    // TODO Auto-generated
                                                    // catch block
                                                    e.printStackTrace();
                                                }
                                            }

                                        } else if (((RecordingItem) recItem2).getProcessingType()
                                                .equals("capture")) {

                                        } else {
                                            if (!recItem2.getType().equals("date")) {
                                                try {
                                                    ts.getTimeSeries()
                                                            .addOrUpdate((new TimeSeriesDataItem(fMS, Double
                                                                    .parseDouble(String.valueOf(decimalFormat
                                                                            .parse(matcher2.group(count)))))));
                                                } catch (ParseException e) {
                                                    // TODO Auto-generated
                                                    // catch block
                                                    e.printStackTrace();
                                                }
                                            }
                                            // ts.addOrUpdate((new
                                            // TimeSeriesDataItem(fMS,
                                            // 100)));
                                        }
                                        // logger.debug(recItem2.getName() +
                                        // " " +
                                        // Double.parseDouble((matcher2.group(count))));
                                        if (stats) {
                                            int[] array = ts.getStat();
                                            array[1] = array[1] + 1;
                                            array[0] = array[0] + 1;
                                            ts.setStat(array);
                                            if (logger.isDebugEnabled())
                                                logger.debug("stats " + array[0] + " " + array[1]);
                                        }
                                        eventMap.put(recItem2.getName(), ts);

                                    }
                                }
                            }
                            count++;
                            // logger.info("event statistics: "+eventMatch +
                            // " and " +eventHit +
                            // " ; stat statistics: "+statMatch + " and "
                            // +statHit);
                        }
                    }
                    if (timings) {
                        recordingMatchEnd = ManagementFactory.getThreadMXBean()
                                .getThreadCpuTime(Thread.currentThread().getId());
                        if (matchTimings.containsKey(rec.getName())) {
                            arrayBefore = matchTimings.get(rec.getName());
                            // logger.info(file.getName() + " contains " +
                            // arrayBefore);
                            // 0-> sum of time for success matching of given
                            // recording ; 1-> sum of time for failed
                            // matching ; 2-> count of match attempts,
                            // 3->count of success attempts

                            long[] array = { arrayBefore[0] + recordingMatchEnd - recordingMatchStart,
                                    arrayBefore[1], arrayBefore[2] + 1, arrayBefore[3] + 1 };
                            // logger.info(file.getName() +
                            // " add success to" + rec.getName() + " 0: "+
                            // array[0] + " 1: "+ array[1]+ " 2: "+ array[2]
                            // +" 3: "+ array[3]);
                            matchTimings.put(rec.getName(), array);
                        } else {
                            long[] array = { recordingMatchEnd - recordingMatchStart, 0, 1, 1 };
                            matchTimings.put(rec.getName(), array);
                            // logger.info(file.getName() + " first success"
                            // + rec.getName() + " 0: "+ array[0] + " 1: "+
                            // array[1]+ " 2: "+ array[2] +" 3: "+
                            // array[3]);
                        }
                    }
                } else {
                    if (timings) {
                        recordingMatchEnd = ManagementFactory.getThreadMXBean()
                                .getThreadCpuTime(Thread.currentThread().getId());
                        if (matchTimings.containsKey(rec.getName())) {
                            arrayBefore = matchTimings.get(rec.getName());
                            // 0-> sum of time for success matching of given
                            // recording ; 1-> sum of time for failed
                            // matching ; 2-> count of match attempts,
                            // 3->count of success attempts
                            long[] array = { arrayBefore[0],
                                    arrayBefore[1] + recordingMatchEnd - recordingMatchStart,
                                    arrayBefore[2] + 1, arrayBefore[3] };
                            matchTimings.put(rec.getName(), array);
                        } else {
                            long[] array = { 0, recordingMatchEnd - recordingMatchStart, 1, 0 };
                            matchTimings.put(rec.getName(), array);
                        }
                    }
                }

            }
            lineCount++;

            // timing
        }
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            buf1st.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /*
     * if (logger.isInfoEnabled()) { Iterator Ite =
     * matchTimings.entrySet().iterator(); long successTotalTime=0; long
     * failedTotalTime=0; // 0-> sum of time for success matching of given
     * // recording ; 1-> sum of time for failed // matching ; 2-> count of
     * match attempts, // 3->count of success attempts // long[] array;
     * while (Ite.hasNext()) { Map.Entry pairs = (Map.Entry) Ite.next();
     * long[] array = (long[]) pairs.getValue(); logger.info(file.getName()
     * + " - "+ pairs.getKey() + " / success all time: " + array[0] +
     * " failed all time: " + array[1] + " attempt count: " + array[2] +
     * " success count: " + array[3] + " failed count:"
     * +(array[2]-array[3])); successTotalTime=successTotalTime+array[0];
     * failedTotalTime=failedTotalTime+array[1]; } logger.info("success: "
     * +successTotalTime + " failed: " + failedTotalTime); Ite =
     * matchTimings.entrySet().iterator(); while (Ite.hasNext()) { Map.Entry
     * pairs = (Map.Entry) Ite.next(); long[] array = (long[])
     * pairs.getValue(); logger.info(file.getName() + " percents - "+
     * pairs.getKey() + " / % success time: " + (( successTotalTime!=0) ?
     * ((double)((double)array[0] / successTotalTime)*100) : 0 ) +
     * " % failed time: " + (( failedTotalTime!=0) ?((double)array[1]/
     * failedTotalTime)*100 :0) + " attempt cost: " + ((array[2]!=0) ?
     * ((double)successTotalTime + failedTotalTime ) /array[2]:0 )+
     * " success cost: " + ((array[3]!=0) ? ((double)successTotalTime )
     * /array[3] : 0) + " failed cost:" + ((array[2]-array[3]!=0) ?
     * ((double)failedTotalTime/(array[2]-array[3])) : 0) ); } }
     */
    return new FileMineResult(fileRecord, statMap, eventMap, matchTimings, RIFileLineDateMap, startDate,
            endDate);
}

From source file:logdruid.ui.chart.GraphPanel.java

public void load(JPanel panel_2) {
    startDateJSpinner = (JSpinner) panel_2.getComponent(2);
    endDateJSPinner = (JSpinner) panel_2.getComponent(3);
    // scrollPane.setV
    panel.removeAll();//from ww w .j  a  v  a 2  s .  com
    Dimension panelSize = this.getSize();
    add(scrollPane, BorderLayout.CENTER);
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    // scrollPane.set trying to replace scroll where it was
    JCheckBox relativeCheckBox = (JCheckBox) panel_2.getComponent(5);
    estimatedTime = System.currentTimeMillis() - startTime;
    logger.info("gathering time: " + estimatedTime);
    startTime = System.currentTimeMillis();
    //   Map<Source, Map<String, MineResult>>
    Map<Source, Map<String, MineResult>> treeMap = new TreeMap<Source, Map<String, MineResult>>(
            mineResultSet.mineResults);
    Iterator mineResultSetIterator = treeMap.entrySet().iterator();
    int ite = 0;
    logger.debug("mineResultSet size: " + mineResultSet.mineResults.size());
    while (mineResultSetIterator.hasNext()) {
        final Map.Entry pairs = (Map.Entry) mineResultSetIterator.next();
        logger.debug("mineResultSet key/source: " + ((Source) pairs.getKey()).getSourceName());
        JCheckBox checkBox = (JCheckBox) panel_1.getComponent(ite++);
        logger.debug("checkbox: " + checkBox.getText() + ", " + checkBox.isSelected());
        if (checkBox.isSelected()) {

            Map mrArrayList = (Map<String, MineResult>) pairs.getValue();
            ArrayList<String> mineResultGroup = new ArrayList<String>();
            Set<String> mrss = mrArrayList.keySet();

            mineResultGroup.addAll(mrss);
            Collections.sort(mineResultGroup, new AlphanumComparator());
            Iterator mrArrayListIterator = mineResultGroup.iterator();
            while (mrArrayListIterator.hasNext()) {

                String key = (String) mrArrayListIterator.next();
                logger.debug(key);
                final MineResult mr = (MineResult) mrArrayList.get(key);
                Map<String, ExtendedTimeSeries> statMap = mr.getStatTimeseriesMap();
                Map<String, ExtendedTimeSeries> eventMap = mr.getEventTimeseriesMap();
                // logger.info("mineResultSet hash size: "
                // +mr.getTimeseriesMap().size());
                // logger.info("mineResultSet hash content: " +
                // mr.getStatTimeseriesMap());
                logger.debug("mineResultSet mr.getStartDate(): " + mr.getStartDate()
                        + " mineResultSet mr.getEndDate(): " + mr.getEndDate());
                logger.debug("mineResultSet (Date)jsp.getValue(): " + (Date) startDateJSpinner.getValue());
                logger.debug("mineResultSet (Date)jsp2.getValue(): " + (Date) endDateJSPinner.getValue());
                if (mr.getStartDate() != null && mr.getEndDate() != null) {
                    if ((mr.getStartDate().before((Date) endDateJSPinner.getValue()))
                            && (mr.getEndDate().after((Date) startDateJSpinner.getValue()))) {

                        ArrayList<String> mineResultGroup2 = new ArrayList<String>();
                        Set<String> mrss2 = statMap.keySet();
                        mineResultGroup2.addAll(mrss2);
                        Collections.sort(mineResultGroup2, new AlphanumComparator());
                        Iterator statMapIterator = mineResultGroup2.iterator();

                        //            Iterator statMapIterator = statMap.entrySet().iterator();
                        if (!statMap.entrySet().isEmpty() || !eventMap.entrySet().isEmpty()) {
                            JPanel checkboxPanel = new JPanel(new WrapLayout());

                            checkboxPanel.setBackground(Color.white);

                            int count = 1;
                            chart = ChartFactory.createXYAreaChart(// Title
                                    mr.getSourceID() + " " + mr.getGroup(), // +
                                    null, // X-Axis
                                    // label
                                    null, // Y-Axis label
                                    null, // Dataset
                                    PlotOrientation.VERTICAL, false, // Show
                                    // legend
                                    true, // tooltips
                                    false // url
                            );
                            TextTitle my_Chart_title = new TextTitle(mr.getSourceID() + " " + mr.getGroup(),
                                    new Font("Verdana", Font.BOLD, 17));
                            chart.setTitle(my_Chart_title);
                            XYPlot plot = (XYPlot) chart.getPlot();
                            ValueAxis range = plot.getRangeAxis();
                            range.setVisible(false);

                            final DateAxis domainAxis1 = new DateAxis();
                            domainAxis1.setTickLabelsVisible(true);
                            // domainAxis1.setTickMarksVisible(true);

                            logger.debug("getRange: " + domainAxis1.getRange());
                            if (relativeCheckBox.isSelected()) {
                                domainAxis1.setRange((Date) startDateJSpinner.getValue(),
                                        (Date) endDateJSPinner.getValue());
                            } else {
                                Date startDate = mr.getStartDate();
                                Date endDate = mr.getEndDate();
                                if (mr.getStartDate().before((Date) startDateJSpinner.getValue())) {
                                    startDate = (Date) startDateJSpinner.getValue();
                                    logger.debug("setMinimumDate: " + (Date) startDateJSpinner.getValue());
                                }
                                if (mr.getEndDate().after((Date) endDateJSPinner.getValue())) {
                                    endDate = (Date) endDateJSPinner.getValue();
                                    logger.debug("setMaximumDate: " + (Date) endDateJSPinner.getValue());
                                }
                                if (startDate.before(endDate)) {
                                    domainAxis1.setRange(startDate, endDate);
                                }
                            }
                            XYToolTipGenerator tt1 = new XYToolTipGenerator() {
                                public String generateToolTip(XYDataset dataset, int series, int item) {
                                    StringBuffer sb = new StringBuffer();
                                    String htmlStr = "<html>";
                                    Number x;
                                    FastDateFormat sdf = FastDateFormat.getInstance("dd-MMM-yyyy HH:mm:ss");
                                    x = dataset.getX(series, item);
                                    sb.append(htmlStr);
                                    if (x != null) {
                                        sb.append("<p style='color:#000000;'>" + (sdf.format(x)) + "</p>");
                                        sb.append("<p style='color:#000000;'>"
                                                + dataset.getSeriesKey(series).toString() + ": "
                                                + form.format(dataset.getYValue(0, item)) + "</p>");
                                        if (mr.getFileLineForDate(new Date(x.longValue()),
                                                dataset.getSeriesKey(series).toString()) != null) {
                                            sb.append(
                                                    "<p style='color:#0000FF;'>"
                                                            + cd.sourceFileArrayListMap
                                                                    .get(pairs.getKey()).get(mr
                                                                            .getFileLineForDate(
                                                                                    new Date(x.longValue()),
                                                                                    dataset.getSeriesKey(series)
                                                                                            .toString())
                                                                            .getFileId())
                                                                    .getFile().getName()
                                                            + ":"
                                                            + mr.getFileLineForDate(new Date(x.longValue()),
                                                                    dataset.getSeriesKey(series).toString())
                                                                    .getLineNumber()
                                                            + "</p>");

                                        }
                                    }
                                    return sb.toString();
                                }
                            };

                            while (statMapIterator.hasNext()) {

                                TimeSeriesCollection dataset = new TimeSeriesCollection();
                                String me = (String) statMapIterator.next();

                                ExtendedTimeSeries ts = (ExtendedTimeSeries) statMap.get(me);
                                // logger.info(((TimeSeries)
                                // me.getValue()).getMaxY());
                                if (((ExtendedTimeSeries) statMap.get(me)).getTimeSeries().getMaxY() > 0)
                                    dataset.addSeries(ts.getTimeSeries());
                                logger.debug("mineResultSet group: " + mr.getGroup() + ", key: " + me
                                        + " nb records: " + ((ExtendedTimeSeries) statMap.get(me))
                                                .getTimeSeries().getItemCount());
                                logger.debug("(((TimeSeries) me.getValue()).getMaxY(): "
                                        + (((ExtendedTimeSeries) statMap.get(me)).getTimeSeries().getMaxY()));
                                logger.debug("(((TimeSeries) me.getValue()).getMinY(): "
                                        + (((ExtendedTimeSeries) statMap.get(me)).getTimeSeries().getMinY()));
                                XYPlot plot1 = chart.getXYPlot();
                                //   LogarithmicAxis axis4 = new LogarithmicAxis(me.toString());
                                NumberAxis axis4 = new NumberAxis(me.toString());
                                axis4.setAutoRange(true);
                                axis4.setAxisLineVisible(true);
                                axis4.setAutoRangeIncludesZero(false);
                                plot1.setDomainCrosshairVisible(true);
                                plot1.setRangeCrosshairVisible(true);
                                axis4.setRange(new Range(
                                        ((ExtendedTimeSeries) statMap.get(me)).getTimeSeries().getMinY(),
                                        ((ExtendedTimeSeries) statMap.get(me)).getTimeSeries().getMaxY()));
                                axis4.setLabelPaint(colors[count]);
                                axis4.setTickLabelPaint(colors[count]);
                                plot1.setRangeAxis(count, axis4);
                                final ValueAxis domainAxis = domainAxis1;
                                domainAxis.setLowerMargin(0.0);
                                domainAxis.setUpperMargin(0.0);
                                plot1.setDomainAxis(domainAxis);
                                plot1.setForegroundAlpha(0.5f);
                                plot1.setDataset(count, dataset);
                                plot1.mapDatasetToRangeAxis(count, count);
                                final XYAreaRenderer renderer = new XYAreaRenderer(); // XYAreaRenderer2
                                // also
                                // nice
                                if ((((ExtendedTimeSeries) statMap.get(me)).getTimeSeries().getMaxY()
                                        - ((ExtendedTimeSeries) statMap.get(me)).getTimeSeries()
                                                .getMinY()) > 0) {

                                    // renderer.setToolTipGenerator(new
                                    // StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,new
                                    // FastDateFormat("d-MMM-yyyy HH:mm:ss"),
                                    // new DecimalFormat("#,##0.00")));
                                }
                                renderer.setSeriesPaint(0, colors[count]);
                                renderer.setSeriesVisible(0, true);
                                renderer.setSeriesToolTipGenerator(0, tt1);
                                plot1.setRenderer(count, renderer);
                                int hits = 0; // ts.getStat()[1]
                                int matchs = 0;
                                if (((ExtendedTimeSeries) statMap.get(me)).getStat() != null) {
                                    hits = ((ExtendedTimeSeries) statMap.get(me)).getStat()[1];
                                    //   matchs= ((ExtendedTimeSeries) statMap.get(me)).getStat()[0];
                                }
                                JCheckBox jcb = new JCheckBox(new VisibleAction(panel, checkboxPanel, axis4,
                                        me.toString() + "(" + hits + ")", 0));
                                Boolean selected = true;
                                jcb.setSelected(true);
                                jcb.setBackground(Color.white);
                                jcb.setBorderPainted(true);
                                jcb.setBorder(BorderFactory.createLineBorder(colors[count], 1, true));
                                jcb.setFont(new Font("Sans-serif", oldSmallFont.getStyle(),
                                        oldSmallFont.getSize()));
                                checkboxPanel.add(jcb);
                                count++;
                            }
                            Iterator eventMapIterator = eventMap.entrySet().iterator();
                            while (eventMapIterator.hasNext()) {

                                //   HistogramDataset histoDataSet=new HistogramDataset();

                                TimeSeriesCollection dataset = new TimeSeriesCollection();
                                Map.Entry me = (Map.Entry) eventMapIterator.next();
                                // if (dataset.getEndXValue(series, item))
                                if (((ExtendedTimeSeries) me.getValue()).getTimeSeries().getMaxY() > 0)
                                    dataset.addSeries(((ExtendedTimeSeries) me.getValue()).getTimeSeries());

                                logger.debug("mineResultSet group: " + mr.getGroup() + ", key: " + me.getKey()
                                        + " nb records: "
                                        + ((ExtendedTimeSeries) me.getValue()).getTimeSeries().getItemCount());
                                logger.debug("mineResultSet hash content: " + mr.getEventTimeseriesMap());
                                logger.debug("(((TimeSeries) me.getValue()).getMaxY(): "
                                        + (((ExtendedTimeSeries) me.getValue()).getTimeSeries().getMaxY()));
                                logger.debug("(((TimeSeries) me.getValue()).getMinY(): "
                                        + (((ExtendedTimeSeries) me.getValue()).getTimeSeries().getMinY()));
                                XYPlot plot2 = chart.getXYPlot();
                                //   LogarithmicAxis axis4 = new LogarithmicAxis(me.toString());
                                NumberAxis axis4 = new NumberAxis(me.getKey().toString());
                                axis4.setAutoRange(true);
                                // axis4.setInverted(true);
                                axis4.setAxisLineVisible(true);
                                axis4.setAutoRangeIncludesZero(true);

                                // axis4.setRange(new Range(((TimeSeries)
                                // axis4.setRange(new Range(((TimeSeries)
                                // me.getValue()).getMinY(), ((TimeSeries)
                                // me.getValue()).getMaxY()));
                                axis4.setLabelPaint(colors[count]);
                                axis4.setTickLabelPaint(colors[count]);
                                plot2.setRangeAxis(count, axis4);
                                final ValueAxis domainAxis = domainAxis1;

                                // domainAxis.setLowerMargin(0.001);
                                // domainAxis.setUpperMargin(0.0);
                                plot2.setDomainCrosshairVisible(true);
                                plot2.setRangeCrosshairVisible(true);
                                //plot2.setRangeCrosshairLockedOnData(true);
                                plot2.setDomainAxis(domainAxis);
                                plot2.setForegroundAlpha(0.5f);
                                plot2.setDataset(count, dataset);
                                plot2.mapDatasetToRangeAxis(count, count);
                                XYBarRenderer rend = new XYBarRenderer(); // XYErrorRenderer

                                rend.setShadowVisible(false);
                                rend.setDrawBarOutline(true);
                                Stroke stroke = new BasicStroke(5);
                                rend.setBaseStroke(stroke);
                                final XYItemRenderer renderer = rend;
                                renderer.setSeriesToolTipGenerator(0, tt1);
                                // renderer.setItemLabelsVisible(true);
                                renderer.setSeriesPaint(0, colors[count]);
                                renderer.setSeriesVisible(0, true);
                                plot2.setRenderer(count, renderer);
                                int hits = 0;
                                int matchs = 0;

                                if (((ExtendedTimeSeries) me.getValue()).getStat() != null) {
                                    hits = ((ExtendedTimeSeries) me.getValue()).getStat()[1];
                                    //   matchs= ((ExtendedTimeSeries) me.getValue()).getStat()[0];
                                }
                                JCheckBox jcb = new JCheckBox(new VisibleAction(panel, checkboxPanel, axis4,
                                        me.getKey().toString() + "(" + hits + ")", 0));

                                jcb.setSelected(true);
                                jcb.setBackground(Color.white);
                                jcb.setBorderPainted(true);
                                jcb.setBorder(BorderFactory.createLineBorder(colors[count], 1, true));
                                jcb.setFont(new Font("Sans-serif", oldSmallFont.getStyle(),
                                        oldSmallFont.getSize()));
                                checkboxPanel.add(jcb);
                                count++;
                            }

                            JPanel pan = new JPanel();

                            pan.setLayout(new BorderLayout());
                            pan.setPreferredSize(new Dimension(600,
                                    Integer.parseInt((String) Preferences.getPreference("chartSize"))));
                            // pan.setPreferredSize(panelSize);
                            panel.add(pan);
                            final ChartPanel cpanel = new ChartPanel(chart);
                            cpanel.setMinimumDrawWidth(0);
                            cpanel.setMinimumDrawHeight(0);
                            cpanel.setMaximumDrawWidth(1920);
                            cpanel.setMaximumDrawHeight(1200);
                            // cpanel.setInitialDelay(0);
                            cpanel.setDismissDelay(9999999);
                            cpanel.setInitialDelay(50);
                            cpanel.setReshowDelay(200);
                            cpanel.setPreferredSize(new Dimension(600, 350));
                            // cpanel.restoreAutoBounds(); fix the tooltip
                            // missing problem but then relative display is
                            // broken
                            panel.add(new JSeparator(SwingConstants.HORIZONTAL));
                            pan.add(cpanel, BorderLayout.CENTER);
                            // checkboxPanel.setPreferredSize(new Dimension(600,
                            // 0));
                            cpanel.addChartMouseListener(new ChartMouseListener() {

                                public void chartMouseClicked(ChartMouseEvent chartmouseevent) {
                                    // chartmouseevent.getEntity().

                                    ChartEntity entity = chartmouseevent.getEntity();
                                    if (entity instanceof XYItemEntity) {
                                        XYItemEntity item = ((XYItemEntity) entity);
                                        if (item.getDataset() instanceof TimeSeriesCollection) {

                                            TimeSeriesCollection data = (TimeSeriesCollection) item
                                                    .getDataset();
                                            TimeSeries series = data.getSeries(item.getSeriesIndex());
                                            TimeSeriesDataItem dataitem = series.getDataItem(item.getItem());

                                            // logger.info(" Serie: "+series.getKey().toString()
                                            // +
                                            // " Period : "+dataitem.getPeriod().toString());
                                            // mr.getFileForDate(new Date
                                            // (x.longValue())
                                            ;
                                            int x = chartmouseevent.getTrigger().getX();
                                            // logger.info(mr.getFileForDate(dataitem.getPeriod().getEnd()));
                                            int y = chartmouseevent.getTrigger().getY();
                                            String myString = "";
                                            if (dataitem.getPeriod() != null) {
                                                logger.info(dataitem.getPeriod().getEnd());
                                                //                                    myString = mr.getFileForDate(dataitem.getPeriod().getEnd()).toString();
                                                String lineString = ""
                                                        + mr.getFileLineForDate(dataitem.getPeriod().getEnd(),
                                                                item.getDataset()
                                                                        .getSeriesKey(item.getSeriesIndex())
                                                                        .toString())
                                                                .getLineNumber();
                                                String fileString = cd.sourceFileArrayListMap
                                                        .get(pairs.getKey())
                                                        .get(mr.getFileLineForDate(
                                                                dataitem.getPeriod().getEnd(),
                                                                item.getDataset()
                                                                        .getSeriesKey(item.getSeriesIndex())
                                                                        .toString())
                                                                .getFileId())
                                                        .getFile().getAbsolutePath();
                                                String command = Preferences.getPreference("editorCommand");
                                                command = command.replace("$line", lineString);
                                                command = command.replace("$file", fileString);
                                                logger.info(command);
                                                Runtime rt = Runtime.getRuntime();
                                                try {
                                                    rt.exec(command);
                                                } catch (IOException e1) {
                                                    // TODO Auto-generated catch block
                                                    e1.printStackTrace();
                                                }
                                                StringSelection stringSelection = new StringSelection(
                                                        fileString);
                                                Clipboard clpbrd = Toolkit.getDefaultToolkit()
                                                        .getSystemClipboard();
                                                clpbrd.setContents(stringSelection, null);
                                                //      cpanel.getGraphics().drawString("file name copied", x - 5, y - 5);
                                                try {
                                                    Thread.sleep(500);
                                                } catch (InterruptedException e) {
                                                    // TODO Auto-generated catch
                                                    // block
                                                    e.printStackTrace();
                                                }
                                            }

                                            // logger.info(mr.getFileForDate(dataitem.getPeriod().getStart()));
                                        }
                                    }
                                }

                                public void chartMouseMoved(ChartMouseEvent e) {
                                }

                            });

                            pan.add(checkboxPanel, BorderLayout.SOUTH);

                        }
                    }
                } else {
                    logger.debug("mr dates null: " + mr.getGroup() + mr.getSourceID() + mr.getLogFiles());
                }
            }
        }
    }
    // Map=miner.mine(sourceFiles,repo);
    estimatedTime = System.currentTimeMillis() - startTime;

    revalidate();
    logger.info("display time: " + estimatedTime);
}

From source file:com.irccloud.android.fragment.BuffersListFragment.java

@SuppressWarnings("unchecked")
@Override//from  w  w  w . j av a  2 s  .co  m
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    conn = NetworkConnection.getInstance();
    view = inflater.inflate(R.layout.bufferslist, null);
    topUnreadIndicator = (LinearLayout) view.findViewById(R.id.topUnreadIndicator);
    topUnreadIndicator.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            int scrollTo = adapter.unreadPositionAbove(getListView().getFirstVisiblePosition());
            if (scrollTo > 0)
                getListView().setSelection(scrollTo - 1);
            else
                getListView().setSelection(0);

            updateUnreadIndicators(getListView().getFirstVisiblePosition(),
                    getListView().getLastVisiblePosition());
        }

    });
    topUnreadIndicatorColor = (LinearLayout) view.findViewById(R.id.topUnreadIndicatorColor);
    topUnreadIndicatorBorder = (LinearLayout) view.findViewById(R.id.topUnreadIndicatorBorder);
    bottomUnreadIndicator = (LinearLayout) view.findViewById(R.id.bottomUnreadIndicator);
    bottomUnreadIndicator.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            int offset = getListView().getLastVisiblePosition() - getListView().getFirstVisiblePosition();
            int scrollTo = adapter.unreadPositionBelow(getListView().getLastVisiblePosition()) - offset + 2;
            if (scrollTo < adapter.getCount())
                getListView().setSelection(scrollTo);
            else
                getListView().setSelection(adapter.getCount() - 1);

            updateUnreadIndicators(getListView().getFirstVisiblePosition(),
                    getListView().getLastVisiblePosition());
        }

    });
    bottomUnreadIndicatorColor = (LinearLayout) view.findViewById(R.id.bottomUnreadIndicatorColor);
    bottomUnreadIndicatorBorder = (LinearLayout) view.findViewById(R.id.bottomUnreadIndicatorBorder);
    listView = (ListView) view.findViewById(android.R.id.list);
    listView.setOnScrollListener(new OnScrollListener() {
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            updateUnreadIndicators(firstVisibleItem, firstVisibleItem + visibleItemCount - 1);
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }
    });
    listView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
            return mListener
                    .onBufferLongClicked(BuffersDataSource.getInstance().getBuffer(adapter.data.get(pos).bid));
        }

    });

    ready = NetworkConnection.getInstance().ready;

    if (ready) {
        if (savedInstanceState != null && savedInstanceState.containsKey("expandedArchives")) {
            ArrayList<Integer> expandedArchives = savedInstanceState.getIntegerArrayList("expandedArchives");
            Iterator<Integer> i = expandedArchives.iterator();
            while (i.hasNext()) {
                Integer cid = i.next();
                mExpandArchives.put(cid, true);
            }
        }
        refreshTask = new RefreshTask();
        refreshTask.doInBackground((Void) null);
        refreshTask.onPostExecute(null);
        if (savedInstanceState != null && savedInstanceState.containsKey("scrollPosition"))
            listView.setSelection(savedInstanceState.getInt("scrollPosition"));
    }
    return view;
}

From source file:ui.Interface.java

private void butSortSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butSortSelectActionPerformed
    if (txtNumbersSelect.getText().equals("")) {
        JOptionPane.showMessageDialog(this, "Please fill out the Empty fields!", "Sorting Algo Simulator v2.0",
                javax.swing.JOptionPane.ERROR_MESSAGE);
        return;//  www.  j ava2  s .c om
    }
    try {
        ArrayList simulationSteps = new ArrayList();
        String numbers = txtNumbersSelect.getText();
        numbers = numbers.replaceAll("\\s+", " ");
        String parts[] = numbers.split(" ");
        int size = parts.length;
        SelectionSort selectionSort = new SelectionSort(size);

        int Numbers[] = new int[parts.length];
        for (int i = 0; i < parts.length; i++) {
            Numbers[i] = Integer.parseInt(parts[i]);
        }
        for (int i = 0; i < size; i++) {
            selectionSort.insert(Numbers[i]);
        }
        long startTime = System.nanoTime();
        simulationSteps = selectionSort.selectionSort();
        long endTime = System.nanoTime();
        SelectTimeDiff = (endTime - startTime);

        listSortingSelect.setModel(new DefaultListModel());
        Iterator it = simulationSteps.iterator();
        while (it.hasNext()) {
            ((DefaultListModel) listSortingSelect.getModel()).addElement(it.next());
        }

        String lastElement = simulationSteps.get(simulationSteps.size() - 1).toString();
        txtSortedSelect.setText(lastElement);
        txtTimeSelect.setText(String.valueOf(SelectTimeDiff));
        txtCountSelect.setText(String.valueOf(SelectInstructionCount));
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this,
                "Error : Pls recheck the Number Sequence.. Sorry! non Numeric Characters are not allowed here",
                "Sorting Algo Simulator v2.0", javax.swing.JOptionPane.ERROR_MESSAGE);
        return;
    }
}

From source file:ui.Interface.java

private void butSortInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butSortInsertActionPerformed
    if (txtNumbersInsert.getText().equals("")) {
        JOptionPane.showMessageDialog(this, "Please fill out the Empty fields!", "Sorting Algo Simulator v2.0",
                javax.swing.JOptionPane.ERROR_MESSAGE);
        return;/*  w  ww .ja va  2 s . co  m*/
    }
    try {
        ArrayList simulationSteps = new ArrayList();
        String numbers = txtNumbersInsert.getText();
        numbers = numbers.replaceAll("\\s+", " ");

        String parts[] = numbers.split(" ");
        int size = parts.length;
        InsertionSort insertionSort = new InsertionSort(size);

        int Numbers[] = new int[parts.length];
        for (int i = 0; i < parts.length; i++) {
            Numbers[i] = Integer.parseInt(parts[i]);
        }
        for (int i = 0; i < size; i++) {
            insertionSort.insert(Numbers[i]);
        }
        long startTime = System.nanoTime();
        simulationSteps = insertionSort.insertionSortingAlgo();
        long endTime = System.nanoTime();

        InsertTimeDiff = (endTime - startTime);
        listSortingInsert.setModel(new DefaultListModel());
        Iterator it = simulationSteps.iterator();
        while (it.hasNext()) {
            ((DefaultListModel) listSortingInsert.getModel()).addElement(it.next());
        }
        String lastElement = simulationSteps.get(simulationSteps.size() - 1).toString();
        txtSortedInsert.setText(lastElement);
        txtTimeInsert.setText(String.valueOf(InsertTimeDiff));
        txtCountInsert.setText(String.valueOf(InsertInstructionCount));
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this,
                "Error : Pls recheck the Number Sequence.. Sorry! non Numeric Characters are not allowed here",
                "Sorting Algo Simulator v2.0", javax.swing.JOptionPane.ERROR_MESSAGE);
        return;
    }
}

From source file:com.ikon.module.jcr.JcrSearchModule.java

/**
 * Get keyword map//w  w  w . j  a  v a2s  .  c om
 */
private Map<String, Integer> getKeywordMapLive(String token, List<String> filter)
        throws RepositoryException, DatabaseException {
    log.debug("getKeywordMapLive({}, {})", token, filter);
    String statement = "/jcr:root//*[@jcr:primaryType eq 'openkm:document' or @jcr:primaryType eq 'openkm:mail' or @jcr:primaryType eq 'openkm:folder']";
    HashMap<String, Integer> cloud = new HashMap<String, Integer>();
    Session session = null;

    try {
        if (token == null) {
            session = JCRUtils.getSession();
        } else {
            session = JcrSessionManager.getInstance().get(token);
        }

        Workspace workspace = session.getWorkspace();
        QueryManager queryManager = workspace.getQueryManager();
        Query query = queryManager.createQuery(statement, Query.XPATH);
        javax.jcr.query.QueryResult qResult = query.execute();

        for (NodeIterator nit = qResult.getNodes(); nit.hasNext();) {
            Node doc = nit.nextNode();
            Value[] keywordsValue = doc.getProperty(com.ikon.bean.Property.KEYWORDS).getValues();
            ArrayList<String> keywordCollection = new ArrayList<String>();

            for (int i = 0; i < keywordsValue.length; i++) {
                keywordCollection.add(keywordsValue[i].getString());
            }

            if (filter != null && keywordCollection.containsAll(filter)) {
                for (Iterator<String> it = keywordCollection.iterator(); it.hasNext();) {
                    String keyword = it.next();

                    if (!filter.contains(keyword)) {
                        Integer occurs = cloud.get(keyword) != null ? cloud.get(keyword) : 0;
                        cloud.put(keyword, occurs + 1);
                    }
                }
            }
        }
    } catch (javax.jcr.RepositoryException e) {
        log.error(e.getMessage(), e);
        throw new RepositoryException(e.getMessage(), e);
    } finally {
        if (token == null)
            JCRUtils.logout(session);
    }

    log.debug("getKeywordMapLive: {}", cloud);
    return cloud;
}

From source file:de.ifsr.adam.ImageGenerator.java

/**
 * Takes a snapshot of the Pane and prints it to a pdf.
 *
 * @return True if no IOException occurred
 *///from  w w w.ja v  a  2s.c  o m
private boolean printToPDF(String filePath, Pane pane) {
    //Scene set up
    Group root = new Group();
    Scene printScene = new Scene(root);
    printScene.getStylesheets().add(this.stylesheetURI.toString());

    //Snapshot generation
    ArrayList<WritableImage> images = new ArrayList<>();
    try {
        ObservableList<Node> panes = pane.getChildren();
        for (int i = 0; i < panes.size(); i++) {
            GridPane gridPane = (GridPane) panes.get(i);
            ((Group) printScene.getRoot()).getChildren().clear();
            ((Group) printScene.getRoot()).getChildren().addAll(gridPane);
            images.add(printScene.snapshot(null));
            panes.add(i, gridPane);
        }
    } catch (Exception e) {
        log.error(e);
        return false;
    }

    //PDF Setup
    File outFile = new File(filePath + "." + "pdf");
    Iterator<WritableImage> iterImages = images.iterator();
    PDDocument doc = new PDDocument();

    try {

        while (iterImages.hasNext()) {
            //Page setup
            PDPage page = new PDPage();
            doc.addPage(page);
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, false);
            //Image setup
            BufferedImage bufImage = SwingFXUtils.fromFXImage(iterImages.next(), null);
            PDPixelMap pixelMap = new PDPixelMap(doc, bufImage);

            int width = (int) (page.getMediaBox().getWidth());
            int height = (int) (page.getMediaBox().getHeight());
            Dimension dim = new Dimension(width, height);
            contentStream.drawXObject(pixelMap, 0, 0, dim.width, dim.height);
            contentStream.close();
        }

        doc.save(outFile);
        return true;
    } catch (IOException | COSVisitorException e) {
        log.error(e);
        return false;
    }
}

From source file:com.tremolosecurity.proxy.myvd.inserts.restful.OpenUnisonRestful.java

@Override
public void search(SearchInterceptorChain chain, DistinguishedName base, Int scope, Filter filter,
        ArrayList<Attribute> attributes, Bool typesOnly, Results results, LDAPSearchConstraints constraints)
        throws LDAPException {
    String localBindDN = this.getRemoteMappedDN(base.getDN()).toString();

    HttpCon con;/*  w  w  w .  ja va 2 s  .  c om*/
    try {
        con = this.createClient();
    } catch (Exception e) {
        throw new LDAPException(LDAPException.resultCodeToString(LDAPException.OPERATIONS_ERROR),
                LDAPException.OPERATIONS_ERROR, "Could not create connection", e);
    }

    try {

        String searchScope;

        switch (scope.getValue()) {
        case 0:
            searchScope = "base";
            break;
        case 1:
            searchScope = "one";
            break;
        case 2:
            searchScope = "sub";
            break;
        default:
            throw new LDAPException(LDAPException.resultCodeToString(LDAPException.OPERATIONS_ERROR),
                    LDAPException.OPERATIONS_ERROR, "Unknown search scope : " + scope.getValue());
        }

        StringBuffer b = new StringBuffer();
        b.append(this.uriPath).append('/').append(URLEncoder.encode(localBindDN, "UTF-8")).append('/')
                .append(URLEncoder.encode(searchScope, "UTF-8"));

        StringBuffer urlBuffer = new StringBuffer();
        urlBuffer.append(this.urlBase).append(b);

        urlBuffer.append("?filter=").append(URLEncoder.encode(filter.getRoot().toString(), "UTF-8"));

        for (Attribute attribute : attributes) {
            urlBuffer.append("&attributes=")
                    .append(URLEncoder.encode(attribute.getAttribute().getName(), "UTF-8"));
        }

        HttpGet get = new HttpGet(urlBuffer.toString());

        this.addAuthorizationHeader(b.toString(), get);

        HttpResponse resp = con.getHttp().execute(get);

        String json = EntityUtils.toString(resp.getEntity());

        if (resp.getStatusLine().getStatusCode() == 200) {
            ArrayList<Entry> toReturn = new ArrayList<Entry>();
            Type listType = new TypeToken<List<LdapJsonEntry>>() {
            }.getType();

            List<LdapJsonEntry> returned = gson.fromJson(json, listType);
            for (LdapJsonEntry fromServer : returned) {
                LDAPAttributeSet attrs = new LDAPAttributeSet();
                for (String attrName : fromServer.getAttrs().keySet()) {
                    LDAPAttribute attr = new LDAPAttribute(attrName);
                    for (String value : fromServer.getAttrs().get(attrName)) {
                        attr.addValue(value);
                    }
                    attrs.add(attr);
                }
                LDAPEntry ldapEntry = new LDAPEntry(
                        this.getLocalMappedDN(new DN(fromServer.getDn())).toString(), attrs);
                toReturn.add(new Entry(ldapEntry));
            }

            chain.addResult(results, new IteratorEntrySet(toReturn.iterator()), base, scope, filter, attributes,
                    typesOnly, constraints);

        } else {
            LdapJsonError ldapResponse = gson.fromJson(json, LdapJsonError.class);
            throw new LDAPException(LDAPException.resultCodeToString(ldapResponse.getResponseCode()),
                    ldapResponse.getResponseCode(), ldapResponse.getErrorMessage());
        }
    } catch (LDAPException e) {
        throw e;
    } catch (Exception e) {
        throw new LDAPException(LDAPException.resultCodeToString(LDAPException.OPERATIONS_ERROR),
                LDAPException.OPERATIONS_ERROR, "Could not create connection", e);
    } finally {
        if (con != null) {
            try {
                con.getHttp().close();
            } catch (IOException e) {
                //no point
            }
            con.getBcm().close();
        }

    }
}

From source file:it.cnr.icar.eric.server.profile.ws.wsdl.cataloger.WSDLCatalogerEngine.java

@SuppressWarnings("unused")
private Collection<File> addZipEntriesToMap(ExtrinsicObjectType zipEO, InputSource inputSource)
        throws IOException {
    //Unzip the file in tmp dir
    ArrayList<File> files = Utility.unZip(TMP_DIR, inputSource.getByteStream());
    Iterator<File> iter = files.iterator();
    while (iter.hasNext()) {
        File file = iter.next();/* w w  w  .j av  a2s  . com*/
        String fileName = file.getName();
        String fileNameAbolute = file.getAbsolutePath();
        //String fileNameRelative = fileNameAbolute.substring(TMP_DIR.length()+1, fileNameAbolute.length());
        String fileNameRelative = fileNameAbolute.substring(TMP_DIR.length(), fileNameAbolute.length());
        idToFileMap.put(fileNameRelative, file);
    }
    return idToFileMap.values();
}