Example usage for java.util HashSet iterator

List of usage examples for java.util HashSet iterator

Introduction

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

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this set.

Usage

From source file:org.apache.hadoop.chukwa.analysis.salsa.visualization.Heatmap.java

/**
 * Interfaces with database to get data and 
 * populate data structures for rendering
 *//*  w ww .ja  va  2s . c o m*/
public HeatmapData getData() {
    // preliminary setup
    OfflineTimeHandler time_offline;
    TimeHandler time_online;
    long start, end, min, max;

    if (offline_use) {
        time_offline = new OfflineTimeHandler(param_map, this.timezone);
        start = time_offline.getStartTime();
        end = time_offline.getEndTime();
    } else {
        time_online = new TimeHandler(this.request, this.timezone);
        start = time_online.getStartTime();
        end = time_online.getEndTime();
    }

    DatabaseWriter dbw = new DatabaseWriter(this.cluster);

    // setup query
    String query;
    if (this.query_state != null && this.query_state.equals("read")) {
        query = "select block_id,start_time,finish_time,start_time_millis,finish_time_millis,status,state_name,hostname,other_host,bytes from ["
                + table
                + "] where finish_time between '[start]' and '[end]' and (state_name like 'read_local' or state_name like 'read_remote')";
    } else if (this.query_state != null && this.query_state.equals("write")) {
        query = "select block_id,start_time,finish_time,start_time_millis,finish_time_millis,status,state_name,hostname,other_host,bytes from ["
                + table
                + "] where finish_time between '[start]' and '[end]' and (state_name like 'write_local' or state_name like 'write_remote' or state_name like 'write_replicated')";
    } else {
        query = "select block_id,start_time,finish_time,start_time_millis,finish_time_millis,status,state_name,hostname,other_host,bytes from ["
                + table + "] where finish_time between '[start]' and '[end]' and state_name like '"
                + query_state + "'";
    }
    Macro mp = new Macro(start, end, query);
    query = mp.toString() + " order by start_time";

    ArrayList<HashMap<String, Object>> events = new ArrayList<HashMap<String, Object>>();

    ResultSet rs = null;

    log.debug("Query: " + query);
    // run query, extract results
    try {
        rs = dbw.query(query);
        ResultSetMetaData rmeta = rs.getMetaData();
        int col = rmeta.getColumnCount();
        while (rs.next()) {
            HashMap<String, Object> event = new HashMap<String, Object>();
            long event_time = 0;
            for (int i = 1; i <= col; i++) {
                if (rmeta.getColumnType(i) == java.sql.Types.TIMESTAMP) {
                    event.put(rmeta.getColumnName(i), rs.getTimestamp(i).getTime());
                } else {
                    event.put(rmeta.getColumnName(i), rs.getString(i));
                }
            }
            events.add(event);
        }
    } catch (SQLException ex) {
        // handle any errors
        log.error("SQLException: " + ex.getMessage());
        log.error("SQLState: " + ex.getSQLState());
        log.error("VendorError: " + ex.getErrorCode());
    } finally {
        dbw.close();
    }
    SimpleDateFormat format = new SimpleDateFormat("MMM dd yyyy HH:mm:ss");

    log.info(events.size() + " results returned.");

    HashSet<String> host_set = new HashSet<String>();
    HashMap<String, Integer> host_indices = new HashMap<String, Integer>();
    HashMap<Integer, String> host_rev_indices = new HashMap<Integer, String>();

    // collect hosts, name unique hosts
    for (int i = 0; i < events.size(); i++) {
        HashMap<String, Object> event = events.get(i);
        String curr_host = (String) event.get("hostname");
        String other_host = (String) event.get("other_host");
        host_set.add(curr_host);
        host_set.add(other_host);
    }
    int num_hosts = host_set.size();

    Iterator<String> host_iter = host_set.iterator();
    for (int i = 0; i < num_hosts && host_iter.hasNext(); i++) {
        String curr_host = host_iter.next();
        host_indices.put(curr_host, new Integer(i));
        host_rev_indices.put(new Integer(i), curr_host);
    }

    System.out.println("Number of hosts: " + num_hosts);
    long stats[][] = new long[num_hosts][num_hosts];
    long count[][] = new long[num_hosts][num_hosts]; // used for averaging

    int start_millis = 0, end_millis = 0;

    // deliberate design choice to duplicate code PER possible operation
    // otherwise we have to do the mode check N times, for N states returned
    //
    // compute aggregate statistics
    log.info("Query statistic type: " + this.query_stat_type);
    if (this.query_stat_type.equals("transaction_count")) {
        for (int i = 0; i < events.size(); i++) {
            HashMap<String, Object> event = events.get(i);
            start = (Long) event.get("start_time");
            end = (Long) event.get("finish_time");
            start_millis = Integer.parseInt(((String) event.get("start_time_millis")));
            end_millis = Integer.parseInt(((String) event.get("finish_time_millis")));
            String cell = (String) event.get("state_name");
            String this_host = (String) event.get("hostname");
            String other_host = (String) event.get("other_host");
            int this_host_idx = host_indices.get(this_host).intValue();
            int other_host_idx = host_indices.get(other_host).intValue();

            // to, from
            stats[other_host_idx][this_host_idx] += 1;
        }
    } else if (this.query_stat_type.equals("avg_duration")) {
        for (int i = 0; i < events.size(); i++) {
            HashMap<String, Object> event = events.get(i);
            start = (Long) event.get("start_time");
            end = (Long) event.get("finish_time");
            start_millis = Integer.parseInt(((String) event.get("start_time_millis")));
            end_millis = Integer.parseInt(((String) event.get("finish_time_millis")));
            String cell = (String) event.get("state_name");
            String this_host = (String) event.get("hostname");
            String other_host = (String) event.get("other_host");
            int this_host_idx = host_indices.get(this_host).intValue();
            int other_host_idx = host_indices.get(other_host).intValue();

            long curr_val = end_millis - start_millis + ((end - start) * 1000);

            // to, from
            stats[other_host_idx][this_host_idx] += curr_val;
            count[other_host_idx][this_host_idx] += 1;
        }
        for (int i = 0; i < num_hosts; i++) {
            for (int j = 0; j < num_hosts; j++) {
                if (count[i][j] > 0)
                    stats[i][j] = stats[i][j] / count[i][j];
            }
        }
    } else if (this.query_stat_type.equals("avg_volume")) {
        for (int i = 0; i < events.size(); i++) {
            HashMap<String, Object> event = events.get(i);
            start = (Long) event.get("start_time");
            end = (Long) event.get("finish_time");
            start_millis = Integer.parseInt(((String) event.get("start_time_millis")));
            end_millis = Integer.parseInt(((String) event.get("finish_time_millis")));
            String cell = (String) event.get("state_name");
            String this_host = (String) event.get("hostname");
            String other_host = (String) event.get("other_host");
            int this_host_idx = host_indices.get(this_host).intValue();
            int other_host_idx = host_indices.get(other_host).intValue();

            long curr_val = Long.parseLong((String) event.get("bytes"));

            // to, from
            stats[other_host_idx][this_host_idx] += curr_val;
            count[other_host_idx][this_host_idx] += 1;
        }
        for (int i = 0; i < num_hosts; i++) {
            for (int j = 0; j < num_hosts; j++) {
                if (count[i][j] > 0)
                    stats[i][j] = stats[i][j] / count[i][j];
            }
        }
    } else if (this.query_stat_type.equals("total_duration")) {
        for (int i = 0; i < events.size(); i++) {
            HashMap<String, Object> event = events.get(i);
            start = (Long) event.get("start_time");
            end = (Long) event.get("finish_time");
            start_millis = Integer.parseInt(((String) event.get("start_time_millis")));
            end_millis = Integer.parseInt(((String) event.get("finish_time_millis")));
            String cell = (String) event.get("state_name");
            String this_host = (String) event.get("hostname");
            String other_host = (String) event.get("other_host");
            int this_host_idx = host_indices.get(this_host).intValue();
            int other_host_idx = host_indices.get(other_host).intValue();

            double curr_val = end_millis - start_millis + ((end - start) * 1000);

            // to, from
            stats[other_host_idx][this_host_idx] += curr_val;
        }
    } else if (this.query_stat_type.equals("total_volume")) {
        for (int i = 0; i < events.size(); i++) {
            HashMap<String, Object> event = events.get(i);
            start = (Long) event.get("start_time");
            end = (Long) event.get("finish_time");
            start_millis = Integer.parseInt(((String) event.get("start_time_millis")));
            end_millis = Integer.parseInt(((String) event.get("finish_time_millis")));
            String cell = (String) event.get("state_name");
            String this_host = (String) event.get("hostname");
            String other_host = (String) event.get("other_host");
            int this_host_idx = host_indices.get(this_host).intValue();
            int other_host_idx = host_indices.get(other_host).intValue();

            long curr_val = Long.parseLong((String) event.get("bytes"));

            // to, from
            stats[other_host_idx][this_host_idx] += curr_val;
        }
    }

    int[] permute = null;
    if (sort_nodes) {
        permute = hClust(stats);
        stats = doPermute(stats, permute);
    }

    Table agg_tab = new Table();
    agg_tab.addColumn("stat", long.class);
    min = Long.MAX_VALUE;
    max = Long.MIN_VALUE;
    agg_tab.addRows(num_hosts * num_hosts);

    // row-wise placement (row1, followed by row2, etc.)
    for (int i = 0; i < num_hosts; i++) {
        for (int j = 0; j < num_hosts; j++) {
            agg_tab.setLong((i * num_hosts) + j, "stat", stats[i][j]);
            if (stats[i][j] > max)
                max = stats[i][j];
            if (stats[i][j] > 0 && stats[i][j] < min)
                min = stats[i][j];
        }
    }
    if (min == Long.MAX_VALUE)
        min = 0;

    log.info(agg_tab);

    // collate data
    HeatmapData hd = new HeatmapData();
    hd.stats = new long[num_hosts][num_hosts];
    hd.stats = stats;
    hd.min = min;
    hd.max = max;
    hd.num_hosts = num_hosts;
    hd.agg_tab = agg_tab;

    this.add_info_extra = new String("\nState: " + this.prettyStateNames.get(this.query_state) + " ("
            + events.size() + " " + this.query_state + "'s [" + this.query_stat_type + "])\n"
            + "Plotted value range: [" + hd.min + "," + hd.max + "] (Zeros in black)");

    hd.hostnames = new String[num_hosts];
    for (int i = 0; i < num_hosts; i++) {
        String curr_host = host_rev_indices.get(new Integer(permute[i]));
        if (sort_nodes) {
            hd.hostnames[i] = new String(curr_host);
        } else {
            hd.hostnames[i] = new String(curr_host);
        }
    }

    return hd;
}

