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:com.clustercontrol.monitor.run.factory.RunMonitor.java

/**
 * ????/*from  w  ww  . ja v a 2s .c  om*/
 * <p>
 * <ol>
 * <li>????????{@link #setMonitorInfo(String, String)}</li>
 * <li>?????????{@link #setJudgementInfo()}</li>
 * <li>??????????{@link #setCheckInfo()}</li>
 * <li>???????? {@link #collect(String)}</li>
 * <li>???????? {@link #getCheckResult(boolean)}</li>
 * <li>?????????{@link #getPriority(int)}</li>
 * <li>????{@link #notify(boolean, String, int, Date)}</li>
 * </ol>
 *
 * @return ??????</code> true </code>
 * @throws FacilityNotFound
 * @throws MonitorNotFound
 * @throws InvalidRole
 * @throws EntityExistsException
 * @throws HinemosUnknown
 *
 * @see #setMonitorInfo(String, String)
 * @see #setJudgementInfo()
 * @see #setCheckInfo()
 * @see #collect(String)
 * @see #getCheckResult(boolean)
 * @see #getPriority(int)
 * @see #notify(boolean, String, int, Date)
 */
protected boolean runMonitorInfo()
        throws FacilityNotFound, MonitorNotFound, InvalidRole, EntityExistsException, HinemosUnknown {

    m_now = HinemosTime.getDateInstance();

    m_priorityMap = new HashMap<Integer, ArrayList<String>>();
    m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_INFO), new ArrayList<String>());
    m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_WARNING), new ArrayList<String>());
    m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_CRITICAL), new ArrayList<String>());
    m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_UNKNOWN), new ArrayList<String>());
    List<Sample> sampleList = new ArrayList<Sample>();
    List<StringSample> collectedSamples = new ArrayList<>();

    try {
        // 
        boolean run = this.setMonitorInfo(m_monitorTypeId, m_monitorId);
        if (!run) {
            // ?
            return true;
        }

        // 
        setJudgementInfo();

        // ??
        setCheckInfo();

        ArrayList<String> facilityList = null;
        ExecutorCompletionService<MonitorRunResultInfo> ecs = new ExecutorCompletionService<MonitorRunResultInfo>(
                ParallelExecution.instance().getExecutorService());
        int taskCount = 0;

        if (!m_isMonitorJob) {
            // ??
            // ID?????
            // /?true?????ID??
            facilityList = new RepositoryControllerBean().getExecTargetFacilityIdList(m_facilityId,
                    m_monitor.getOwnerRoleId());
            if (facilityList.size() == 0) {
                return true;
            }

            m_isNode = new RepositoryControllerBean().isNode(m_facilityId);

            // ???????
            nodeInfo = new HashMap<String, NodeInfo>();
            for (String facilityId : facilityList) {
                try {
                    synchronized (this) {
                        nodeInfo.put(facilityId, new RepositoryControllerBean().getNode(facilityId));
                    }
                } catch (FacilityNotFound e) {
                    // ???
                }
            }

            m_log.debug("monitor start : monitorTypeId : " + m_monitorTypeId + ", monitorId : " + m_monitorId);

            /**
             * ?
             */
            // ID???????
            Iterator<String> itr = facilityList.iterator();
            while (itr.hasNext()) {
                String facilityId = itr.next();
                if (facilityId != null && !"".equals(facilityId)) {

                    // ???RunMonitor????
                    // ?????????????
                    RunMonitor runMonitor = this.createMonitorInstance();

                    // ?????
                    runMonitor.m_monitorTypeId = this.m_monitorTypeId;
                    runMonitor.m_monitorId = this.m_monitorId;
                    runMonitor.m_now = this.m_now;
                    runMonitor.m_priorityMap = this.m_priorityMap;
                    runMonitor.setMonitorInfo(runMonitor.m_monitorTypeId, runMonitor.m_monitorId);
                    runMonitor.setJudgementInfo();
                    runMonitor.setCheckInfo();
                    runMonitor.nodeInfo = this.nodeInfo;

                    ecs.submit(new MonitorExecuteTask(runMonitor, facilityId));
                    taskCount++;

                    if (m_log.isDebugEnabled()) {
                        m_log.debug("starting monitor result : monitorId = " + m_monitorId + ", facilityId = "
                                + facilityId);
                    }
                } else {
                    facilityList.remove(facilityId);
                }
            }

        } else {
            // ??
            // ID?????
            // /?true?????ID??
            facilityList = new RepositoryControllerBean().getExecTargetFacilityIdList(m_facilityId,
                    m_monitor.getOwnerRoleId());
            if (facilityList.size() != 1 || !facilityList.get(0).equals(m_facilityId)) {
                return true;
            }

            m_isNode = true;

            // ???????
            nodeInfo = new HashMap<String, NodeInfo>();
            try {
                synchronized (this) {
                    nodeInfo.put(m_facilityId, new RepositoryControllerBean().getNode(m_facilityId));
                }
            } catch (FacilityNotFound e) {
                // ???
            }
            m_log.debug("monitor start : monitorTypeId : " + m_monitorTypeId + ", monitorId : " + m_monitorId);

            /**
             * ?
             */
            // ???RunMonitor????
            // ?????????????
            RunMonitor runMonitor = this.createMonitorInstance();

            // ?????
            runMonitor.m_isMonitorJob = this.m_isMonitorJob;
            runMonitor.m_monitorTypeId = this.m_monitorTypeId;
            runMonitor.m_monitorId = this.m_monitorId;
            runMonitor.m_now = this.m_now;
            runMonitor.m_priorityMap = this.m_priorityMap;
            runMonitor.setMonitorInfo(runMonitor.m_monitorTypeId, runMonitor.m_monitorId);
            runMonitor.setJudgementInfo();
            runMonitor.setCheckInfo();
            runMonitor.nodeInfo = this.nodeInfo;
            runMonitor.m_prvData = this.m_prvData;

            ecs.submit(new MonitorExecuteTask(runMonitor, m_facilityId));
            taskCount++;

            if (m_log.isDebugEnabled()) {
                m_log.debug("starting monitor result : monitorId = " + m_monitorId + ", facilityId = "
                        + m_facilityId);
            }
        }

        /**
         * ??
         */
        MonitorRunResultInfo result = new MonitorRunResultInfo(); // ??

        m_log.debug("total start : monitorTypeId : " + m_monitorTypeId + ", monitorId : " + m_monitorId);

        // ???
        StringSample strSample = null;
        Sample sample = null;
        if (m_monitor.getCollectorFlg()) {
            //? - 
            if (m_monitor.getMonitorType() == MonitorTypeConstant.TYPE_STRING
                    || m_monitor.getMonitorType() == MonitorTypeConstant.TYPE_TRAP) {
                strSample = new StringSample(HinemosTime.getDateInstance(), m_monitor.getMonitorId());
            }
            //? - 
            else {
                sample = new Sample(HinemosTime.getDateInstance(), m_monitor.getMonitorId());
            }
        }

        for (int i = 0; i < taskCount; i++) {
            Future<MonitorRunResultInfo> future = ecs.take();
            result = future.get(); // ??

            String facilityId = result.getFacilityId();
            m_nodeDate = result.getNodeDate();

            if (m_log.isDebugEnabled()) {
                m_log.debug("finished monitor : monitorId = " + m_monitorId + ", facilityId = " + facilityId);
            }

            //??????????
            if (m_monitor.getMonitorType() == MonitorTypeConstant.TYPE_STRING
                    || m_monitor.getMonitorType() == MonitorTypeConstant.TYPE_TRAP) {
                if (strSample != null) {
                    strSample.set(facilityId, m_monitor.getMonitorTypeId(), result.getMessageOrg());
                }
            }

            if (!m_isMonitorJob) {
                // ???
                if (result.getProcessType().booleanValue()) {
                    // ?
                    notify(true, facilityId, result.getCheckResult(), new Date(m_nodeDate), result);
                    // ???
                    if (sample != null) {
                        int errorType = -1;
                        if (result.isCollectorResult()) {
                            errorType = CollectedDataErrorTypeConstant.NOT_ERROR;
                        } else {
                            errorType = CollectedDataErrorTypeConstant.UNKNOWN;
                        }
                        sample.set(facilityId, m_monitor.getItemName(), result.getValue(), errorType);
                    }
                }
            } else {
                m_monitorRunResultInfo = new MonitorRunResultInfo();
                m_monitorRunResultInfo.setPriority(result.getPriority());
                m_monitorRunResultInfo.setCheckResult(result.getCheckResult());
                m_monitorRunResultInfo.setNodeDate(m_nodeDate);
                m_monitorRunResultInfo
                        .setMessageOrg(makeJobOrgMessage(result.getMessageOrg(), result.getMessage()));
                m_monitorRunResultInfo.setCurData(result.getCurData());
            }
        }

        // ?????
        if (m_monitor.getMonitorType() == MonitorTypeConstant.TYPE_STRING
                || m_monitor.getMonitorType() == MonitorTypeConstant.TYPE_TRAP) {
            //? - ?????
            if (strSample != null) {
                collectedSamples.add(strSample);
            }
            if (!collectedSamples.isEmpty()) {
                CollectStringDataUtil.store(collectedSamples);
            }
        } else {
            if (sample != null) {
                sampleList.add(sample);
            }
            if (!sampleList.isEmpty()) {
                CollectDataUtil.put(sampleList);
            }
        }

        m_log.debug("monitor end : monitorTypeId : " + m_monitorTypeId + ", monitorId : " + m_monitorId);

        return true;

    } catch (FacilityNotFound e) {
        throw e;
    } catch (InterruptedException e) {
        m_log.info("runMonitorInfo() monitorTypeId = " + m_monitorTypeId + ", monitorId  = " + m_monitorId
                + " : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        return false;
    } catch (ExecutionException e) {
        m_log.info("runMonitorInfo() monitorTypeId = " + m_monitorTypeId + ", monitorId  = " + m_monitorId
                + " : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        return false;
    }
}

From source file:org.openmeetings.app.remote.red5.ScopeApplicationAdapter.java

/**
 * This Function is triggered from the Whiteboard
 * //from  ww w  .  j ava2s . c  om
 * @param whiteboardObj
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public synchronized void sendVars(ArrayList whiteboardObjParam) {
    //
    try {

        // In previous version this has been always a Map, now its a List
        // so I re-wrapp that class to be a Map again.
        // swagner 13.02.2009
        // log.debug("*..*sendVars1: " + whiteboardObjParam);
        // log.debug("*..*sendVars2: " + whiteboardObjParam.getClass());
        // log.debug("*..*sendVars3: " +
        // whiteboardObjParam.getClass().getName());

        Map whiteboardObj = new HashMap();
        int i = 0;
        for (Iterator iter = whiteboardObjParam.iterator(); iter.hasNext();) {
            Object obj = iter.next();
            // log.debug("obj"+obj);
            whiteboardObj.put(i, obj);
            i++;
        }

        // Map whiteboardObj = (Map) whiteboardObjParam;

        // Check if this User is the Mod:
        IConnection current = Red5.getConnectionLocal();
        RoomClient currentClient = this.clientListManager.getClientByStreamId(current.getClient().getId());

        if (currentClient == null) {
            return;
        }

        Long room_id = currentClient.getRoom_id();

        String action = whiteboardObj.get(2).toString();

        // log.debug("***** sendVars: " + actionObject.get(0));

        if (action != null && action.equals("whiteboardObj")) {
            // Update Whiteboard Object
            List actionObject = (List) whiteboardObj.get(3);
            WhiteboardManagement.getInstance().updateWhiteboardObject(room_id, actionObject);
        } else if (action != null && action.equals("moveMap")) {
            // Update Whiteboard Object
            List actionObject = (List) whiteboardObj.get(3);
            WhiteboardManagement.getInstance().updateWhiteboardObjectPos(room_id, actionObject);
        } else {
            // Store event in list
            WhiteboardManagement.getInstance().addWhiteBoardObject(room_id, whiteboardObj);
        }

        boolean showDrawStatus = getWhiteboardDrawStatus();

        // Notify all Clients of that Scope (Room)
        Collection<Set<IConnection>> conCollection = current.getScope().getConnections();
        for (Set<IConnection> conset : conCollection) {
            for (IConnection conn : conset) {
                if (conn != null) {
                    if (conn instanceof IServiceCapableConnection) {

                        if (conn.getClient().getId().equals(current.getClient().getId())) {
                            continue;
                        }

                        RoomClient rcl = this.clientListManager
                                .getSyncClientByStreamId(conn.getClient().getId());

                        if (rcl == null) {
                            continue;
                        }

                        if (!currentClient.getStreamid().equals(rcl.getStreamid())) {
                            ((IServiceCapableConnection) conn).invoke("sendVarsToWhiteboard",
                                    new Object[] { (showDrawStatus ? currentClient : null), whiteboardObj },
                                    this);
                        }
                    }
                }
            }
        }

    } catch (Exception err) {
        log.error("[sendVars]", err);
    }
}

From source file:com.mysql.stresstool.RunnableQueryInsertPCH.java

public void run() {

    BufferedReader d = null;//from  w  w w .j av a 2s .com
    Connection conn = null;

    if (conn == null) {

        try {
            long execTime = 0;
            int pkStart = 0;
            int pkEnds = 0;
            int intDeleteInterval = 0;
            int intBlobInterval = 0;
            int intBlobIntervalLimit = StressTool.getNumberFromRandom(4).intValue();
            ThreadInfo thInfo;

            long threadTimeStart = System.currentTimeMillis();
            active = true;

            thInfo = new ThreadInfo();
            thInfo.setId(this.ID);
            thInfo.setType("insert");
            thInfo.setStatusActive(this.isActive());

            StressTool.setInfo(this.ID, thInfo);
            boolean lazy = false;
            int lazyInterval = 0;

            for (int repeat = 0; repeat <= repeatNumber; repeat++) {

                try {
                    if (conn != null && !conn.isClosed()) {
                        conn.close();
                    }
                    SoftReference sf = new SoftReference(
                            DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl")));
                    conn = (Connection) sf.get();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
                Statement stmt = null;
                //                ResultSet rs = null;
                //                ResultSet rs2 = null;

                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                stmt.execute("SET AUTOCOMMIT=0");
                ResultSet rs = null;
                int ServerId = 0;
                String query = null;
                ArrayList insert1 = null;
                ArrayList insert2 = null;
                int pk = 0;

                {
                    SoftReference sf = new SoftReference(
                            stmt.executeQuery("show global variables like 'SERVER_ID'"));
                    rs = (ResultSet) sf.get();
                }
                rs.next();
                ServerId = rs.getInt(2);

                if (repeat > 0 && lazyInterval < 500) {
                    lazy = true;
                    ++lazyInterval;
                } else {
                    lazy = false;
                    lazyInterval = 0;
                }

                intBlobInterval = StressTool.getNumberFromRandom(10).intValue();
                //               intBlobInterval++;
                //IMPLEMENTING lazy

                Vector v = null;
                {
                    SoftReference sf = new SoftReference(this.getTablesValues(lazy, ServerId));
                    v = (Vector) sf.get();
                }
                insert1 = (ArrayList<String>) v.get(0);
                insert2 = (ArrayList<String>) v.get(1);

                //                    System.out.println(insert1);
                //                    System.out.println(insert2);

                //                    pk = ((Integer) v.get(2)).intValue();

                int[] iLine = { 0, 0 };

                //                    pkStart = StressTool.getNumberFromRandom(2147483647).intValue();
                //                    pkEnds = StressTool.getNumberFromRandom(2147483647).intValue();

                try {

                    long timeStart = System.currentTimeMillis();

                    if (this.ignoreBinlog)
                        stmt.execute("SET sql_log_bin=0");
                    stmt.execute("SET GLOBAL max_allowed_packet=10737418");

                    if (dbType.equals("MySQL") && !engine.toUpperCase().equals("BRIGHTHOUSE"))
                        stmt.execute("BEGIN");
                    else
                        stmt.execute("COMMIT");
                    //                                stmt.execute("SET TRANSACTION NAME 'TEST'");
                    {
                        Iterator<String> it = insert1.iterator();
                        while (it.hasNext()) {
                            stmt.addBatch(it.next());
                        }
                    }

                    if (!this.doSimplePk) {
                        //                      System.out.println("Blob insert value :" + intBlobInterval);
                        if (intBlobInterval > intBlobIntervalLimit) {
                            Iterator<String> it = insert2.iterator();
                            while (it.hasNext()) {
                                stmt.addBatch(it.next());
                            }
                            //                        intBlobInterval=0;

                        }
                    }

                    iLine = stmt.executeBatch();
                    stmt.clearBatch();
                    //                            System.out.println("Query1 = " + insert1);
                    //                            System.out.println("Query2 = " + insert2);
                    //                            stmt.execute("START TRANSACTION");
                    //                            stmt.execute(insert1);
                    //                            iLine = stmt.executeBatch();
                    //                            conn.commit();
                    long timeEnds = System.currentTimeMillis();
                    execTime = (timeEnds - timeStart);

                } catch (Exception sqle) {
                    conn.rollback();
                    if (StressTool.getErrorLogHandler() != null) {
                        StressTool.getErrorLogHandler().appendToFile(("FAILED QUERY1==" + insert1));
                        StressTool.getErrorLogHandler().appendToFile(("FAILED QUERY2==" + insert2));
                        StressTool.getErrorLogHandler().appendToFile(sqle.toString());

                    } else {
                        sqle.printStackTrace();
                        System.out.println("FAILED QUERY1==" + insert1);
                        System.out.println("FAILED QUERY2==" + insert2);
                        sqle.printStackTrace();
                        System.exit(1);
                    }
                    //conn.close();
                    //this.setJdbcUrl(jdbcUrl);
                    //System.out.println("Query Insert TH RE-INIZIALIZING");

                } finally {
                    //                           conn.commit();
                    stmt.execute("COMMIT");
                    rs.close();
                    stmt.close();
                    rs = null;
                    stmt = null;

                    //                            intDeleteInterval++;
                    if (doLog) {

                        System.out.println("Query Insert TH = " + this.getID() + " Loop N = " + repeat + " "
                                + iLine[0] + "|" + ((iLine.length > 1) ? iLine[1] : 0) + " Exec Time(ms) ="
                                + execTime + " Running = " + repeat + " of " + repeatNumber + " to go ="
                                + (repeatNumber - repeat) + " Using Lazy=" + lazy);
                    }
                }
                thInfo.setExecutedLoops(repeat);
                if (sleepFor > 0 || this.getSleepWrite() > 0) {
                    if (this.getSleepWrite() > 0) {
                        Thread.sleep(getSleepWrite());
                    } else
                        Thread.sleep(sleepFor);
                }

                conn.close();
                conn = null;
            }

            long threadTimeEnd = System.currentTimeMillis();
            this.executionTime = (threadTimeEnd - threadTimeStart);
            //                this.setExecutionTime(executionTime);
            active = false;
            //                System.out.println("Query Insert TH = " + this.getID() + " COMPLETED!  TOTAL TIME = " + execTime + "(ms) Sec =" + (execTime/1000));

            thInfo.setExecutionTime(executionTime);
            thInfo.setStatusActive(false);
            StressTool.setInfo(this.ID, thInfo);
            return;

        } catch (Exception ex) {
            if (StressTool.getErrorLogHandler() != null) {
                StressTool.getErrorLogHandler().appendToFile(ex.toString() + "\n");
            } else
                ex.printStackTrace();

            try {
                conn.close();
                conn = null;
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                if (StressTool.getErrorLogHandler() != null) {
                    StressTool.getErrorLogHandler().appendToFile(e.toString() + "\n");
                    conn = null;
                } else
                    e.printStackTrace();
            }
        }

    }

}

From source file:eu.stork.peps.auth.engine.STORKSAMLEngine.java

/**
 * Generate assertion.//  w w w .j  a va 2s .  co m
 * 
 * @param ipAddress the IP address.
 * @param assertConsumerURL the assert consumer URL.
 * @param inResponseTo the in response to
 * @param issuer the issuer
 * @param notOnOrAfter the not on or after
 * 
 * @return the assertion
 * 
 * @throws STORKSAMLEngineException the STORKSAML engine exception
 */
private Assertion generateAssertion(final String ipAddress, final String assertConsumerURL,
        final String inResponseTo, final String issuer, final DateTime notOnOrAfter)
        throws STORKSAMLEngineException {
    LOG.info("Generate Assertion.");

    // Mandatory STORK
    LOG.debug("Generate Issuer to Assertion");
    final Issuer issuerAssertion = SAMLEngineUtils.generateIssuer();
    issuerAssertion.setValue(super.getSamlCoreProperties().getResponder());

    // Format Entity Optional STORK
    issuerAssertion.setFormat(super.getSamlCoreProperties().getFormatEntity());

    final Assertion assertion = SAMLEngineUtils.generateAssertion(SAMLVersion.VERSION_20,
            SAMLEngineUtils.generateNCName(), SAMLEngineUtils.getCurrentTime(), issuerAssertion);

    final Subject subject = SAMLEngineUtils.generateSubject();

    // Mandatory STORK verified
    // String format = NameID.UNSPECIFIED
    // specification: 'SAML:2.0' exist
    // opensaml: "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
    // opensaml  "urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified"
    final String format = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified";

    final String nameQualifier = "";

    LOG.debug("Generate NameID");
    final NameID nameId = SAMLEngineUtils.generateNameID(super.getSamlCoreProperties().getResponder(), format,
            nameQualifier);
    nameId.setValue(format);
    subject.setNameID(nameId);

    // Mandatory if urn:oasis:names:tc:SAML:2.0:cm:bearer.
    // Optional in other case.
    LOG.debug("Generate SubjectConfirmationData.");
    final SubjectConfirmationData dataBearer = SAMLEngineUtils
            .generateSubjectConfirmationData(SAMLEngineUtils.getCurrentTime(), assertConsumerURL, inResponseTo);

    // Mandatory if urn:oasis:names:tc:SAML:2.0:cm:bearer.
    // Optional in other case.
    LOG.debug("Generate SubjectConfirmation");
    final SubjectConfirmation subjectConf = SAMLEngineUtils
            .generateSubjectConfirmation(SubjectConfirmation.METHOD_BEARER, dataBearer);

    final ArrayList<SubjectConfirmation> listSubjectConf = new ArrayList<SubjectConfirmation>();
    listSubjectConf.add(subjectConf);

    for (final Iterator<SubjectConfirmation> iter = listSubjectConf.iterator(); iter.hasNext();) {
        final SubjectConfirmation element = iter.next();

        if (SubjectConfirmation.METHOD_BEARER.equals(element.getMethod())) {
            // ipAddress Mandatory if method is Bearer.

            if (StringUtils.isBlank(ipAddress)) {
                throw new STORKSAMLEngineException("ipAddress is null or empty");
            }
            element.getSubjectConfirmationData().setAddress(ipAddress.trim());
        }

        element.getSubjectConfirmationData().setRecipient(assertConsumerURL);
        element.getSubjectConfirmationData().setNotOnOrAfter(notOnOrAfter);
    }

    // The SAML 2.0 specification allows multiple SubjectConfirmations
    subject.getSubjectConfirmations().addAll(listSubjectConf);

    // Mandatory Stork
    assertion.setSubject(subject);

    // Conditions that MUST be evaluated when assessing the validity of
    // and/or when using the assertion.
    final Conditions conditions = this.generateConditions(SAMLEngineUtils.getCurrentTime(), notOnOrAfter,
            issuer);

    assertion.setConditions(conditions);

    LOG.debug("Generate stork Authentication Statement.");
    final AuthnStatement storkAuthnStat = this.generateStorkAuthStatement(ipAddress);
    assertion.getAuthnStatements().add(storkAuthnStat);

    return assertion;
}

From source file:com.aol.framework.helper.report.CustomizedReporter.java

synchronized private void generateModuleTestMethodSummary(String testName, String modulename,
        List<ISuite> suites, String fileName, ArrayList<ITestNGMethod> testngMethods, String nodeIp)
        throws IOException {
    final PrintWriter pw = TestHelper.createFileWriter(TestHelper.customReportDir + fileName);

    startHtmlPage(pw);/*from   ww w  .  j a v  a2 s  .c  om*/

    String htmlFile = testName + "-customized-report.html";
    String modulewiseTestFileName = testName + "-" + modulename + "-customized-report.html";

    pw.println("<button class=\"sexybutton sexysimple sexylarge sexyblack\" onClick=\"location.href='"
            + htmlFile + "'\"><span class=\"prev\">Back to Modulewise Execution Summary</span></button>");
    pw.println("<br/><br/><br/><fieldset><legend><b>Details</b></legend><br/>"
            + "<table class=\"details\" cellspacing=0 cellpadding=0><tr><td><b>Test Name: </b></td><td>"
            + testName + "</td></tr>");
    pw.println("<tr><td><b>Module Name: </b></td><td>" + modulename + "</td></tr>");
    pw.println("<tr><td><b>Node IP: </b></td><td>" + nodeIp + "</td></tr></table></fieldset><br/><br/>");

    pw.println("<table id=\"myTable\" width=\"100%\" cellspacing=0 cellpadding=0 class=\"tablesorter\">");
    pw.println("<thead><tr><th  style=\"text-align:left\">Method Name</th>" + "<th>Total Time (ms)</th>"
            + "<th>Status</th>"
            + "<th style=\"text-align:center\">Stack Trace | Test Parameters</th></tr></thead>");

    for (ISuite suite : suites) {
        Map<String, ISuiteResult> tests = suite.getResults();
        for (ISuiteResult re : tests.values()) {
            ITestContext overview = re.getTestContext();
            if ((overview.getName()).equalsIgnoreCase(testName)) {
                Iterator<ITestNGMethod> it = testngMethods.iterator();
                while (it.hasNext()) {
                    ITestNGMethod method = it.next();
                    String[] allGroups = method.getGroups();

                    String methodName = "";
                    //String className = "";

                    for (String grp : allGroups) {
                        if (grp.equalsIgnoreCase(modulename)) {
                            methodName = method.getMethodName();
                            //className = method.getTestClass().getName();

                            ArrayList<Set<ITestResult>> statusResult = new ArrayList<Set<ITestResult>>();

                            Set<ITestResult> failedTestAutomationStatus = overview
                                    .getFailedButWithinSuccessPercentageTests().getResults(method);
                            if (!(failedTestAutomationStatus.isEmpty())) {
                                statusResult.add(setTestStatus(failedTestAutomationStatus,
                                        ITestResult.SUCCESS_PERCENTAGE_FAILURE));
                            }

                            //TODO -- these 2 sets are somehow missing from the report, not sure they are attached
                            // with @test method or @BeforeMethod, so could be commented out if they are always empty
                            Set<ITestResult> confFailedTestStatus = overview.getFailedConfigurations()
                                    .getResults(method);
                            if (!(confFailedTestStatus.isEmpty())) {
                                statusResult.add(setTestStatus(confFailedTestStatus,
                                        ITestResult.SUCCESS_PERCENTAGE_FAILURE));
                            }
                            Set<ITestResult> confSkippedTestStatus = overview.getSkippedConfigurations()
                                    .getResults(method);
                            if (!(confSkippedTestStatus.isEmpty())) {
                                statusResult.add(setTestStatus(confSkippedTestStatus, ITestResult.SKIP));
                            }
                            // ***************************************************************************************************

                            Set<ITestResult> skippedTestStatus = overview.getSkippedTests().getResults(method);
                            if (!(skippedTestStatus.isEmpty())) {
                                statusResult.add(setTestStatus(skippedTestStatus, ITestResult.SKIP));
                            }

                            Set<ITestResult> passedTestStatus = overview.getPassedTests().getResults(method);
                            if (!(passedTestStatus.isEmpty())) {
                                statusResult.add(setTestStatus(passedTestStatus, ITestResult.SUCCESS));
                            }
                            Set<ITestResult> failedTestStatus = overview.getFailedTests().getResults(method);
                            if (!(failedTestStatus.isEmpty())) {
                                statusResult.add(setTestStatus(failedTestStatus, ITestResult.FAILURE));
                            }

                            if (methodName == null || methodName.trim() == "") {
                                methodName = " Empty ?";
                            }

                            // ________________________________________________________
                            String test_tag = "";
                            pw.print("<tr><td  style=\"text-align:left\" colspan=\"3\"><b>"
                                    + methodName.toUpperCase() + "</b>");

                            pw.println("" + "</td>" + "<td bgcolor=\"white\" style=\"border: 0px;\"></td>"
                                    + "</tr>");

                            Iterator<Set<ITestResult>> statusIterator = statusResult.iterator();

                            while (statusIterator.hasNext()) {
                                Set<ITestResult> status = statusIterator.next();

                                StringBuilder stackTrace;
                                StringBuilder failedConf;

                                Iterator<ITestResult> it2 = status.iterator();

                                List<String> msgs = new ArrayList<String>();

                                String executionStatus = "";

                                long time_start = Long.MAX_VALUE;
                                long time_end = Long.MIN_VALUE;

                                Throwable exception = null;
                                String screenshotFileLink = "";
                                String currentTestUrl = "";
                                String jsError = "";

                                ITestResult result = null;

                                while (it2.hasNext()) {

                                    //                                        pw.println("<tr><td  style=\"text-align:left\"><b>"
                                    //                                                + methodName.toUpperCase() + "</b></td>");

                                    stackTrace = new StringBuilder();
                                    failedConf = new StringBuilder();

                                    result = it2.next();

                                    time_start = result.getStartMillis();
                                    time_end = result.getEndMillis();
                                    Object[] params = result.getParameters();
                                    //                                        
                                    //                                        if(test_tag.equals("")){
                                    //                                           test_tag = getTestTag(params);
                                    //                                           if(status.size()==1){
                                    //                                           pw.println( " ["+test_tag+"]"
                                    //                                        +"</td>"
                                    //                                        + "<td bgcolor=\"white\" style=\"border: 0px;\"></td>"
                                    //                                                + "</tr>");
                                    //                                           }else {
                                    //                                               pw.println( ""
                                    //                                                       +"</td>"
                                    //                                                       + "<td bgcolor=\"white\" style=\"border: 0px;\"></td>"
                                    //                                                               + "</tr>");
                                    //                                           }
                                    //                                        }

                                    // String test_para = getTestPara(params,status.size()>1?0:1);
                                    String test_para = getTestPara(params, 0);
                                    int execStatus = result.getStatus();
                                    if (execStatus == ITestResult.SUCCESS) {
                                        executionStatus = "PASS";
                                    } else if (execStatus == ITestResult.FAILURE) {
                                        executionStatus = "FAIL";
                                    } else if (execStatus == ITestResult.SKIP) {
                                        executionStatus = "SKIP";
                                    } else if (execStatus == ITestResult.SUCCESS_PERCENTAGE_FAILURE) {
                                        executionStatus = "WARN";
                                    }

                                    //                                        if (execStatus == ITestResult.SKIP)
                                    //                                        {
                                    //                                            status = overview.getFailedConfigurations().getAllResults();
                                    //                                            it2 = status.iterator();
                                    //                                            failedConf.append("<br/>");
                                    //                                            while (it2.hasNext())
                                    //                                            {
                                    //                                                result = it2.next();
                                    //                                                failedConf.append("<b>Failed Configuration - "
                                    //                                                        + result.getMethod().getMethodName() + "</b>");
                                    //                                                failedConf.append("<br/>");
                                    //                                            }
                                    //                                            
                                    //                                            status = overview.getSkippedConfigurations().getAllResults();
                                    //                                            it2 = status.iterator();
                                    //                                            failedConf.append("<br/>");
                                    //                                            while (it2.hasNext())
                                    //                                            {
                                    //                                                result = it2.next();
                                    //                                                failedConf.append("<b>Skipped Configuration - "
                                    //                                                        + result.getMethod().getMethodName() + "</b>");
                                    //                                                failedConf.append("<br/>");
                                    //                                            }
                                    //                                            exception = result.getThrowable();
                                    //                                        } else
                                    {
                                        exception = result.getThrowable();
                                        if (exception == null) {
                                            if (execStatus == ITestResult.SKIP) {
                                                status = overview.getFailedConfigurations().getAllResults();
                                                it2 = status.iterator();
                                                failedConf.append("<br/>");
                                                while (it2.hasNext()) {
                                                    result = it2.next();
                                                    failedConf.append("<b>Failed Configuration - "
                                                            + result.getMethod().getMethodName() + "</b>");
                                                    failedConf.append("<br/>");
                                                }

                                                status = overview.getSkippedConfigurations().getAllResults();
                                                it2 = status.iterator();
                                                failedConf.append("<br/>");
                                                while (it2.hasNext()) {
                                                    result = it2.next();
                                                    failedConf.append("<b>Skipped Configuration - "
                                                            + result.getMethod().getMethodName() + "</b>");
                                                    failedConf.append("<br/>");
                                                }
                                                exception = result.getThrowable();
                                            }
                                        }
                                    }

                                    msgs = Reporter.getOutput(result);

                                    /*
                                     * If enable logs is false, then only
                                     * take the screenshot.
                                     */
                                    if (//(TestHelper.getTestConfig("ENABLE_LOGS_IN_CUSTOM_REPORT").equalsIgnoreCase("false")) && 
                                    (msgs != null)) {
                                        for (String line : msgs) {
                                            if (line.contains(TestHelper.jsErrorMarkerInOutputFile)) {
                                                jsError = line.substring(line
                                                        .indexOf(TestHelper.jsErrorMarkerInOutputFile)
                                                        + (TestHelper.jsErrorMarkerInOutputFile.length()),
                                                        line.length()).trim();
                                            }
                                            if (line.contains(TestHelper.testUrlMarkerInOutputFile)) {
                                                currentTestUrl = line.substring(line
                                                        .indexOf(TestHelper.testUrlMarkerInOutputFile)
                                                        + (TestHelper.testUrlMarkerInOutputFile.length()),
                                                        line.length());
                                            }

                                            if (line.contains(TestHelper.testScreenshotMarkerInOutputFile)) {
                                                screenshotFileLink = line.substring(line
                                                        .indexOf(TestHelper.testScreenshotMarkerInOutputFile)
                                                        + (TestHelper.testScreenshotMarkerInOutputFile
                                                                .length()),
                                                        line.length());
                                                break;
                                            }

                                        }
                                    }

                                    /*
                                     * If enable logs is true, take the
                                     * whole log along with screenshot.
                                     */
                                    if ((TestHelper.getTestConfig("ENABLE_LOGS_IN_CUSTOM_REPORT")
                                            .equalsIgnoreCase("true")) && (msgs != null)) {
                                        //                                            if(currentTestUrl!=null && currentTestUrl.trim().length()!=0){
                                        //                                            stackTrace
                                        //                                            .append("<br/><a target=\"_blank\" href=\""
                                        //                                                            + currentTestUrl
                                        //                                                            + "\"><u><b>URL</b></u> - "
                                        //                                                    + currentTestUrl
                                        //                                                    + "</a>");
                                        //                                            }    
                                        for (String line : msgs) {
                                            stackTrace.append("<br/>" + line);
                                        }
                                    } else if (screenshotFileLink != null
                                            && screenshotFileLink.trim().length() != 0) {

                                        stackTrace.append(
                                                "<br/><div id=\"screenshot-div\" style=\"cursor:pointer;color:blue;\"><u><b>Enlarge Screenshot</b></u> - "
                                                        + currentTestUrl + "</div><br/>"
                                                        // +(jsError.equals("")?jsError:"<b>JS Error:</b>"+jsError+"<br/>")
                                                        + "<a target=\"_blank\" href=\"" + screenshotFileLink
                                                        + "\"><b>View Screenshot in New Window/Tab</b></a><br/><br/><img id=\"screenshot\" src='"
                                                        + screenshotFileLink
                                                        + "' height='300' width='300' border=\"1\" style=\"position: relative; left: 0px;\"/>"
                                                        + (jsError.equals("") ? jsError
                                                                : "<br/><br/><b>JS Error:</b><br/>" + jsError
                                                                        + "<br/>"));
                                    }

                                    if (msgs != null) {
                                        msgs.clear();
                                    }

                                    Random randomGenerator = new Random();
                                    int randomInt = randomGenerator.nextInt(100000);

                                    String stackTraceFile = testName + "-" + modulename + "-" + methodName + "-"
                                            + randomInt + "-" + "custom-report.html";

                                    stackTrace.append("<br/>" + failedConf.toString());

                                    generateStackTraceReport(modulewiseTestFileName, stackTraceFile, stackTrace,
                                            exception, method, nodeIp, result);

                                    String link = "<button class=\"sexybutton sexysimple sexyblack\" onClick=\"location.href='"
                                            + stackTraceFile + "'\"><span class=\"info\">"
                                            + "View StackTrace/Screenshots" + "</span></button>";

                                    if (executionStatus.equalsIgnoreCase("pass")) {
                                        executionStatus = "<td bgcolor=\"" + passColor
                                                + "\"><font color=\"white\"><b>" + executionStatus
                                                + "</b></font></td>";
                                    } else if (executionStatus.equalsIgnoreCase("fail")) {
                                        executionStatus = "<td bgcolor=\"" + failColor
                                                + "\"><font color=\"white\"><b>" + executionStatus
                                                + "</b></font></td>";
                                    } else if (executionStatus.equalsIgnoreCase("warn")) {
                                        executionStatus = "<td bgcolor=\"" + warnColor
                                                + "\"><font color=\"white\"><b>" + executionStatus
                                                + "</b></font></td>";
                                    } else if (executionStatus.equalsIgnoreCase("skip")) {
                                        executionStatus = "<td bgcolor=\"" + skipColor
                                                + "\"><font color=\"white\"><b>" + executionStatus
                                                + "</b></font></td>";
                                    } else {
                                        executionStatus = "<td>" + executionStatus + "</td>";
                                    }

                                    pw.println(//"<tr><td style=\"text-align:left\">" + "[Class Name] " + className
                                            "<tr><td style=\"text-align:left\">" + "[Test Params] " + test_para
                                                    + "</td><td>" + (time_end - time_start) + "</td>"
                                                    + executionStatus
                                                    + "<td bgcolor=\"white\" style=\"text-align:center;border: 0px;\">"
                                                    + link + "</td></tr>");

                                    pw.flush();
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    pw.println("</table>");
    endHtmlPage(pw);
    pw.flush();
    pw.close();
}

From source file:com.xpn.xwiki.objects.classes.DBTreeListClass.java

/**
 * <p>//from  www . j  a  va2 s . co  m
 * Computes the query corresponding to the current XProperty. The query is either manually specified by the XClass
 * creator in the <tt>sql</tt> field, or, if the query field is blank, constructed using the <tt>classname</tt>,
 * <tt>idField</tt>, <tt>valueField</tt> and <tt>parentField</tt> properties. The query is constructed according to
 * the following rules:
 * </p>
 * <ul>
 * <li>If no classname, id and value fields are selected, return a query that return no rows, as the parent is not
 * enough to make a query.</li>
 * <li>If no parent field is provided, use the document "parent" medatada.</li>
 * <li>If only the classname is provided, select all document names which have an object of that type, preserving
 * the hierarchy defined by the parent field.</li>
 * <li>If only one of id and value is provided, use it for both columns.</li>
 * <li>If no classname is provided, assume the fields are document properties.</li>
 * <li>If the document is not used at all, don't put it in the query.</li>
 * <li>If the object is not used at all, don't put it in the query.</li>
 * </ul>
 * <p>
 * The generated query always selects 3 columns, the first one is used as the stored value, the second one as the
 * displayed value, and the third one defines the "parent" of the current value.
 * </p>
 * 
 * @param context The current {@link XWikiContext context}.
 * @return The HQL query corresponding to this property.
 */
@Override
public String getQuery(XWikiContext context) {
    // First, get the hql query entered by the user.
    String sql = getSql();
    // If the query field is blank, construct a query using the classname, idField,
    // valueField and parentField properties.
    if (StringUtils.isBlank(sql)) {
        if (context.getWiki().getHibernateStore() != null) {
            // Extract the 3 properties in non-null variables.
            String classname = StringUtils.defaultString(getClassname());
            String idField = StringUtils.defaultString(getIdField());
            String valueField = StringUtils.defaultString(getValueField());
            String parentField = StringUtils.defaultString(getParentField());

            // Check if the properties are specified or not.
            boolean hasClassname = !StringUtils.isBlank(classname);
            boolean hasIdField = !StringUtils.isBlank(idField);
            boolean hasValueField = !StringUtils.isBlank(valueField);
            boolean hasParentField = !StringUtils.isBlank(parentField);

            if (!(hasIdField || hasValueField)) {
                // If only the classname is specified, return a query that selects all the
                // document names which have an object of that type, and the hierarchy is
                // defined by the document "parent" property (unless a parent property is
                // specified).
                if (hasClassname) {
                    sql = "select distinct doc.fullName, doc.fullName, "
                            + (hasParentField ? parentField : "doc.parent")
                            + " from XWikiDocument as doc, BaseObject as obj"
                            + " where doc.fullName=obj.name and obj.className='" + classname + "'";
                } else {
                    // If none of the first 3 properties is specified, return a query that
                    // always returns no rows (only with the parent field no query can be made)
                    sql = DEFAULT_QUERY;
                }
                return sql;
            }

            // If only one of the id and value fields is specified, use it for both columns.
            if (!hasIdField && hasValueField) {
                idField = valueField;
            } else if (hasIdField && !hasValueField) {
                valueField = idField;
            }

            // If no parent field was specified, use the document "parent" metadata
            if (!hasParentField) {
                parentField = "doc.parent";
            }

            // Check if the document and object are needed or not.
            // The object is needed if there is a classname, or if at least one of the selected
            // columns is an object property.
            boolean usesObj = hasClassname || idField.startsWith("obj.") || valueField.startsWith("obj.")
                    || parentField.startsWith("obj.");
            // The document is needed if one of the selected columns is a document property, or
            // if there is no classname specified and at least one of the selected columns is
            // not an object property.
            boolean usesDoc = idField.startsWith("doc.") || valueField.startsWith("doc.")
                    || parentField.startsWith("doc.");
            if ((!idField.startsWith("obj.") || !valueField.startsWith("obj.")
                    || !parentField.startsWith("obj.")) && !hasClassname) {
                usesDoc = true;
            }

            // Build the query in this variable.
            StringBuffer select = new StringBuffer("select distinct ");
            // These will hold the components of the from and where parts of the query.
            ArrayList<String> fromStatements = new ArrayList<String>();
            ArrayList<String> whereStatements = new ArrayList<String>();

            // Add the document to the query only if it is needed.
            if (usesDoc) {
                fromStatements.add("XWikiDocument as doc");
                if (usesObj) {
                    whereStatements.add("doc.fullName=obj.name");
                }
            }
            // Add the object to the query only if it is needed.
            if (usesObj) {
                fromStatements.add("BaseObject as obj");
                if (hasClassname) {
                    whereStatements.add("obj.className='" + classname + "'");
                }
            }

            // Add the first column to the query.
            if (idField.startsWith("doc.") || idField.startsWith("obj.")) {
                select.append(idField);
            } else if (!hasClassname) {
                select.append("doc." + idField);
            } else {
                select.append("idprop.value");
                fromStatements.add("StringProperty as idprop");
                whereStatements.add("obj.id=idprop.id.id and idprop.id.name='" + idField + "'");
            }

            // Add the second column to the query.
            if (valueField.startsWith("doc.") || valueField.startsWith("obj.")) {
                select.append(", ").append(valueField);
            } else if (!hasClassname) {
                select.append(", doc." + valueField);
            } else {
                if (valueField.equals(idField)) {
                    select.append(", idprop.value");
                } else {
                    select.append(", valueprop.value");
                    fromStatements.add("StringProperty as valueprop");
                    whereStatements.add("obj.id=valueprop.id.id and valueprop.id.name='" + valueField + "'");
                }
            }

            // Add the third column to the query.
            if (parentField.startsWith("doc.") || parentField.startsWith("obj.")) {
                select.append(", ").append(parentField);
            } else if (!hasClassname) {
                select.append(", doc." + parentField);
            } else {
                if (parentField.equals(idField)) {
                    select.append(", idprop.value");
                } else if (parentField.equals(valueField)) {
                    select.append(", valueprop.value");
                } else {
                    select.append(", parentprop.value");
                    fromStatements.add("StringProperty as parentprop");
                    whereStatements.add("obj.id=parentprop.id.id and parentprop.id.name='" + parentField + "'");
                }
            }
            // Let's create the complete query
            select.append(" from ");
            select.append(StringUtils.join(fromStatements.iterator(), ", "));
            if (whereStatements.size() > 0) {
                select.append(" where ");
                select.append(StringUtils.join(whereStatements.iterator(), " and "));
            }
            sql = select.toString();
        } else {
            // TODO: query plugin impl.
            // We need to generate the right query for the query plugin
        }
    }
    // Parse the query, so that it can contain velocity scripts, for example to use the
    // current document name, or the current username.
    try {
        sql = context.getWiki().parseContent(sql, context);
    } catch (Exception e) {
        LOGGER.error("Failed to parse SQL script [" + sql + "]. Continuing with non-rendered script.", e);
    }
    return sql;
}

From source file:com.workplacesystems.utilsj.collections.TransactionalBidiTreeMap.java

/**
 * Removes all mappings from this map//from  w  w  w.j  a v a 2 s. co m
 */
@Override
public void clear() {

    if (auto_commit) {
        modify();

        nodeCount = 0;
        rootNode[KEY] = null;
        rootNode[VALUE] = null;
    } else {
        String thread_id = getCurrentThreadId();
        ArrayList<Entry<K, V>> list = new ArrayList<Entry<K, V>>(entrySet());
        for (Iterator<Entry<K, V>> i = list.iterator(); i.hasNext();) {
            Node<K, V> node = (Node<K, V>) i.next();
            if (node.is(Node.ADDED, thread_id))
                doRedBlackDelete(node);
            else {
                node.setStatus(Node.DELETED, thread_id);
            }
        }
    }
}

From source file:com.workplacesystems.utilsj.collections.TransactionalBidiTreeMap.java

/**
 * Commits the changes to the map so that all threads
 * see them.//from   w w  w .ja v a  2s.  c  om
 *
 * @param id the thread id to commit for, null commits
 *           all threads changes
 */
private void commit(final String id) {

    ArrayList<Entry<K, V>> list = new ArrayList<Entry<K, V>>(allEntrySet());
    for (Iterator<Entry<K, V>> i = list.iterator(); i.hasNext();) {
        final Node<K, V> node = (Node<K, V>) i.next();

        if (node.is(Node.DELETED, id)) {
            doRedBlackDelete(node);
            if (commit_notifiers != null) {
                SyncUtils.synchronizeRead(commit_notifiers, new Callback() {
                    @Override
                    protected void doAction() {
                        for (Iterator i2 = commit_notifiers.iterator(); i2.hasNext();)
                            ((TransactionNotifiable) i2.next()).removedFromMap(node.getKey(), node.getValue());
                    }
                });
            }

        }

        if (node.is(Node.ADDED, id)) {
            node.setStatus(Node.NO_CHANGE, null);
            if (commit_notifiers != null) {
                SyncUtils.synchronizeRead(commit_notifiers, new Callback() {
                    @Override
                    protected void doAction() {
                        for (Iterator i2 = commit_notifiers.iterator(); i2.hasNext();)
                            ((TransactionNotifiable) i2.next()).addedToMap(node.getKey(), node.getValue());
                    }
                });
            }
        }
    }
}

From source file:com.workplacesystems.utilsj.collections.TransactionalBidiTreeMap.java

/**
 * Rolls back the changes to the map./*w  w  w .  j ava 2s  . co  m*/
 */
public void rollback() {

    if (auto_commit)
        return;

    String id = getCurrentThreadId();

    ArrayList<Entry<K, V>> list = new ArrayList<Entry<K, V>>(allEntrySet());
    for (Iterator<Entry<K, V>> i = list.iterator(); i.hasNext();) {
        final Node<K, V> node = (Node<K, V>) i.next();

        if (node.is(Node.ADDED, id)) {
            doRedBlackDelete(node);
            if (rollback_notifiers != null) {
                SyncUtils.synchronizeRead(rollback_notifiers, new Callback() {
                    @Override
                    protected void doAction() {
                        for (Iterator i2 = rollback_notifiers.iterator(); i2.hasNext();)
                            ((TransactionNotifiable) i2.next()).removedFromMap(node.getKey(), node.getValue());
                    }
                });
            }
        }

        if (node.is(Node.DELETED, id)) {
            node.setStatus(Node.NO_CHANGE, null);
            if (rollback_notifiers != null) {
                SyncUtils.synchronizeRead(rollback_notifiers, new Callback() {
                    @Override
                    protected void doAction() {
                        for (Iterator i2 = rollback_notifiers.iterator(); i2.hasNext();)
                            ((TransactionNotifiable) i2.next()).addedToMap(node.getKey(), node.getValue());
                    }
                });
            }
        }
    }
}

From source file:com.planetmayo.debrief.satc_rcp.views.MaintainContributionsView.java

private void addNewPerformanceScore(double value, List<CompositeRoute> topRoutes) {
    // remember each contribution's set of scores
    HashMap<BaseContribution, HashMap<Date, Double>> stackedSeries = new HashMap<BaseContribution, HashMap<Date, Double>>();

    // remember the times for which we have states
    ArrayList<Date> valueTimes = new ArrayList<Date>();

    // ok - have a look at the scores
    Iterator<CoreRoute> legIter = topRoutes.get(0).getLegs().iterator();
    while (legIter.hasNext()) {
        CoreRoute route = legIter.next();
        Iterator<State> states = route.getStates().iterator();
        while (states.hasNext()) {
            State state = states.next();
            HashMap<BaseContribution, Double> scores = state.getScores();
            Iterator<BaseContribution> contributions = scores.keySet().iterator();
            while (contributions.hasNext()) {
                BaseContribution cont = contributions.next();

                // get the score
                Double score = scores.get(cont);
                if (score > 0) {

                    HashMap<Date, Double> thisSeries = stackedSeries.get(cont);
                    if (thisSeries == null) {
                        thisSeries = new HashMap<Date, Double>();
                        stackedSeries.put(cont, thisSeries);
                        final IBarSeries series = (IBarSeries) performanceChart.getSeriesSet()
                                .createSeries(SeriesType.BAR, cont.getName());
                        series.setBarColor(colorFor(cont));
                        // series.enableStack(true);
                    }/*from  w  w w. j a v  a 2s  . co m*/
                    thisSeries.put(state.getTime(), scores.get(cont));

                    // store the time of this value
                    if (!valueTimes.contains(state.getTime())) {
                        valueTimes.add(state.getTime());
                    }
                }
            }
        }
    }

    // ok, now loop through the series
    Iterator<BaseContribution> conts = stackedSeries.keySet().iterator();
    while (conts.hasNext()) {
        BaseContribution cont = conts.next();
        HashMap<Date, Double> vals = stackedSeries.get(cont);
        if (vals.size() > 0) {
            final IBarSeries series = (IBarSeries) performanceChart.getSeriesSet().getSeries(cont.getName());

            // ok, we need to produce a value for each value time
            double[] valArr = new double[valueTimes.size()];

            Iterator<Date> iter2 = valueTimes.iterator();
            int ctr = 0;
            while (iter2.hasNext()) {
                Date date = iter2.next();
                Double thisV = vals.get(date);
                final double res;
                if (thisV != null)
                    res = thisV;
                else
                    res = 0;

                valArr[ctr++] = res;
            }

            series.setYSeries(valArr);
            // series.enableStack(true);
        }
    }

    // prepare the category labels
    String[] labels = new String[valueTimes.size()];
    Iterator<Date> vIter = valueTimes.iterator();

    // get our date formatter ready
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

    // determine frequency f (trim to 1)
    int wid = performanceChart.getBounds().width;
    int allowed = wid / 90;
    int freq = Math.max(labels.length / allowed, 1);

    int ctr = 0;
    while (vIter.hasNext()) {
        Date date = vIter.next();
        final String str;
        if (ctr % freq == 0)
            str = sdf.format(date);
        else
            str = "";
        labels[ctr++] = str;
    }

    // set category labels
    performanceChart.getAxisSet().getXAxis(0).enableCategory(true);
    performanceChart.getAxisSet().getXAxis(0).setCategorySeries(labels);

    ISeries[] series = performanceChart.getSeriesSet().getSeries();
    if (series.length == 2 && series[0] instanceof IBarSeries && series[1] instanceof IBarSeries) {
        performanceChart.getLegend().setVisible(true);
        performanceChart.getLegend().setPosition(SWT.RIGHT);
        IBarSeries barSeries1 = (IBarSeries) series[0];
        IBarSeries barSeries2 = (IBarSeries) series[1];
        // enable stack series
        barSeries1.enableStack(false);
        barSeries2.enableStack(false);
        barSeries1.enableStack(true);
        barSeries2.enableStack(true);

    }

    // and resize the axes
    performanceChart.getAxisSet().adjustRange();

    final String perfString;
    if (value > 200d)
        perfString = "Unachievable";
    else
        perfString = PERFORMANCE_TITLE + (int) value;

    performanceChart.getTitle().setText(perfString);

    //
    performanceChart.redraw();
}