From source file:it.cnr.icar.eric.server.common.ServerRequestContext.java

/**
 * Delete of composed objects such as ClassificationNodes within Schemes
 * can result in duplicate ObjectRefs being deleted.
 *//*from   w w  w.  j a  va 2s.  co m*/
private void removeDuplicateAffectedObjects(AuditableEventType ae) {
    HashSet<String> ids = new HashSet<String>();
    HashSet<ObjectRefType> duplicateObjectRefs = new HashSet<ObjectRefType>();

    //Determine duplicate ObjectRefs
    Iterator<ObjectRefType> iter = ae.getAffectedObjects().getObjectRef().iterator();
    while (iter.hasNext()) {
        ObjectRefType oref = iter.next();
        String id = oref.getId();
        if (ids.contains(id)) {
            duplicateObjectRefs.add(oref);
        } else {
            ids.add(id);
        }
    }

    //Now remove duplicate ObjectRefs
    iter = duplicateObjectRefs.iterator();
    while (iter.hasNext()) {
        ae.getAffectedObjects().getObjectRef().remove(iter.next());
    }

}

From source file:org.apache.axis.wsdl.toJava.JavaStubWriter.java

/**
 * This method returns a set of all the TypeEntry in a given PortType.
 * The elements of the returned HashSet are Types.
 * /* ww  w  .  ja  va  2 s  .  c  om*/
 * @param portType 
 * @return 
 */
private HashSet getTypesInPortType(PortType portType) {

    HashSet types = new HashSet();
    HashSet firstPassTypes = new HashSet();

    // Get all the types from all the operations
    List operations = portType.getOperations();

    for (int i = 0; i < operations.size(); ++i) {
        Operation op = (Operation) operations.get(i);

        firstPassTypes.addAll(getTypesInOperation(op));
    }

    // Add all the types nested and derived from the types
    // in the first pass.
    Iterator i = firstPassTypes.iterator();

    while (i.hasNext()) {
        TypeEntry type = (TypeEntry) i.next();

        if (!types.contains(type)) {
            types.add(type);
            types.addAll(type.getNestedTypes(symbolTable, true));
        }
    }

    if (emitter.isAllWanted()) {
        HashMap rawSymbolTable = symbolTable.getHashMap();
        for (Iterator j = rawSymbolTable.values().iterator(); j.hasNext();) {
            Vector typeVector = (Vector) j.next();
            for (Iterator k = typeVector.iterator(); k.hasNext();) {
                Object symbol = k.next();
                if (symbol instanceof DefinedType) {
                    TypeEntry type = (TypeEntry) symbol;
                    if (!types.contains(type)) {
                        types.add(type);
                    }
                }
            }
        }
    }
    return types;
}

From source file:org.prom5.framework.log.filter.LogEventLogFilterEnh.java

/**
 * Returns a Panel for the setting of parameters. When a LogFilter can be
 * added to a list in the framework. This panel is shown, and parameters can
 * be set. When the dialog is closed, a new instance of a LogFilter is
 * created by the framework by calling the <code>getNewLogFilter</code> method
 * of the dialog./*from  w  ww  .  ja v a 2 s.  com*/
 *
 * @param summary A LogSummary to be used for setting parameters.
 * @return JPanel
 */
public LogFilterParameterDialog getParameterDialog(LogSummary summary) {
    return new LogFilterParameterDialog(summary, LogEventLogFilterEnh.this) {

        LogEventCheckBoxEnh[] checks;
        JSpinner percTaskSpinner;
        JSpinner percPiSpinner;
        JComboBox choiceBox;

        /**
         * Keep the statistics for all the tasks
         */
        SummaryStatistics taskStatistics = null;

        /**
         * Keep the statistics for the occurrence of tasks in process instances
         */
        SummaryStatistics piStatistics = null;

        public LogFilter getNewLogFilter() {
            LogEvents e = new LogEvents();
            for (int i = 0; i < checks.length; i++) {
                if (checks[i].isSelected()) {
                    e.add(checks[i].getLogEvent());
                }
            }
            return new LogEventLogFilterEnh(e, getDoubleValueFromSpinner(percTaskSpinner.getValue()),
                    getDoubleValueFromSpinner(percPiSpinner.getValue()),
                    choiceBox.getSelectedItem().toString());
        }

        protected JPanel getPanel() {
            // add message to the test log for this plugin
            Message.add("<EnhEvtLogFilter>", Message.TEST);
            // statistics
            taskStatistics = SummaryStatistics.newInstance();
            piStatistics = SummaryStatistics.newInstance();
            // Set up an percentformatter
            NumberFormat percentFormatter = NumberFormat.getPercentInstance();
            percentFormatter.setMinimumFractionDigits(2);
            percentFormatter.setMaximumFractionDigits(2);
            // Instantiate the spinners
            percTaskSpinner = new JSpinner(new SpinnerNumberModel(5.0, 0.0, 100.0, 1.0));
            percPiSpinner = new JSpinner(new SpinnerNumberModel(5.0, 0.0, 100.0, 1.0));
            // generate the buttons that are needed
            JButton jButtonCalculate = new JButton("Calculate");
            JButton jButtonInvert = new JButton("Invert selection");
            // set up a choicebox to indicate whether the relationship between the two
            // percentages is AND or OR.

            percTaskSpinner.setValue(new Double(percentageTask));
            percPiSpinner.setValue(new Double(percentagePI));

            choiceBox = new JComboBox();
            choiceBox.addItem("AND");
            choiceBox.addItem("OR");
            choiceBox.setSelectedItem(selectedItemComboBox);

            // Some values that are needed for the sequel.
            int size = summary.getLogEvents().size();
            // For the new log reader sumATEs should be calculated in another way
            int sumATEs = 0;
            if (summary instanceof ExtendedLogSummary) {
                sumATEs = summary.getNumberOfAuditTrailEntries();
            } else if (summary instanceof LightweightLogSummary) {
                HashSet<ProcessInstance> pis = new HashSet<ProcessInstance>();
                Iterator logEvents = summary.getLogEvents().iterator();
                while (logEvents.hasNext()) {
                    LogEvent evt = (LogEvent) logEvents.next();
                    pis.addAll(summary.getInstancesForEvent(evt));
                }
                Iterator pis2 = pis.iterator();
                while (pis2.hasNext()) {
                    ProcessInstance pi = (ProcessInstance) pis2.next();
                    int simPis = MethodsForWorkflowLogDataStructures.getNumberSimilarProcessInstances(pi);
                    int numberATEs = pi.getAuditTrailEntryList().size();
                    sumATEs += simPis * numberATEs;
                    pi.isEmpty();
                }
            } else {

            }
            // calculate the number of process Instances, taking into account
            // the number of similar instances
            int sumPIs = 0;
            if (summary instanceof LightweightLogSummary) {
                sumPIs = calculateSumPIs(summary);
            }
            checks = new LogEventCheckBoxEnh[size];

            // create panels and labels
            JPanel global = new JPanel(new BorderLayout());
            JPanel sub2 = new JPanel(new BorderLayout());
            sub2.setBackground(Color.white);
            JLabel labelPercTask = new JLabel("percentage task");
            JLabel labelPercPI = new JLabel("percentage PI");

            // create panel sub1 to put the checkboxes on
            JPanel sub1 = new JPanel(new SpringLayout());
            sub1.setBackground(Color.lightGray);

            // Get percentage of task in the log and percentage of in how many
            // different PIs it appears.
            Iterator it = summary.getLogEvents().iterator();
            int i = 0;
            while (it.hasNext()) {
                LogEvent evt = (LogEvent) it.next();
                double percent = 0.0;
                if (summary instanceof ExtendedLogSummary) {
                    percent = ((double) evt.getOccurrenceCount() / (double) sumATEs);
                } else if (summary instanceof LightweightLogSummary) {
                    Set instances = summary.getInstancesForEvent(evt);
                    // getFrequencyTasks(evt, instances)
                    percent = (double) getFrequencyTasks(evt, instances) / (double) sumATEs;
                } else {

                }
                //String percString = percentFormatter.format(percent);
                LogEventCheckBoxEnh check = new LogEventCheckBoxEnh(evt);
                check.setPercentageTask(percent * 100);
                // add percentage to the statistics for the tasks
                taskStatistics.addValue(percent);
                // Get percentage of in how many different PIs a task appears,
                // taking into account whether the new or old logreader is used
                if (summary instanceof LightweightLogSummary) {
                    Set<ProcessInstance> pis = summary.getInstancesForEvent(evt);
                    int numberInstancesTask = 0;
                    Iterator it2 = pis.iterator();
                    while (it2.hasNext()) {
                        ProcessInstance pi = (ProcessInstance) it2.next();
                        numberInstancesTask += MethodsForWorkflowLogDataStructures
                                .getNumberSimilarProcessInstances(pi);
                    }
                    double fPI = (double) numberInstancesTask / (double) sumPIs;

                    check.setPercentagePI(fPI * 100);
                    // add percentage to the statistics for the PIs
                    piStatistics.addValue(fPI);
                } else if (summary instanceof ExtendedLogSummary) {
                    double percPIcheck = getPercentagePI(evt);
                    check.setPercentagePI(percPIcheck);
                    piStatistics.addValue(percPIcheck / 100);
                } else {
                    // raise exception, unknown logreader
                }
                // add to the checks array
                checks[i++] = check;
            }
            // fill sub1 with statistics information
            sub1.add(new JLabel(" Statistics    ( #tasks = " + taskStatistics.getN() + " )"));
            sub1.add(new JLabel(" "));
            sub1.add(new JLabel(" "));
            sub1.add(new JLabel(" Arithmetic Mean "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMean())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getMean())));
            sub1.add(new JLabel(" Geometric Mean "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getGeometricMean())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getGeometricMean())));
            sub1.add(new JLabel(" Standard Deviation "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getStandardDeviation())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getStandardDeviation())));
            sub1.add(new JLabel(" Min "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMin())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getMin())));
            sub1.add(new JLabel(" Max "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMax())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getMax())));
            sub1.add(new JLabel(" ------------------ "));
            sub1.add(new JLabel(" --------------- "));
            sub1.add(new JLabel(" --------------- "));
            sub1.add(new JLabel(" Tasks "));
            sub1.add(new JLabel(" percentage task "));
            sub1.add(new JLabel(" percentage PI "));
            // generate messages for the test case for this plugin
            Message.add("number tasks: " + taskStatistics.getN(), Message.TEST);
            Message.add("<percentage task>", Message.TEST);
            Message.add("arithmetic mean: " + taskStatistics.getMean(), Message.TEST);
            Message.add("geometric mean: " + taskStatistics.getGeometricMean(), Message.TEST);
            Message.add("standard deviation: " + taskStatistics.getStandardDeviation(), Message.TEST);
            Message.add("min: " + taskStatistics.getMin(), Message.TEST);
            Message.add("max: " + taskStatistics.getMax(), Message.TEST);
            Message.add("<percentage task/>", Message.TEST);
            Message.add("<percentage PI>", Message.TEST);
            Message.add("arithmetic mean: " + piStatistics.getMean(), Message.TEST);
            Message.add("geometric mean: " + piStatistics.getGeometricMean(), Message.TEST);
            Message.add("standard deviation: " + piStatistics.getStandardDeviation(), Message.TEST);
            Message.add("min: " + piStatistics.getMin(), Message.TEST);
            Message.add("max: " + piStatistics.getMax(), Message.TEST);
            Message.add("<percentage PI/>", Message.TEST);
            // add the checkboxes to the GUI.
            Arrays.sort(checks);
            for (i = 0; i < checks.length; i++) {
                sub1.add(checks[i]);
                if ((eventsToKeep != null) && (!eventsToKeep.contains(checks[i].getLogEvent()))) {
                    checks[i].setSelected(false);
                }
                // put the percentages on the GUI
                sub1.add(new JLabel(percentFormatter.format(checks[i].getPercentageTask() / 100)));
                sub1.add(new JLabel(percentFormatter.format(checks[i].getPercentagePI() / 100)));
            }
            //
            SpringUtilities util = new SpringUtilities();
            util.makeCompactGrid(sub1, checks.length + 8, 3, 3, 3, 8, 3);
            // put the contents on the respective panels
            global.add(sub2, java.awt.BorderLayout.CENTER);
            global.add(sub1, java.awt.BorderLayout.SOUTH);
            //
            JPanel sub21 = new JPanel(new SpringLayout());
            //sub21.setLayout(new BoxLayout(sub21, BoxLayout.PAGE_AXIS));
            sub2.setBackground(Color.red);
            JPanel textPanel = new JPanel(new BorderLayout());
            textPanel.setBackground(Color.yellow);
            JPanel sub221 = new JPanel(new FlowLayout());
            sub221.setBackground(Color.yellow);
            JPanel sub222 = new JPanel(new FlowLayout());
            sub222.setBackground(Color.yellow);
            // two different panels to be places on sub21
            //JPanel sub21First = new JPanel();
            //sub21First.setLayout(new BoxLayout(sub21First, BoxLayout.LINE_AXIS));
            //sub21First.setMaximumSize(new Dimension(1000, 25));
            //sub21First.add(Box.createHorizontalGlue());
            //sub21First.add(labelPercTask);
            //sub21First.add(percTaskSpinner, null);
            //percTaskSpinner.setMaximumSize(new Dimension(10, 20));
            //sub21First.add(jButtonCalculate);
            //jButtonCalculate.setMaximumSize(new Dimension(10, 20));
            //sub21First.add(labelPercPI);
            //sub21First.add(percPiSpinner, null);
            //percPiSpinner.setMaximumSize(new Dimension(10, 20));
            //sub21First.add(choiceBox);
            //choiceBox.setMaximumSize(new Dimension(10, 20));
            //sub21First.add(Box.createHorizontalGlue());
            //JPanel sub21Second = new JPanel();
            //sub21Second.setLayout(new BoxLayout(sub21Second, BoxLayout.LINE_AXIS));
            //sub21Second.setMaximumSize(new Dimension(1000, 25));
            //sub21Second.add(Box.createHorizontalGlue());
            //sub21Second.add(jButtonInvert);
            //sub21Second.add(Box.createHorizontalGlue());
            //
            //sub21.add(sub21First);
            //sub21.add(sub21Second);

            sub21.add(labelPercTask);
            sub21.add(percTaskSpinner, null);
            sub21.add(jButtonCalculate);
            sub21.add(labelPercPI);
            sub21.add(percPiSpinner, null);
            sub21.add(choiceBox);
            // add the invert button
            sub21.add(new JLabel(" "));
            sub21.add(new JLabel(" "));
            sub21.add(jButtonInvert);
            sub21.add(new JLabel(" "));
            sub21.add(new JLabel(" "));
            sub21.add(new JLabel(" "));
            sub21.setMaximumSize(sub21.getPreferredSize());
            sub2.add(sub21, java.awt.BorderLayout.CENTER);
            sub2.add(textPanel, java.awt.BorderLayout.SOUTH);
            textPanel.add(new JLabel(
                    "The Calculate button needs to be clicked to calculate which tasks need to be selected!!!"),
                    java.awt.BorderLayout.CENTER);
            textPanel.add(
                    new JLabel("Clicking the OK button only accepts, but nothing is again calculated!!!!"),
                    java.awt.BorderLayout.SOUTH);
            util.makeCompactGrid(sub21, 2, 6, 3, 3, 8, 3);
            //

            // specify button action for the button ButtonPreview
            jButtonCalculate.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    // The preview button is clicked
                    buttonClicked();
                    // end for
                }
            });

            // specify button action for the button Invert
            jButtonInvert.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    invertButtonClicked();
                }
            });

            return global;

        }

        /**
         * When the preview button is clicked
         */
        public void buttonClicked() {
            for (int k = 0; k < checks.length; k++) {
                boolean firstCheck = false;
                boolean secondCheck = false;
                LogEventCheckBoxEnh c = checks[k];
                // check for the task in c whether its percentage is higher than
                // perc
                firstCheck = checkTask(c, percTaskSpinner.getValue());

                // Also check whether the task occurs in more than percTr
                // percent of the traces
                secondCheck = checkPI(c, percPiSpinner.getValue());

                // Check whether for choiceBox OR or AND is selected
                boolean logicalResult = true;
                if (((String) choiceBox.getSelectedItem()).equals("AND")) {
                    logicalResult = firstCheck && secondCheck;
                } else if (((String) choiceBox.getSelectedItem()).equals("OR")) {
                    logicalResult = firstCheck || secondCheck;
                }
                // set the checkbox selected or not
                if (logicalResult == true) {
                    c.setSelected(true);
                } else {
                    c.setSelected(false);
                }
            }
            // add messages to the test log for this case
            int numberCheckedBoxes = 0;
            for (int i = 0; i < checks.length; i++) {
                if (checks[i].isSelected()) {
                    numberCheckedBoxes++;
                }
            }
            Message.add("number of selected tasks: " + numberCheckedBoxes, Message.TEST);
            Message.add("<EnhEvtLogFilter/>", Message.TEST);
        }

        /**
         *
         */
        public void invertButtonClicked() {
            for (int i = 0; i < checks.length; i++) {
                checks[i].setSelected(!checks[i].isSelected());
            }
        }

        /**
         * Checks whether the task in c occurs with a lower percentage in the log
         * than the percentage given by percTask.
         * @param c LogEventCheckBoxEnh the checkbox that contains the task.
         * @param percTask Object the percentage
         * @return boolean True if the percentage of which the task in c occurs
         * in the log is greater or equal than percTaks, false otherwise.
         */
        private boolean checkTask(LogEventCheckBoxEnh c, Object percTask) {
            boolean returnBoolean = false;
            double percT = 0.0;
            percT = getDoubleValueFromSpinner(percTask);
            // check whether its percentage is higher than percT
            if (c.getPercentageTask() >= percT) {
                returnBoolean = true;
            } else {
                returnBoolean = false;
            }

            return returnBoolean;
        }

        /**
         * Checks whether the task in c occurs with a lower percentage in different
         * process instances than the percentage given by percTrace.
         * @param c LogEventCheckBoxEnh the checkbox that contains the task.
         * @param percTrace Object the percentage.
         * @return boolean True, if the percentage of which the task in different
         * process instances occurs in the log is greater or equal than percTrace,
         * false otherwise.
         */
        private boolean checkPI(LogEventCheckBoxEnh c, Object percPIobj) {
            boolean returnBoolean = false;
            double percPI = 0.0;

            percPI = getDoubleValueFromSpinner(percPIobj);
            // check whether its percentage is higher than percPI
            if (c.getPercentagePI() >= percPI) {
                returnBoolean = true;
            } else {
                returnBoolean = false;
            }

            return returnBoolean;
        }

        /**
         * Get the percentage of that this task occurs in different PIs
         * @param evt LogEvent the logEvent in which the task can be found
         * @return double the percentage of which this task in the log occurs
         */
        private double getPercentagePI(LogEvent evt) {
            double returnPercent = 0.0;
            HashMap mapping = ((ExtendedLogSummary) summary).getMappingAtesToNumberPIs();
            int numberPI = summary.getNumberOfProcessInstances();

            // Get the frequency of PI in which the task occurs
            Object value = null;
            Iterator it = mapping.keySet().iterator();
            while (it.hasNext()) {
                Object keyObj = it.next();
                String key = (String) keyObj;
                if (key.equals(
                        evt.getModelElementName().trim() + " " + "(" + evt.getEventType().trim() + ")")) {
                    value = mapping.get(keyObj);
                    break;
                }
            }

            if (value != null) {
                // calculate frequency
                returnPercent = (((Integer) value).doubleValue() / new Double(numberPI).doubleValue()) * 100;
            }

            return returnPercent;
        }

        private int getFrequencyTasks(LogEvent evt, Set instances) {
            int returnFrequency = 0;
            Iterator instIterator = instances.iterator();
            while (instIterator.hasNext()) {
                ProcessInstance pi = (ProcessInstance) instIterator.next();
                Iterator ates = pi.getAuditTrailEntryList().iterator();
                while (ates.hasNext()) {
                    AuditTrailEntry ate = (AuditTrailEntry) ates.next();
                    if (ate.getElement().trim().equals(evt.getModelElementName().trim())
                            && ate.getType().equals(evt.getEventType())) {
                        returnFrequency += MethodsForWorkflowLogDataStructures
                                .getNumberSimilarProcessInstances(pi);
                    }
                }
            }
            return returnFrequency;
        }

        /**
         * Gets the double value of an object, provided that value is a
         * Double or Long object
         * @param value Object
         * @return double the double value
         */
        private double getDoubleValueFromSpinner(Object value) {
            double returnDouble = 0.0;

            if (value instanceof Long) {
                returnDouble = (((Long) value).doubleValue());
            } else if (value instanceof Double) {
                returnDouble = (((Double) value).doubleValue());
            }

            return returnDouble;
        }

        /**
         * Returns the number of process instances, taking into account the
         * number of similar instances
         * @param summary LogSummary the log summary
         * @return int the number of process instances
         */
        private int calculateSumPIs(LogSummary summary) {
            int returnSum = 0;
            HashSet pis = new HashSet<ProcessInstance>();
            Iterator it = summary.getLogEvents().iterator();
            while (it.hasNext()) {
                LogEvent evt = (LogEvent) it.next();
                pis.addAll(summary.getInstancesForEvent(evt));
            }
            // for each process instance in pis, get the number of similar instances
            Iterator it2 = pis.iterator();
            while (it2.hasNext()) {
                ProcessInstance pi = (ProcessInstance) it2.next();
                returnSum += MethodsForWorkflowLogDataStructures.getNumberSimilarProcessInstances(pi);
            }
            return returnSum;
        }

        protected boolean getAllParametersSet() {
            // calculate values
            //buttonClicked();
            return true;
        }

    };
}

From source file:org.apache.axis.encoding.SerializationContext.java

/**
 * The serialize method uses hrefs to reference all non-primitive
 * values.  These values are stored and serialized by calling
 * outputMultiRefs after the serialize method completes.
 *//*from www .j  av a2 s  .c  o m*/
public void outputMultiRefs() throws IOException {
    if (!doMultiRefs || (multiRefValues == null) || soapConstants == SOAPConstants.SOAP12_CONSTANTS)
        return;
    outputMultiRefsFlag = true;
    AttributesImpl attrs = new AttributesImpl();
    attrs.addAttribute("", "", "", "", "");

    String encodingURI = soapConstants.getEncodingURI();
    // explicitly state that this attribute is not a root
    String prefix = getPrefixForURI(encodingURI);
    String root = prefix + ":root";
    attrs.addAttribute(encodingURI, Constants.ATTR_ROOT, root, "CDATA", "0");

    // Make sure we put the encodingStyle on each multiref element we
    // output.
    String encodingStyle;
    if (msgContext != null) {
        encodingStyle = msgContext.getEncodingStyle();
    } else {
        encodingStyle = soapConstants.getEncodingURI();
    }
    String encStyle = getPrefixForURI(soapConstants.getEnvelopeURI()) + ':' + Constants.ATTR_ENCODING_STYLE;
    attrs.addAttribute(soapConstants.getEnvelopeURI(), Constants.ATTR_ENCODING_STYLE, encStyle, "CDATA",
            encodingStyle);

    // Make a copy of the keySet because it could be updated
    // during processing
    HashSet keys = new HashSet();
    keys.addAll(multiRefValues.keySet());
    Iterator i = keys.iterator();
    while (i.hasNext()) {
        while (i.hasNext()) {
            AttributesImpl attrs2 = new AttributesImpl(attrs);
            Object val = i.next();
            MultiRefItem mri = (MultiRefItem) multiRefValues.get(val);
            attrs2.setAttribute(0, "", Constants.ATTR_ID, "id", "CDATA", mri.id);

            forceSer = mri.value;

            // Now serialize the value.
            // The sendType parameter is defaulted for interop purposes.
            // Some of the remote services do not know how to
            // ascertain the type in these circumstances (though Axis does).
            serialize(multirefQName, attrs2, mri.value, mri.xmlType, null, this.sendNull, Boolean.TRUE); // mri.sendType
        }

        // Done processing the iterated values.  During the serialization
        // of the values, we may have run into new nested values.  These
        // were placed in the secondLevelObjects map, which we will now
        // process by changing the iterator to locate these values.
        if (secondLevelObjects != null) {
            i = secondLevelObjects.iterator();
            secondLevelObjects = null;
        }
    }

    // Reset maps and flags
    forceSer = null;
    outputMultiRefsFlag = false;
    multiRefValues = null;
    multiRefIndex = -1;
    secondLevelObjects = null;
}

From source file:org.apache.roller.weblogger.pojos.WeblogEntry.java

public void updateTags(List<String> updatedTags) throws WebloggerException {

    if (updatedTags == null) {
        return;//from   w  ww.  j a va 2s.c o  m
    }

    HashSet newTags = new HashSet(updatedTags.size());
    Locale localeObject = getWebsite() != null ? getWebsite().getLocaleInstance() : Locale.getDefault();

    for (Iterator<String> it = updatedTags.iterator(); it.hasNext();) {
        String name = it.next();
        newTags.add(Utilities.normalizeTag(name, localeObject));
    }

    HashSet removeTags = new HashSet();

    // remove old ones no longer passed.
    for (Iterator it = getTags().iterator(); it.hasNext();) {
        WeblogEntryTag tag = (WeblogEntryTag) it.next();
        if (!newTags.contains(tag.getName())) {
            removeTags.add(tag.getName());
        } else {
            newTags.remove(tag.getName());
        }
    }

    WeblogEntryManager weblogManager = WebloggerFactory.getWeblogger().getWeblogEntryManager();
    for (Iterator it = removeTags.iterator(); it.hasNext();) {
        weblogManager.removeWeblogEntryTag((String) it.next(), this);
    }

    for (Iterator it = newTags.iterator(); it.hasNext();) {
        addTag((String) it.next());
    }
}

From source file:com.redhat.rhn.manager.kickstart.KickstartFormatter.java

private String getRhnPost() {
    log.debug("getRhnPost called.");
    StringBuilder retval = new StringBuilder();
    retval.append("%" + KickstartScript.TYPE_POST);
    addLogBegin(retval, RHN_LOG_FILE, "");
    retval.append(BEGINRHN_LOG_APPEND);/* www.jav  a 2  s. com*/

    retval.append(renderKeys() + NEWLINE);

    List<ActivationKey> tokens = generateActKeyTokens(this.ksdata, this.session);

    HashSet updatePackages = getUpdatePackages(tokens);
    HashSet freshPackages = getFreshPackages(tokens);
    boolean isFresh = freshPackages.size() > 0;
    boolean isUpdate = updatePackages.size() > 0;

    // update the required/optional packages needed for the kickstart
    if (isUpdate || isFresh) {
        log.debug("need latest up2date");
        //order matters, therfore multiple logic branches
        retval.append(MKDIR_OPTIONAL + NEWLINE);
        if (isUpdate) {
            //wregglej - wget is broken, so workaround it.
            retval.append(CHDIR_OPT_RPMS + NEWLINE);

            retval.append(WGET_OPT_RPMS);
            for (Iterator itr = updatePackages.iterator(); itr.hasNext();) {
                retval.append(itr.next().toString() + SPACE);
            }
            retval.append(NEWLINE);
        }
        if (isFresh) {
            //wregglej - work around wget again.
            retval.append(CHDIR_RPMS + NEWLINE);

            retval.append(WGET_RPMS);
            for (Iterator itr = freshPackages.iterator(); itr.hasNext();) {
                retval.append(itr.next().toString() + SPACE);
            }
            retval.append(NEWLINE);
        }
        if (isUpdate) {
            retval.append(UPDATE_CMD);
            for (int i = 0; i < UPDATE_PKG_NAMES.length; i++) {
                retval.append(UPDATE_OPT_PATH + UPDATE_PKG_NAMES[i] + "* ");
            }
            retval.append(NEWLINE);
        }
        if (isFresh) {
            retval.append(FRESH_CMD + NEWLINE);
        }
    }

    if (this.ksdata.getKickstartDefaults().getVirtualizationType().getLabel().equals("para_host")) {
        retval.append(VIRT_HOST_GRUB_FIX);
    }

    // For rhel2,3,4 we import a different key.  otherwise we just
    // rely on the cobbler snippet below to import the key.
    if (this.ksdata.isRhel2()) {
        retval.append(IMPORT_RHN_KEY2 + NEWLINE);
    } else if (this.ksdata.isRhel3() || this.ksdata.isRhel4()) {
        retval.append(IMPORT_RHN_KEY34 + NEWLINE);
    }

    if (log.isDebugEnabled()) {
        log.debug("kickstart_host: [" + XMLRPC_HOST + "] kshost: [" + this.ksHost + "] indexof: "
                + this.ksHost.indexOf(XMLRPC_HOST));
    }

    String up2datehost = REDHAT_MGMT_SERVER;
    //check if server going through Spacewalk Proxy,
    //if so, register through proxy instead
    if (this.session != null && this.session.getSystemRhnHost() != null
            && !this.session.getSystemRhnHost().equals("unknown")) {
        up2datehost = this.session.getSystemRhnHost();
    }

    log.debug("adding perl -npe for /etc/sysconfig/rhn/up2date");
    if (this.ksdata.isRhel2()) {
        retval.append("perl -npe " + "'s|^(\\s*(noSSLS\\|s)erverURL\\s*=\\s*[^:]+://)[^/]*/|${1}" + up2datehost
                + "/|' -i /etc/sysconfig/rhn/rhn_register" + NEWLINE);
    }
    // both rhel 2 and rhel3/4 need the following
    retval.append("perl -npe " + "'s|^(\\s*(noSSLS\\|s)erverURL\\s*=\\s*[^:]+://)[^/]*/|\\${1}" + up2datehost
            + "/|' -i /etc/sysconfig/rhn/up2date" + NEWLINE);

    if (this.ksdata.getVerboseUp2date()) {
        retval.append("[ -r /etc/yum.conf ] && " + "perl -npe 's/debuglevel=2/debuglevel=5/' -i /etc/yum.conf"
                + NEWLINE);
        retval.append("[ -r /etc/sysconfig/rhn/up2date ] && "
                + "perl -npe 's/debug=0/debug=1/' -i /etc/sysconfig/rhn/up2date" + NEWLINE);
    }

    if (this.ksdata.getKickstartDefaults().getRemoteCommandFlag().booleanValue()) {
        retval.append(REMOTE_CMD + NEWLINE);
    }

    if (this.ksdata.getKickstartDefaults().getCfgManagementFlag().booleanValue()) {
        retval.append(CONFIG_CMD + NEWLINE);
    }

    retval.append(NEWLINE);
    retval.append(KSTREE);
    retval.append(NEWLINE);

    //RHEL 5u4 hack for bz 495680
    if (ksdata.isRhel5()) {
        retval.append("/etc/init.d/messagebus restart" + NEWLINE);
        retval.append("/etc/init.d/haldaemon restart" + NEWLINE);
    }
    retval.append("# begin cobbler snippet" + NEWLINE);
    addCobblerSnippet(retval, DEFAULT_MOTD);
    addCobblerSnippet(retval, REDHAT_REGISTER_SNIPPET);
    retval.append("# end cobbler snippet" + NEWLINE);

    retval.append(NEWLINE);
    retval.append(RHNCHECK + NEWLINE);
    addLogEnd(retval, RHN_LOG_FILE, "");

    retval.append(NEWLINE);
    // Work around for bug #522251
    if (!this.ksdata.getKickstartDefaults().getKstree().getChannel().getChannelArch().getName()
            .startsWith("s390")) {
        addCobblerSnippet(retval, "post_install_network_config");
    }
    addEnd(retval);
    return retval.toString();
}

From source file:org.apache.axis.wsdl.toJava.JavaGeneratorFactory.java

/**
 * setFaultContext:/*from   w w w.  jav a  2  s.  c o m*/
 * Helper routine for the setFaultContext method above.
 * Examines the indicated fault and sets COMPLEX_TYPE_FAULT
 * EXCEPTION_DATA_TYPE and EXCEPTION_CLASS_NAME as appropriate.
 *
 * @param fault       FaultInfo to analyze
 * @param symbolTable SymbolTable
 */
private void setFaultContext(FaultInfo fault, SymbolTable symbolTable) {

    QName faultXmlType = null;
    Vector parts = new Vector();

    // Get the parts of the fault's message.
    // An IOException is thrown if the parts cannot be
    // processed.  Skip such parts for this analysis
    try {
        symbolTable.getParametersFromParts(parts, fault.getMessage().getOrderedParts(null), false,
                fault.getName(), null);
    } catch (IOException e) {
    }

    // Inspect each TypeEntry referenced in a Fault Message Part
    String exceptionClassName = null;

    for (int j = 0; j < parts.size(); j++) {
        TypeEntry te = ((Parameter) (parts.elementAt(j))).getType();

        // If the TypeEntry is an element, advance to the type.
        // This occurs if the message part uses the element= attribute
        TypeEntry elementTE = null;

        if (te instanceof Element) {
            elementTE = te;
            te = te.getRefType();
        }

        // remember the QName of the type.
        faultXmlType = te.getQName();

        // Determine if the te should be processed using the
        // simple type mapping or the complex type mapping
        // NOTE: treat array types as simple types
        if ((te.getBaseType() != null) || te.isSimpleType()
                || ((te.getDimensions().length() > 0) && (te.getRefType().getBaseType() != null))) {

            // Simple Type Exception
        } else {

            // Complex Type Exception
            Boolean isComplexFault = (Boolean) te.getDynamicVar(JavaGeneratorFactory.COMPLEX_TYPE_FAULT);

            if ((isComplexFault == null) || !isComplexFault.booleanValue()) {

                // Mark the type as a complex type fault
                te.setDynamicVar(JavaGeneratorFactory.COMPLEX_TYPE_FAULT, Boolean.TRUE);

                if (elementTE != null) {
                    te.setDynamicVar(JavaGeneratorFactory.COMPLEX_TYPE_FAULT, Boolean.TRUE);
                }

                // Mark all derived types as Complex Faults
                HashSet derivedSet = org.apache.axis.wsdl.symbolTable.Utils.getDerivedTypes(te, symbolTable);
                Iterator derivedI = derivedSet.iterator();

                while (derivedI.hasNext()) {
                    TypeEntry derivedTE = (TypeEntry) derivedI.next();

                    derivedTE.setDynamicVar(JavaGeneratorFactory.COMPLEX_TYPE_FAULT, Boolean.TRUE);
                }

                // Mark all base types as Complex Faults
                TypeEntry base = SchemaUtils.getComplexElementExtensionBase(te.getNode(), symbolTable);

                while (base != null) {
                    base.setDynamicVar(JavaGeneratorFactory.COMPLEX_TYPE_FAULT, Boolean.TRUE);

                    base = SchemaUtils.getComplexElementExtensionBase(base.getNode(), symbolTable);
                }
            }

            // The exception class name is the name of the type
            exceptionClassName = te.getName();
        }
    }

    String excName = getExceptionJavaNameHook(fault.getMessage().getQName()); //     for derived class
    if (excName != null) {
        exceptionClassName = excName;
    }

    // Set the name of the exception and
    // whether the exception is a complex type
    MessageEntry me = symbolTable.getMessageEntry(fault.getMessage().getQName());

    if (me != null) {
        me.setDynamicVar(JavaGeneratorFactory.EXCEPTION_DATA_TYPE, faultXmlType);

        if (exceptionClassName != null) {
            me.setDynamicVar(JavaGeneratorFactory.COMPLEX_TYPE_FAULT, Boolean.TRUE);
            me.setDynamicVar(JavaGeneratorFactory.EXCEPTION_CLASS_NAME, exceptionClassName);
        } else {
            me.setDynamicVar(JavaGeneratorFactory.EXCEPTION_CLASS_NAME, emitter.getJavaName(me.getQName()));
        }
    }
}

From source file:net.sourceforge.mipa.predicatedetection.lattice.sequence.SequenceWindowedLatticeChecker.java

private void computeReachableStatesOri(AbstractLatticeIDNode CGS) {
    // TODO Auto-generated method stub
    labelingCGS((SequenceLatticeIDNode) CGS);
    HashSet<State> precState = new HashSet<State>();
    for (int i = 0; i < children.length; i++) {
        String[] index = new String[children.length];
        for (int j = 0; j < children.length; j++) {
            index[j] = CGS.getID()[j];/*w  w  w . j  av  a  2s . c  o m*/
        }
        index[i] = Integer.toString(Integer.valueOf(index[i]) - 1);
        String ID = StringUtils.join(index, ' ');
        if (oriMappedLattice.get(ID) != null) {
            SequenceLatticeIDNode node = (SequenceLatticeIDNode) oriMappedLattice.get(ID);
            if (node.getReachedStates().size() == 0) {
                computeReachableStatesOri(node);
            }
            Iterator<State> iterator = node.getReachedStates().iterator();
            while (iterator.hasNext()) {
                precState.add(iterator.next());
            }
        }
    }
    Iterator<State> iterator = precState.iterator();
    while (iterator.hasNext()) {
        State state = iterator.next();
        String[] satisfiedPredicate = ((SequenceLatticeIDNode) CGS).getSatisfiedPredicates().split(" ");
        for (int i = 0; i < satisfiedPredicate.length; i++) {
            if (!satisfiedPredicate[i].equals("")) {
                char c = satisfiedPredicate[i].charAt(0);
                State step = state.step(c);
                ((SequenceLatticeIDNode) CGS).addReachedStates(step);
            }
        }
    }
    if (DEBUG) {
        long time_t = (new Date()).getTime();
        outOriConstruction.print("[ ");
        for (int i = 0; i < CGS.getID().length; i++) {
            outOriConstruction.print(CGS.getID()[i] + " ");
        }
        outOriConstruction.print("]: reachable states: ");
        Iterator<State> it = ((SequenceLatticeIDNode) CGS).getReachedStates().iterator();
        while (it.hasNext()) {
            State state = it.next();
            outOriConstruction.print(state.getName() + " ");
        }
        outOriConstruction.println();
        outOriConstruction.flush();
        wastedOriTime += (new Date()).getTime() - time_t;
    }
}

From source file:org.processmining.framework.log.filter.LogEventLogFilterEnh.java

/**
 * Returns a Panel for the setting of parameters. When a LogFilter can be
 * added to a list in the framework. This panel is shown, and parameters can
 * be set. When the dialog is closed, a new instance of a LogFilter is
 * created by the framework by calling the <code>getNewLogFilter</code>
 * method of the dialog.//from w  w  w . j  av  a  2  s . c  om
 * 
 * @param summary
 *            A LogSummary to be used for setting parameters.
 * @return JPanel
 */
public LogFilterParameterDialog getParameterDialog(LogSummary summary) {
    return new LogFilterParameterDialog(summary, LogEventLogFilterEnh.this) {

        LogEventCheckBoxEnh[] checks;
        JSpinner percTaskSpinner;
        JSpinner percPiSpinner;
        JComboBox choiceBox;

        /**
         * Keep the statistics for all the tasks
         */
        SummaryStatistics taskStatistics = null;

        /**
         * Keep the statistics for the occurrence of tasks in process
         * instances
         */
        SummaryStatistics piStatistics = null;

        public LogFilter getNewLogFilter() {
            LogEvents e = new LogEvents();
            for (int i = 0; i < checks.length; i++) {
                if (checks[i].isSelected()) {
                    e.add(checks[i].getLogEvent());
                }
            }
            return new LogEventLogFilterEnh(e, getDoubleValueFromSpinner(percTaskSpinner.getValue()),
                    getDoubleValueFromSpinner(percPiSpinner.getValue()),
                    choiceBox.getSelectedItem().toString());
        }

        protected JPanel getPanel() {
            // add message to the test log for this plugin
            Message.add("<EnhEvtLogFilter>", Message.TEST);
            // statistics
            taskStatistics = SummaryStatistics.newInstance();
            piStatistics = SummaryStatistics.newInstance();
            // Set up an percentformatter
            NumberFormat percentFormatter = NumberFormat.getPercentInstance();
            percentFormatter.setMinimumFractionDigits(2);
            percentFormatter.setMaximumFractionDigits(2);
            // Instantiate the spinners
            percTaskSpinner = new JSpinner(new SpinnerNumberModel(5.0, 0.0, 100.0, 1.0));
            percPiSpinner = new JSpinner(new SpinnerNumberModel(5.0, 0.0, 100.0, 1.0));
            // generate the buttons that are needed
            JButton jButtonCalculate = new JButton("Calculate");
            JButton jButtonInvert = new JButton("Invert selection");
            // set up a choicebox to indicate whether the relationship
            // between the two
            // percentages is AND or OR.

            percTaskSpinner.setValue(new Double(percentageTask));
            percPiSpinner.setValue(new Double(percentagePI));

            choiceBox = new JComboBox();
            choiceBox.addItem("AND");
            choiceBox.addItem("OR");
            choiceBox.setSelectedItem(selectedItemComboBox);

            // Some values that are needed for the sequel.
            int size = summary.getLogEvents().size();
            // For the new log reader sumATEs should be calculated in
            // another way
            int sumATEs = 0;
            if (summary instanceof ExtendedLogSummary) {
                sumATEs = summary.getNumberOfAuditTrailEntries();
            } else if (summary instanceof LightweightLogSummary) {
                HashSet<ProcessInstance> pis = new HashSet<ProcessInstance>();
                Iterator logEvents = summary.getLogEvents().iterator();
                while (logEvents.hasNext()) {
                    LogEvent evt = (LogEvent) logEvents.next();
                    pis.addAll(summary.getInstancesForEvent(evt));
                }
                Iterator pis2 = pis.iterator();
                while (pis2.hasNext()) {
                    ProcessInstance pi = (ProcessInstance) pis2.next();
                    int simPis = MethodsForWorkflowLogDataStructures.getNumberSimilarProcessInstances(pi);
                    int numberATEs = pi.getAuditTrailEntryList().size();
                    sumATEs += simPis * numberATEs;
                    pi.isEmpty();
                }
            } else {

            }
            // calculate the number of process Instances, taking into
            // account
            // the number of similar instances
            int sumPIs = 0;
            if (summary instanceof LightweightLogSummary) {
                sumPIs = calculateSumPIs(summary);
            }
            checks = new LogEventCheckBoxEnh[size];

            // create panels and labels
            JPanel global = new JPanel(new BorderLayout());
            JPanel sub2 = new JPanel(new BorderLayout());
            sub2.setBackground(Color.white);
            JLabel labelPercTask = new JLabel("percentage task");
            JLabel labelPercPI = new JLabel("percentage PI");

            // create panel sub1 to put the checkboxes on
            JPanel sub1 = new JPanel(new SpringLayout());
            sub1.setBackground(Color.lightGray);

            // Get percentage of task in the log and percentage of in how
            // many
            // different PIs it appears.
            Iterator it = summary.getLogEvents().iterator();
            int i = 0;
            while (it.hasNext()) {
                LogEvent evt = (LogEvent) it.next();
                double percent = 0.0;
                if (summary instanceof ExtendedLogSummary) {
                    percent = ((double) evt.getOccurrenceCount() / (double) sumATEs);
                } else if (summary instanceof LightweightLogSummary) {
                    Set instances = summary.getInstancesForEvent(evt);
                    // getFrequencyTasks(evt, instances)
                    percent = (double) getFrequencyTasks(evt, instances) / (double) sumATEs;
                } else {

                }
                // String percString = percentFormatter.format(percent);
                LogEventCheckBoxEnh check = new LogEventCheckBoxEnh(evt);
                check.setPercentageTask(percent * 100);
                // add percentage to the statistics for the tasks
                taskStatistics.addValue(percent);
                // Get percentage of in how many different PIs a task
                // appears,
                // taking into account whether the new or old logreader is
                // used
                if (summary instanceof LightweightLogSummary) {
                    Set<ProcessInstance> pis = summary.getInstancesForEvent(evt);
                    int numberInstancesTask = 0;
                    Iterator it2 = pis.iterator();
                    while (it2.hasNext()) {
                        ProcessInstance pi = (ProcessInstance) it2.next();
                        numberInstancesTask += MethodsForWorkflowLogDataStructures
                                .getNumberSimilarProcessInstances(pi);
                    }
                    double fPI = (double) numberInstancesTask / (double) sumPIs;

                    check.setPercentagePI(fPI * 100);
                    // add percentage to the statistics for the PIs
                    piStatistics.addValue(fPI);
                } else if (summary instanceof ExtendedLogSummary) {
                    double percPIcheck = getPercentagePI(evt);
                    check.setPercentagePI(percPIcheck);
                    piStatistics.addValue(percPIcheck / 100);
                } else {
                    // raise exception, unknown logreader
                }
                // add to the checks array
                checks[i++] = check;
            }
            // fill sub1 with statistics information
            sub1.add(new JLabel(" Statistics    ( #tasks = " + taskStatistics.getN() + " )"));
            sub1.add(new JLabel(" "));
            sub1.add(new JLabel(" "));
            sub1.add(new JLabel(" Arithmetic Mean "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMean())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getMean())));
            sub1.add(new JLabel(" Geometric Mean "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getGeometricMean())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getGeometricMean())));
            sub1.add(new JLabel(" Standard Deviation "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getStandardDeviation())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getStandardDeviation())));
            sub1.add(new JLabel(" Min "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMin())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getMin())));
            sub1.add(new JLabel(" Max "));
            sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMax())));
            sub1.add(new JLabel(percentFormatter.format(piStatistics.getMax())));
            sub1.add(new JLabel(" ------------------ "));
            sub1.add(new JLabel(" --------------- "));
            sub1.add(new JLabel(" --------------- "));
            sub1.add(new JLabel(" Tasks "));
            sub1.add(new JLabel(" percentage task "));
            sub1.add(new JLabel(" percentage PI "));
            // generate messages for the test case for this plugin
            Message.add("number tasks: " + taskStatistics.getN(), Message.TEST);
            Message.add("<percentage task>", Message.TEST);
            Message.add("arithmetic mean: " + taskStatistics.getMean(), Message.TEST);
            Message.add("geometric mean: " + taskStatistics.getGeometricMean(), Message.TEST);
            Message.add("standard deviation: " + taskStatistics.getStandardDeviation(), Message.TEST);
            Message.add("min: " + taskStatistics.getMin(), Message.TEST);
            Message.add("max: " + taskStatistics.getMax(), Message.TEST);
            Message.add("<percentage task/>", Message.TEST);
            Message.add("<percentage PI>", Message.TEST);
            Message.add("arithmetic mean: " + piStatistics.getMean(), Message.TEST);
            Message.add("geometric mean: " + piStatistics.getGeometricMean(), Message.TEST);
            Message.add("standard deviation: " + piStatistics.getStandardDeviation(), Message.TEST);
            Message.add("min: " + piStatistics.getMin(), Message.TEST);
            Message.add("max: " + piStatistics.getMax(), Message.TEST);
            Message.add("<percentage PI/>", Message.TEST);
            // add the checkboxes to the GUI.
            Arrays.sort(checks);
            for (i = 0; i < checks.length; i++) {
                sub1.add(checks[i]);
                if ((eventsToKeep != null) && (!eventsToKeep.contains(checks[i].getLogEvent()))) {
                    checks[i].setSelected(false);
                }
                // put the percentages on the GUI
                sub1.add(new JLabel(percentFormatter.format(checks[i].getPercentageTask() / 100)));
                sub1.add(new JLabel(percentFormatter.format(checks[i].getPercentagePI() / 100)));
            }
            //
            SpringUtilities util = new SpringUtilities();
            util.makeCompactGrid(sub1, checks.length + 8, 3, 3, 3, 8, 3);
            // put the contents on the respective panels
            global.add(sub2, java.awt.BorderLayout.CENTER);
            global.add(sub1, java.awt.BorderLayout.SOUTH);
            //
            JPanel sub21 = new JPanel(new SpringLayout());
            // sub21.setLayout(new BoxLayout(sub21, BoxLayout.PAGE_AXIS));
            sub2.setBackground(Color.red);
            JPanel textPanel = new JPanel(new BorderLayout());
            textPanel.setBackground(Color.yellow);
            JPanel sub221 = new JPanel(new FlowLayout());
            sub221.setBackground(Color.yellow);
            JPanel sub222 = new JPanel(new FlowLayout());
            sub222.setBackground(Color.yellow);
            // two different panels to be places on sub21
            // JPanel sub21First = new JPanel();
            // sub21First.setLayout(new BoxLayout(sub21First,
            // BoxLayout.LINE_AXIS));
            // sub21First.setMaximumSize(new Dimension(1000, 25));
            // sub21First.add(Box.createHorizontalGlue());
            // sub21First.add(labelPercTask);
            // sub21First.add(percTaskSpinner, null);
            // percTaskSpinner.setMaximumSize(new Dimension(10, 20));
            // sub21First.add(jButtonCalculate);
            // jButtonCalculate.setMaximumSize(new Dimension(10, 20));
            // sub21First.add(labelPercPI);
            // sub21First.add(percPiSpinner, null);
            // percPiSpinner.setMaximumSize(new Dimension(10, 20));
            // sub21First.add(choiceBox);
            // choiceBox.setMaximumSize(new Dimension(10, 20));
            // sub21First.add(Box.createHorizontalGlue());
            // JPanel sub21Second = new JPanel();
            // sub21Second.setLayout(new BoxLayout(sub21Second,
            // BoxLayout.LINE_AXIS));
            // sub21Second.setMaximumSize(new Dimension(1000, 25));
            // sub21Second.add(Box.createHorizontalGlue());
            // sub21Second.add(jButtonInvert);
            // sub21Second.add(Box.createHorizontalGlue());
            //
            // sub21.add(sub21First);
            // sub21.add(sub21Second);

            sub21.add(labelPercTask);
            sub21.add(percTaskSpinner, null);
            sub21.add(jButtonCalculate);
            sub21.add(labelPercPI);
            sub21.add(percPiSpinner, null);
            sub21.add(choiceBox);
            // add the invert button
            sub21.add(new JLabel(" "));
            sub21.add(new JLabel(" "));
            sub21.add(jButtonInvert);
            sub21.add(new JLabel(" "));
            sub21.add(new JLabel(" "));
            sub21.add(new JLabel(" "));
            sub21.setMaximumSize(sub21.getPreferredSize());
            sub2.add(sub21, java.awt.BorderLayout.CENTER);
            sub2.add(textPanel, java.awt.BorderLayout.SOUTH);
            textPanel.add(new JLabel(
                    "The Calculate button needs to be clicked to calculate which tasks need to be selected!!!"),
                    java.awt.BorderLayout.CENTER);
            textPanel.add(
                    new JLabel("Clicking the OK button only accepts, but nothing is again calculated!!!!"),
                    java.awt.BorderLayout.SOUTH);
            util.makeCompactGrid(sub21, 2, 6, 3, 3, 8, 3);
            //

            // specify button action for the button ButtonPreview
            jButtonCalculate.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    // The preview button is clicked
                    buttonClicked();
                    // end for
                }
            });

            // specify button action for the button Invert
            jButtonInvert.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    invertButtonClicked();
                }
            });

            return global;

        }

        /**
         * When the preview button is clicked
         */
        public void buttonClicked() {
            for (int k = 0; k < checks.length; k++) {
                boolean firstCheck = false;
                boolean secondCheck = false;
                LogEventCheckBoxEnh c = checks[k];
                // check for the task in c whether its percentage is higher
                // than
                // perc
                firstCheck = checkTask(c, percTaskSpinner.getValue());

                // Also check whether the task occurs in more than percTr
                // percent of the traces
                secondCheck = checkPI(c, percPiSpinner.getValue());

                // Check whether for choiceBox OR or AND is selected
                boolean logicalResult = true;
                if (((String) choiceBox.getSelectedItem()).equals("AND")) {
                    logicalResult = firstCheck && secondCheck;
                } else if (((String) choiceBox.getSelectedItem()).equals("OR")) {
                    logicalResult = firstCheck || secondCheck;
                }
                // set the checkbox selected or not
                if (logicalResult == true) {
                    c.setSelected(true);
                } else {
                    c.setSelected(false);
                }
            }
            // add messages to the test log for this case
            int numberCheckedBoxes = 0;
            for (int i = 0; i < checks.length; i++) {
                if (checks[i].isSelected()) {
                    numberCheckedBoxes++;
                }
            }
            Message.add("number of selected tasks: " + numberCheckedBoxes, Message.TEST);
            Message.add("<EnhEvtLogFilter/>", Message.TEST);
        }

        /**
         *
         */
        public void invertButtonClicked() {
            for (int i = 0; i < checks.length; i++) {
                checks[i].setSelected(!checks[i].isSelected());
            }
        }

        /**
         * Checks whether the task in c occurs with a lower percentage in
         * the log than the percentage given by percTask.
         * 
         * @param c
         *            LogEventCheckBoxEnh the checkbox that contains the
         *            task.
         * @param percTask
         *            Object the percentage
         * @return boolean True if the percentage of which the task in c
         *         occurs in the log is greater or equal than percTaks,
         *         false otherwise.
         */
        private boolean checkTask(LogEventCheckBoxEnh c, Object percTask) {
            boolean returnBoolean = false;
            double percT = 0.0;
            percT = getDoubleValueFromSpinner(percTask);
            // check whether its percentage is higher than percT
            if (c.getPercentageTask() >= percT) {
                returnBoolean = true;
            } else {
                returnBoolean = false;
            }

            return returnBoolean;
        }

        /**
         * Checks whether the task in c occurs with a lower percentage in
         * different process instances than the percentage given by
         * percTrace.
         * 
         * @param c
         *            LogEventCheckBoxEnh the checkbox that contains the
         *            task.
         * @param percTrace
         *            Object the percentage.
         * @return boolean True, if the percentage of which the task in
         *         different process instances occurs in the log is greater
         *         or equal than percTrace, false otherwise.
         */
        private boolean checkPI(LogEventCheckBoxEnh c, Object percPIobj) {
            boolean returnBoolean = false;
            double percPI = 0.0;

            percPI = getDoubleValueFromSpinner(percPIobj);
            // check whether its percentage is higher than percPI
            if (c.getPercentagePI() >= percPI) {
                returnBoolean = true;
            } else {
                returnBoolean = false;
            }

            return returnBoolean;
        }

        /**
         * Get the percentage of that this task occurs in different PIs
         * 
         * @param evt
         *            LogEvent the logEvent in which the task can be found
         * @return double the percentage of which this task in the log
         *         occurs
         */
        private double getPercentagePI(LogEvent evt) {
            double returnPercent = 0.0;
            HashMap mapping = ((ExtendedLogSummary) summary).getMappingAtesToNumberPIs();
            int numberPI = summary.getNumberOfProcessInstances();

            // Get the frequency of PI in which the task occurs
            Object value = null;
            Iterator it = mapping.keySet().iterator();
            while (it.hasNext()) {
                Object keyObj = it.next();
                String key = (String) keyObj;
                if (key.equals(
                        evt.getModelElementName().trim() + " " + "(" + evt.getEventType().trim() + ")")) {
                    value = mapping.get(keyObj);
                    break;
                }
            }

            if (value != null) {
                // calculate frequency
                returnPercent = (((Integer) value).doubleValue() / new Double(numberPI).doubleValue()) * 100;
            }

            return returnPercent;
        }

        private int getFrequencyTasks(LogEvent evt, Set instances) {
            int returnFrequency = 0;
            Iterator instIterator = instances.iterator();
            while (instIterator.hasNext()) {
                ProcessInstance pi = (ProcessInstance) instIterator.next();
                Iterator ates = pi.getAuditTrailEntryList().iterator();
                while (ates.hasNext()) {
                    AuditTrailEntry ate = (AuditTrailEntry) ates.next();
                    if (ate.getElement().trim().equals(evt.getModelElementName().trim())
                            && ate.getType().equals(evt.getEventType())) {
                        returnFrequency += MethodsForWorkflowLogDataStructures
                                .getNumberSimilarProcessInstances(pi);
                    }
                }
            }
            return returnFrequency;
        }

        /**
         * Gets the double value of an object, provided that value is a
         * Double or Long object
         * 
         * @param value
         *            Object
         * @return double the double value
         */
        private double getDoubleValueFromSpinner(Object value) {
            double returnDouble = 0.0;

            if (value instanceof Long) {
                returnDouble = (((Long) value).doubleValue());
            } else if (value instanceof Double) {
                returnDouble = (((Double) value).doubleValue());
            }

            return returnDouble;
        }

        /**
         * Returns the number of process instances, taking into account the
         * number of similar instances
         * 
         * @param summary
         *            LogSummary the log summary
         * @return int the number of process instances
         */
        private int calculateSumPIs(LogSummary summary) {
            int returnSum = 0;
            HashSet pis = new HashSet<ProcessInstance>();
            Iterator it = summary.getLogEvents().iterator();
            while (it.hasNext()) {
                LogEvent evt = (LogEvent) it.next();
                pis.addAll(summary.getInstancesForEvent(evt));
            }
            // for each process instance in pis, get the number of similar
            // instances
            Iterator it2 = pis.iterator();
            while (it2.hasNext()) {
                ProcessInstance pi = (ProcessInstance) it2.next();
                returnSum += MethodsForWorkflowLogDataStructures.getNumberSimilarProcessInstances(pi);
            }
            return returnSum;
        }

        protected boolean getAllParametersSet() {
            // calculate values
            // buttonClicked();
            return true;
        }

    };
}