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:org.openmeetings.app.remote.red5.ScopeApplicationAdapter.java

/**
 * This Function is triggered from the Whiteboard
 * /*from  ww  w .j a va2  s. co  m*/
 * @param whiteboardObj
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public synchronized void sendVarsByWhiteboardId(ArrayList whiteboardObjParam, Long whiteboardId) {
    //
    try {

        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++;
        }

        // 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();

        // log.debug("***** sendVars: " + whiteboardObj);

        // Store event in list
        String action = whiteboardObj.get(2).toString();

        if (action.equals("deleteMindMapNodes")) {

            // Simulate Single Delete Events for z-Index
            List actionObject = (List) whiteboardObj.get(3);

            List<List> itemObjects = (List) actionObject.get(3);

            Map whiteboardTempObj = new HashMap();
            whiteboardTempObj.put(2, "delete");

            for (List itemObject : itemObjects) {

                List<Object> tempActionObject = new LinkedList<Object>();
                tempActionObject.add("mindmapnode");
                tempActionObject.add(itemObject.get(0)); // z-Index -8
                tempActionObject.add(null); // simulate -7
                tempActionObject.add(null); // simulate -6
                tempActionObject.add(null); // simulate -5
                tempActionObject.add(null); // simulate -4
                tempActionObject.add(null); // simulate -3
                tempActionObject.add(null); // simulate -2
                tempActionObject.add(itemObject.get(1)); // Object-Name -1

                whiteboardTempObj.put(3, tempActionObject);

                WhiteboardManagement.getInstance().addWhiteBoardObjectById(room_id, whiteboardTempObj,
                        whiteboardId);

            }

        } else {

            WhiteboardManagement.getInstance().addWhiteBoardObjectById(room_id, whiteboardObj, whiteboardId);

        }

        // This is no longer necessary
        // boolean ismod = currentClient.getIsMod();

        // log.debug("*..*ismod: " + ismod);

        // if (ismod) {

        Map<String, Object> sendObject = new HashMap<String, Object>();
        sendObject.put("id", whiteboardId);
        sendObject.put("param", whiteboardObjParam);

        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("sendVarsToWhiteboardById",
                                    new Object[] { showDrawStatus ? currentClient : null, sendObject }, this);
                        }
                    }
                }
            }
        }

        // return numberOfUsers;
        // } else {
        // // log.debug("*..*you are not allowed to send: "+ismod);
        // return -1;
        // }
    } catch (Exception err) {
        log.error("[sendVarsByWhiteboardId]", err);
    }
}

From source file:core.client.impl.ConditionalWriterImpl.java

public Iterator<Result> write(Iterator<ConditionalMutation> mutations) {

    try {/*w w w  .  ja v a2 s.c o  m*/
        Scanner scanner = conn.createScanner(table, auths);
        BatchWriter bw = conn.createBatchWriter(table, new BatchWriterConfig());

        ArrayList<Result> results = new ArrayList<Result>();

        mloop: while (mutations.hasNext()) {
            ConditionalMutation cm = mutations.next();

            byte[] row = cm.getRow();
            RowLock rowLock = getRowLock(row);
            rowLock.lock();
            try {

                List<Condition> conditions = cm.getConditions();

                for (Condition cc : conditions) {

                    if (!isVisible(cc.getVisibility())) {
                        results.add(new Result(Status.INVISIBLE_VISIBILITY, cm));
                        continue mloop;
                    }

                    scanner.clearColumns();

                    if (cc.getTimestamp() == null) {
                        scanner.setRange(Range.exact(new Text(row), new Text(cc.getFamily().toArray()),
                                new Text(cc.getQualifier().toArray()), new Text(cc.getVisibility().toArray())));
                    } else {
                        scanner.setRange(Range.exact(new Text(row), new Text(cc.getFamily().toArray()),
                                new Text(cc.getQualifier().toArray()), new Text(cc.getVisibility().toArray()),
                                cc.getTimestamp()));
                    }

                    scanner.clearScanIterators();
                    for (IteratorSetting is : cc.getIterators()) {
                        scanner.addScanIterator(is);
                    }

                    Value val = null;

                    for (Entry<Key, Value> entry : scanner) {
                        val = entry.getValue();
                        break;
                    }

                    // TODO check key == condition columns

                    if ((val == null ^ cc.getValue() == null)
                            || (val != null && !cc.getValue().equals(new ArrayByteSequence(val.get())))) {
                        results.add(new Result(Status.REJECTED, cm));
                        continue mloop;
                    }
                }

                try {
                    bw.addMutation(cm);
                    bw.close();
                    results.add(new Result(Status.ACCEPTED, cm));
                } catch (MutationsRejectedException mre) {
                    results.add(new Result(Status.VIOLATED, cm));
                    continue mloop;
                } finally {
                    bw.close();
                    bw = conn.createBatchWriter(table, new BatchWriterConfig());
                }
            } finally {
                rowLock.unlock();
                returnRowLock(rowLock);
            }
        }

        bw.close();

        return results.iterator();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

public void run() {

    BufferedReader d = null;// w  w w  . ja  v a 2  s  . com
    Connection conn = null;

    try {
        if (stikyconnection && jdbcUrlMap.get("dbType") != null
                && !((String) jdbcUrlMap.get("dbType")).equals("MySQL")) {
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("dbType"), "test", "test");
        } else if (stikyconnection)
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl"));

    } catch (SQLException ex) {
        ex.printStackTrace();
    }

    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++) {
            if (!stikyconnection) {
                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) {
                    for (int icon = 0; icon <= 3; icon++) {
                        try {
                            Thread.sleep(10000);
                            SoftReference sf = new SoftReference(
                                    DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl")));
                            conn = (Connection) sf.get();
                        } catch (SQLException ex2) {
                            ex2.printStackTrace();
                        }
                    }
                    //ex.printStackTrace();
                }

            }
            if (conn != null) {
                Statement stmt = null;
                //                ResultSet rs = null;
                //                ResultSet rs2 = null;

                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                stmt.execute("SET AUTOCOMMIT=0");

                String query = null;
                ArrayList insert1 = null;
                ArrayList insert2 = null;
                int pk = 0;

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

                intBlobInterval++;
                //IMPLEMENTING lazy
                Vector v = this.getTablesValues(lazy);

                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=1073741824");

                    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) {
                        if (intBlobInterval > intBlobIntervalLimit) {
                            Iterator<String> it = insert2.iterator();
                            while (it.hasNext()) {
                                stmt.addBatch(it.next());
                            }
                            intBlobInterval = 0;

                        }
                    }
                    if (debug) {
                        System.out.println("Thread " + thInfo.getId() + " Executing loop "
                                + thInfo.getExecutedLoops() + " QUERY1==" + insert1);
                        System.out.println("Thread " + thInfo.getId() + " Executing loop "
                                + thInfo.getExecutedLoops() + " QUERY2==" + insert2);

                    }

                    iLine = executeSQL(stmt);
                    //                            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 (SQLException sqle) {

                    conn.rollback();
                    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();
                    if (conn != null && !conn.isClosed()) {
                        try {
                            stmt.addBatch("COMMIT");
                            executeSQL(stmt);
                        } catch (SQLException sqle) {
                            System.out.println(
                                    "#####################\n[Warning] Cannot explicitly commit given error\n#################");
                            conn.close();
                            continue;
                        }
                    } else {
                        System.out.println(
                                "#####################\n[Warning] Cannot explicitly commit given connection was interrupted unexpectedly\n#################");
                    }
                    //                            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);
                }

            }
        }

        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) {
        ex.printStackTrace();
        try {
            conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:com.funambol.json.api.dao.AlternateJsonApiDao.java

/**
 *  search for application defined equivalent items for a specified item.
 * @return/*w w  w . j a v  a  2 s  .co  m*/
 */
@Override
public String getSyncItemKeysFromTwin(String itemToGetTwins, String itemKeyExpected)
        throws JSONTestAPIDAOException {

    if (log.isInfoEnabled()) {
        log.info("Executing method: getSyncItemKeysFromTwin()");
    }

    try {
        String content = configLoader.getJSONFile(this.getSourceName(), this.getTestName(), itemToGetTwins);

        if (log.isTraceEnabled()) {
            log.trace("content:" + content);
        }
        String req = configLoader.getServerProperty(Def.SERVER_URI) + "/" + this.getSourceName()
                + "/keys/twins";
        JSONObject jsonForTwins = JSONObject.fromObject(content).getJSONObject("data");
        String contentType = jsonForTwins.getString("content-type");
        jsonForTwins = jsonForTwins.getJSONObject("item");

        ArrayList<NameValuePair> requestProps = new ArrayList<NameValuePair>();
        if (contentType != null) {
            if (contentType.equals(Def.CONTENT_CARD)) {
                if (jsonForTwins.containsKey(Def.TWIN_FIRSTNAME)) {
                    requestProps
                            .add(new NameValuePair("firstname", jsonForTwins.optString(Def.TWIN_FIRSTNAME)));
                }
                if (jsonForTwins.containsKey(Def.TWIN_LASTNAME)) {
                    requestProps.add(new NameValuePair("lastname", jsonForTwins.optString(Def.TWIN_LASTNAME)));
                }
                if (jsonForTwins.containsKey(Def.TWIN_EMAIL)) {
                    requestProps.add(new NameValuePair("email", jsonForTwins.optString(Def.TWIN_EMAIL)));
                }
                if (jsonForTwins.containsKey(Def.TWIN_COMPANY)) {
                    requestProps
                            .add(new NameValuePair(Def.TWIN_COMPANY, jsonForTwins.optString(Def.TWIN_COMPANY)));
                }
            } else if (contentType.equals(Def.CONTENT_APPOINTMENT)) {
                if (jsonForTwins.containsKey(Def.TWIN_SUBJECT)) {
                    requestProps
                            .add(new NameValuePair(Def.TWIN_SUBJECT, jsonForTwins.optString(Def.TWIN_SUBJECT)));
                }
                if (jsonForTwins.containsKey(Def.TWIN_STARTDATE)) {
                    requestProps.add(new NameValuePair("dtstart", jsonForTwins.optString(Def.TWIN_STARTDATE)));
                }
                if (jsonForTwins.containsKey(Def.TWIN_ENDDATE)) {
                    requestProps.add(new NameValuePair("dtend", jsonForTwins.optString(Def.TWIN_ENDDATE)));
                }
            } else if (contentType.equals(Def.CONTENT_TASK)) {
                if (jsonForTwins.containsKey(Def.TWIN_SUBJECT)) {
                    requestProps.add(new NameValuePair("subject", jsonForTwins.optString(Def.TWIN_SUBJECT)));
                }
                if (jsonForTwins.containsKey(Def.TWIN_STARTDATE)) {
                    requestProps.add(new NameValuePair("dstart", jsonForTwins.optString(Def.TWIN_STARTDATE)));
                }
                if (jsonForTwins.containsKey(Def.TWIN_DUEDATE)) {
                    requestProps.add(new NameValuePair("dtend", jsonForTwins.optString(Def.TWIN_DUEDATE)));
                }
            } else if (contentType.equals(Def.CONTENT_NOTE)) {
                if (jsonForTwins.containsKey(Def.TWIN_SUBJECT)) {
                    requestProps.add(new NameValuePair("subject", jsonForTwins.optString(Def.TWIN_SUBJECT)));
                }
            }
        }
        if (requestProps.size() > 0) {
            NameValuePair[] n = new NameValuePair[requestProps.size()];
            Iterator it = requestProps.iterator();
            int i = 0;
            while (it.hasNext()) {
                n[i] = (NameValuePair) it.next();
                i++;
            }
            String response = sendGetRequestWithNameValuePairs(req, n);
            if (log.isTraceEnabled()) {
                log.trace("RESPONSE twins : \n" + response);
            }
            JSONArray twinItems = JSONObject.fromObject(response).getJSONObject("data").getJSONArray("keys");
            String keyExpected = configLoader.getKeyFromFile(this.getSourceName(), this.getTestName(),
                    itemKeyExpected, false);
            if (!twinItems.contains(keyExpected)) {
                if (log.isInfoEnabled()) {
                    log.info("ERROR the expected twin:" + keyExpected + " does not exist");
                }
            }
            return response;
        }

    } catch (IOOperationException ex) {
        throw new JSONTestAPIDAOException("Error retrieving twin items " + ex);
    }
    return "";
}

From source file:de.juwimm.cms.remote.UserServiceSpringImpl.java

@Override
protected UserUnitsGroupsValue[] handleGetUserUnitsGroups4UnitAndGroup(Integer unitId, Integer groupId)
        throws Exception {
    Vector<UserUnitsGroupsValue> vec = new Vector<UserUnitsGroupsValue>();
    try {/*from  ww  w. ja v a 2  s.  c  o  m*/
        ArrayList<UserHbm> userList = new ArrayList<UserHbm>();

        UserHbm userLogged = super.getUserHbmDao().load(AuthenticationHelper.getUserName());
        if (!isUserInRole(userLogged.getUserId(), this.getActiveSiteId(), UserRights.SITE_ROOT)) {
            if (isUserInRole(userLogged.getUserId(), this.getActiveSiteId(), UserRights.UNIT_ADMIN)) {
                Iterator unitsIt = userLogged.getUnits().iterator();
                while (unitsIt.hasNext()) {
                    UnitHbm unit = (UnitHbm) unitsIt.next();
                    Collection users = unit.getUsers();
                    Iterator<UserHbm> userIt = users.iterator();
                    while (userIt.hasNext()) {
                        UserHbm current = userIt.next();
                        //not allowed to see user in higher roles than himself 
                        if (!isUserInRole(current.getUserId(), this.getActiveSiteId(), UserRights.SITE_ROOT)) {
                            userList.add(current);
                        }
                    }
                }
            }

        } else {
            if (unitId != null && unitId.intValue() > 0 && groupId != null && groupId.intValue() > 0) {
                userList.addAll(super.getUserHbmDao().findAll4UnitAndGroup(unitId, groupId));
            } else if (unitId != null && unitId.intValue() > 0) {
                userList.addAll(super.getUserHbmDao().findAll4Unit(unitId));
            } else if (groupId != null && groupId.intValue() > 0) {
                userList.addAll(super.getUserHbmDao().findAll4Group(groupId));
            } else {
                userList.addAll(super.getUserHbmDao().findAll(this.getActiveSiteId()));
            }
        }
        Iterator<UserHbm> it = userList.iterator();
        while (it.hasNext()) {
            UserHbm user = it.next();
            vec.add(getUserHbmDao().getUserUnitsGroupsValue(user));
            // vec.add(user.getUserUnitsGroupsValue());
        }
    } catch (Exception e) {
        throw new UserException(e.getMessage(), e);
    }
    return vec.toArray(new UserUnitsGroupsValue[0]);
}

From source file:com.clustercontrol.ping.factory.RunMonitorPing.java

/**
 *    fping???IP??????<BR>//ww w.ja v a  2 s. co m
 *  nodeMap?????public
 * 
 * @param hosts      fping???
 * @param message    
 * @param count      ping
 * @return (IP ??)??
 */
public Hashtable<String, PingResult> wrapUpFping(ArrayList<String> messages, int count, int version) {

    Hashtable<String, PingResult> ret = new Hashtable<String, PingResult>();
    HashMap<String, String> normalMap = new HashMap<String, String>(); //IP, 
    HashMap<String, String> aberrantMap = new HashMap<String, String>(); //IP, 
    HashSet<String> hostSet = new HashSet<String>();

    /**
     * ????????5?
     * ???
     * 
     **/
    String msg;
    String msgOrg;
    int lost;
    float average = 0;
    float reachRatio;

    //IP???

    Pattern patternIp;
    if (version == 6) {
        patternIp = Pattern.compile("^([0-9].*)|^(\\:\\:.*)");
    } else {
        patternIp = Pattern.compile("^([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}.*)");
    }

    //fping??
    Pattern patternSp = Pattern.compile("(\\s:\\s|\\s)+");
    //?
    Pattern patternNormal = Pattern.compile("([0-9]+\\.[0-9]+|-)");

    //IP
    Matcher matcherIp;
    Matcher matcherValue;

    String message;

    /*
     * fping???
     * ???                     127.0.0.1 : 0.10 1.23
     * ????                     127.0.0.1 : - -
     * ???(?IP???)         127.0.0.1 : duplicate for [0], xx bytes, x.xx ms
     * ???(GW??????)   127.0.0.1 : ()
     * ??
     * ????????????????????
     * 2????????????
     * ???????IP????????
     * ?????
     */

    /*
     * ?????
     */
    Iterator<String> itr = messages.iterator();
    m_log.debug("wrapUpFping(): start logic: " + messages.size());
    while (itr.hasNext()) {

        message = itr.next();
        m_log.debug("wrapUpFping(): checkpoint");

        //IP??????????
        boolean bValidIP = false;
        if (version == 6) {
            m_log.debug("wrapUpFping(): into IPv6 loop");
            String[] strs = message.split(" ");
            try {
                InetAddress.getByName(strs[0]);
                bValidIP = true;
            } catch (Exception e) {
                m_log.warn("wrapUpFping() invalid IPv6 adress: original message: " + message, e);
                m_log.warn("wrapUpFping() stack trace: " + e.getClass().getSimpleName() + ", " + e.getMessage(),
                        e);
            }
        } else {
            matcherIp = patternIp.matcher(message);
            if (matcherIp.matches()) {
                bValidIP = true;
            }
        }
        if (bValidIP) {

            //?IP????????
            String[] strs = patternSp.split(message);

            //?IP???
            boolean isNormal = true;
            for (int i = 1; i < strs.length; i++) {

                matcherValue = patternNormal.matcher(strs[i]);
                if (!matcherValue.matches()) {
                    isNormal = false;
                }
            }

            if (isNormal) {
                normalMap.put(strs[0], message);
                m_log.debug("wrapUpFping() : normalValue : " + message);
            } else {
                // ??IP???????
                if (aberrantMap.get(strs[0]) != null && !(aberrantMap.get(strs[0])).equals("")) {
                    String aberrantMessage = aberrantMap.get(strs[0]);
                    aberrantMessage = aberrantMessage + "\n" + message;
                    aberrantMap.put(strs[0], aberrantMessage);
                } else {
                    aberrantMap.put(strs[0], message);
                }
                m_log.debug("wrapUpFping() : aberrantValue : " + message);
            }

            hostSet.add(strs[0]);
        }
    }

    /*
     * ??????????
     */
    itr = hostSet.iterator();
    m_log.debug("wrapUpFping() : before into check result append loop");
    while (itr.hasNext()) {
        m_log.debug("wrapUpFping() : after into check result append loop");

        String host = itr.next();
        String normalMessage = normalMap.get(host);
        String aberrantMessage = aberrantMap.get(host);

        if (normalMessage != null && !normalMessage.equals("")) {

            // String ??
            String[] strs = patternSp.split(normalMessage);

            /*????????*/
            float max = 0; //(?0)
            float min = Float.MAX_VALUE; //?(?Float?)
            int num = 0; //?

            //????????
            for (int i = 1; i <= count; i++) {

                if (strs[i].equals("-")) {

                    //?-????????

                } else {

                    //?count up
                    num++;

                    //???
                    if (max < Float.parseFloat(strs[i])) {
                        max = Float.parseFloat(strs[i]);
                    }

                    //????
                    if (min > Float.parseFloat(strs[i])) {
                        min = Float.parseFloat(strs[i]);
                    }

                    //?
                    average += Float.parseFloat(strs[i]);
                }
            }

            //?????????????
            average /= num;

            /*
             * ???
             */

            StringBuffer buffer = new StringBuffer();
            buffer.append("Pinging " + host + " (" + host + ") .\n\n");

            // ??0??
            if (num == 0) {
                //??0??lost100 reach0
                lost = 100;
                reachRatio = 0;

                for (int i = 0; i < count; i++)
                    // buffer.append("From " + strs[0] + " icmp_seq="+ index +" Destination Host Unreachable");
                    buffer.append("Reply from " + host + " icmp_seq=" + i + " Destination Host Unreachable\n");

                buffer.append("\nPing statistics for " + host + ":\n");
                buffer.append("Packets: Sent = " + count + ", Received = " + num + ", Lost = " + (count - num)
                        + " (" + lost + "% loss),");

            } else {
                lost = (count - num) * 100 / count;
                reachRatio = (float) num * 100 / count;

                buffer.append("\nPing statistics for " + host + ":\n");
                buffer.append("Packets: Sent = " + count + ", Received = " + num + ", Lost = " + (count - num)
                        + " (" + lost + "% loss),");
                buffer.append("Approximate round trip times in milli-seconds:\n");
                buffer.append(
                        "\tMinimum = " + min + "ms, Maximum = " + max + "ms, Average = " + average + "ms\n");
            }

            // ?????msgOrg?
            if (aberrantMessage != null && !aberrantMessage.equals("")) {
                buffer.append("\n\n" + aberrantMessage + "\n");
            }

            msgOrg = buffer.toString();
            msg = "Packets: Sent = " + count + ", Received = " + num + ", Lost = " + (count - num) + " (" + lost
                    + "% loss)";

            PingResult res = new PingResult(host, msg, msgOrg, lost, average, reachRatio);

            ret.put(host, res);

            m_log.debug("wrapUpFping() : success msg = " + msg + ", msgOrg = " + msgOrg);

            msg = "";
            msgOrg = "";
            lost = 100;
            average = 0;
            reachRatio = 0;

        }
        // ??????
        else {

            msg = "Failed to get a value.";
            msgOrg = "Failed to get a value.";
            if (aberrantMessage != null && !aberrantMessage.equals("")) {
                msgOrg = msgOrg + "\n\n" + aberrantMessage;
            }

            PingResult res = new PingResult(host, msg, msgOrg, -1, -1, -1);

            ret.put(host, res);

            m_log.debug("wrapUpFping() : failure msg = " + msg + ", msgOrg = " + msgOrg);

            msg = "";
            msgOrg = "";
        }

    }

    return ret;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.RoomSiteViewerDispatchAction.java

public ActionForward roomViewer(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    User userView = getUserView(request);

    String roomName = request.getParameter("roomName");
    if (roomName == null) {
        roomName = (String) request.getAttribute("roomName");
    }/*w  w w. j  a  v  a2s  .  co m*/
    request.setAttribute("roomName", roomName);
    RoomKey roomKey = null;

    if (roomName != null) {
        roomKey = new RoomKey(roomName);

        ISiteComponent bodyComponent = new InfoSiteRoomTimeTable();
        DynaActionForm indexForm = (DynaActionForm) form;
        Integer indexWeek = (Integer) indexForm.get("indexWeek");
        // Integer executionPeriodID = (Integer)
        // indexForm.get("selectedExecutionPeriodID");
        String executionPeriodIDString = request.getParameter("selectedExecutionPeriodID");
        if (executionPeriodIDString == null) {
            executionPeriodIDString = (String) request.getAttribute("selectedExecutionPeriodID");
        }
        String executionPeriodID = (executionPeriodIDString != null) ? executionPeriodIDString : null;
        if (executionPeriodID == null) {
            try {
                // executionPeriodID = (Integer)
                // indexForm.get("selectedExecutionPeriodID");
                executionPeriodID = indexForm.get("selectedExecutionPeriodID").equals("") ? null
                        : (String) indexForm.get("selectedExecutionPeriodID");
            } catch (IllegalArgumentException ex) {
            }
        }
        Calendar today = new DateMidnight().toCalendar(null);
        ArrayList weeks = new ArrayList();

        InfoExecutionPeriod executionPeriod;
        if (executionPeriodID == null) {
            executionPeriod = ReadCurrentExecutionPeriod.run();
            executionPeriodID = executionPeriod.getExternalId();
            try {
                indexForm.set("selectedExecutionPeriodID", executionPeriod.getExternalId().toString());
            } catch (IllegalArgumentException ex) {
            }
        } else {
            executionPeriod = ReadExecutionPeriodByOID.run(executionPeriodID);
        }

        // weeks
        Calendar begin = Calendar.getInstance();
        begin.setTime(executionPeriod.getBeginDate());
        Calendar end = Calendar.getInstance();
        end.setTime(executionPeriod.getEndDate());
        ArrayList weeksLabelValueList = new ArrayList();
        begin.add(Calendar.DATE, Calendar.MONDAY - begin.get(Calendar.DAY_OF_WEEK));
        int i = 0;
        boolean selectedWeek = false;
        while (begin.before(end) || begin.before(Calendar.getInstance())) {
            Calendar day = Calendar.getInstance();
            day.setTimeInMillis(begin.getTimeInMillis());
            weeks.add(day);
            String beginWeekString = DateFormatUtils.format(begin.getTime(), "dd/MM/yyyy");
            begin.add(Calendar.DATE, 5);
            String endWeekString = DateFormatUtils.format(begin.getTime(), "dd/MM/yyyy");
            weeksLabelValueList.add(
                    new LabelValueBean(beginWeekString + " - " + endWeekString, new Integer(i).toString()));
            begin.add(Calendar.DATE, 2);
            if (!selectedWeek && indexWeek == null && Calendar.getInstance().before(begin)) {
                indexForm.set("indexWeek", new Integer(i));
                selectedWeek = true;
            }
            i++;
        }

        final Collection<ExecutionSemester> executionSemesters = rootDomainObject.getExecutionPeriodsSet();
        final List<LabelValueBean> executionPeriodLabelValueBeans = new ArrayList<LabelValueBean>();
        for (final ExecutionSemester ep : executionSemesters) {
            if (ep.getState().equals(PeriodState.OPEN) || ep.getState().equals(PeriodState.CURRENT)) {
                executionPeriodLabelValueBeans.add(new LabelValueBean(
                        ep.getName() + " " + ep.getExecutionYear().getYear(), ep.getExternalId().toString()));
            }
        }
        request.setAttribute(PresentationConstants.LABELLIST_EXECUTIONPERIOD, executionPeriodLabelValueBeans);

        request.setAttribute(PresentationConstants.LABELLIST_WEEKS, weeksLabelValueList);
        if (indexWeek != null) {
            final int xpto = indexWeek.intValue();
            if (xpto < weeks.size()) {
                today = (Calendar) weeks.get(xpto);
            } else {
                today = (Calendar) weeks.iterator().next();
                indexForm.set("indexWeek", new Integer(0));
            }
        }

        try {
            SiteView siteView = (SiteView) RoomSiteComponentServiceByExecutionPeriodID.run(bodyComponent,
                    roomKey, today, executionPeriodID);

            request.setAttribute("siteView", siteView);

        } catch (NonExistingServiceException e) {
            throw new NonExistingActionException(e);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }
        return mapping.findForward("roomViewer");
    }
    throw new FenixActionException();

}

From source file:com.silverwrist.dynamo.unistore.MessageImpl.java

public synchronized void delete(DynamoUser caller) throws DatabaseException, DynamoSecurityException {
    testPermission(caller, Namespaces.UNISTORE_PERMISSIONS_NAMESPACE, "delete.message", "no.deleteMessage");

    // We need to have lists of the text and binary parts on hand before we delete everything, so that we can
    // send out notifications.  However, not every one of the parts will be in our cache, so we'll need to create
    // some temporary instances, but use the cached ones whereever feasible.
    Map pmap = m_ops.listTextParts(m_id);
    ArrayList text_parts = new ArrayList(pmap.size());
    Iterator it = pmap.entrySet().iterator();
    while (it.hasNext()) { // look for a matching TextPartImpl
        Map.Entry ntry = (Map.Entry) (it.next());
        TextPartImpl p = (TextPartImpl) (m_part_to_text.get(ntry.getKey()));
        if (p == null)
            p = (TextPartImpl) (m_pk_to_text.get(ntry.getValue()));
        if (p == null) { // create a "scratch" instance
            PropertyKey pk = (PropertyKey) (ntry.getValue());
            QualifiedNameKey qname = new QualifiedNameKey(m_nscache.namespaceIdToName(pk.getNamespaceID()),
                    pk.getName());/* w  w  w  .  j  av  a 2s  .  co  m*/
            p = new TextPartImpl(m_post, this, ((Integer) (ntry.getKey())).intValue(), qname);

        } // end if

        text_parts.add(p);

    } // end while

    pmap = m_ops.listBinaryParts(m_id);
    ArrayList binary_parts = new ArrayList(pmap.size());
    it = pmap.entrySet().iterator();
    while (it.hasNext()) { // look for a matching BinaryPartImpl
        Map.Entry ntry = (Map.Entry) (it.next());
        BinaryPartImpl p = (BinaryPartImpl) (m_part_to_binary.get(ntry.getKey()));
        if (p == null)
            p = (BinaryPartImpl) (m_pk_to_binary.get(ntry.getValue()));
        if (p == null) { // create a "scratch" instance
            PropertyKey pk = (PropertyKey) (ntry.getValue());
            QualifiedNameKey qname = new QualifiedNameKey(m_nscache.namespaceIdToName(pk.getNamespaceID()),
                    pk.getName());
            p = new BinaryPartImpl(m_post, this, ((Integer) (ntry.getKey())).intValue(), qname);

        } // end if

        binary_parts.add(p);

    } // end while

    // Delete the message from the database.
    m_ops.delete(m_id);

    // Cut loose most of our data before we start notifying.
    m_ops = null;
    m_nscache = null;
    m_srm = null;
    m_users = null;
    m_parentid = -1;
    m_seq = -1;
    m_creator = -1;
    m_posted = null;
    m_aclid = -1;
    m_properties.clear();
    m_text_count = -1;
    m_binary_count = -1;
    m_part_to_text.clear();
    m_pk_to_text.clear();
    m_part_to_binary.clear();
    m_pk_to_binary.clear();

    // Send out the deletion notifications (and clear the data) for all parts.
    it = text_parts.iterator();
    while (it.hasNext()) { // make sure all of these parts are BALEETED!
        TextPartImpl p = (TextPartImpl) (it.next());
        p.baleeted();

    } // end while

    text_parts.clear();
    it = binary_parts.iterator();
    while (it.hasNext()) { // make sure all of these parts are BALEETED!
        BinaryPartImpl p = (BinaryPartImpl) (it.next());
        p.baleeted();

    } // end while

    binary_parts.clear();

    // Send our own "BALEETED!" notification.
    m_post.postUpdate(new MessageDeletedEvent(this));

    // Now cut loose the rest of our data.
    m_post = null;
    m_id = -1;

}

From source file:edu.umass.cs.gigapaxos.PaxosInstanceStateMachine.java

private MessagingTask handleSyncDecisionsPacket(SyncDecisionsPacket syncReply) throws JSONException {
    int minMissingSlot = syncReply.missingSlotNumbers.get(0);
    log.log(Level.FINE, "{0} handling sync decisions request {1} when maxCommittedSlot = {2}",
            new Object[] { this, syncReply.getSummary(), this.paxosState.getMaxCommittedSlot() });

    if (this.paxosState.getMaxCommittedSlot() - minMissingSlot < 0)
        return null; // I am worse than you

    // get checkpoint if minMissingSlot > last checkpointed slot
    MessagingTask checkpoint = null;//from  w  w  w .ja  v a2  s . c  o m
    if (minMissingSlot - lastCheckpointSlot(this.paxosState.getSlot(), syncReply.getPaxosID()) <= 0) {
        checkpoint = handleCheckpointRequest(syncReply);
        if (checkpoint != null)
            // only get decisions beyond checkpoint
            minMissingSlot = ((StatePacket) (checkpoint.msgs[0])).slotNumber + 1;
    }

    // try to get decisions from memory first
    HashMap<Integer, PValuePacket> missingDecisionsMap = new HashMap<Integer, PValuePacket>();
    for (PValuePacket pvalue : this.paxosState.getCommitted(syncReply.missingSlotNumbers))
        missingDecisionsMap.put(pvalue.slot, pvalue.setNoCoalesce());

    // get decisions from database as unlikely to have all of them in memory
    ArrayList<PValuePacket> missingDecisions = this.paxosManager.getPaxosLogger().getLoggedDecisions(
            this.getPaxosID(), this.getVersion(), minMissingSlot,
            /* If maxDecision <= minMissingSlot, sender is probably
             * doing a creation sync. But we need min < max for the
             * database query to return nonzero results, so we
             * adjust up the max if needed. Note that
             * getMaxCommittedSlot() at this node may not be greater
             * than minMissingDecision either. For example, the
             * sender may be all caught up at slot 0 and request a
             * creation sync for 1 and this node may have committed
             * up to 1; if so, it should return decision 1. */
            syncReply.maxDecisionSlot > minMissingSlot ? syncReply.maxDecisionSlot
                    : Math.max(minMissingSlot + 1, this.paxosState.getMaxCommittedSlot() + 1));

    // filter non-missing from database decisions
    if (syncReply.maxDecisionSlot > minMissingSlot)
        for (Iterator<PValuePacket> pvalueIterator = missingDecisions.iterator(); pvalueIterator.hasNext();) {
            PValuePacket pvalue = pvalueIterator.next();
            if (!syncReply.missingSlotNumbers.contains(pvalue.slot))
                pvalueIterator.remove(); // filter non-missing
            else
                pvalue.setNoCoalesce(); // send as-is, no compacting
            // isRecovery() true only in rollForward
            assert (!pvalue.isRecovery());
        }

    // copy over database decisions not in memory
    for (PValuePacket pvalue : missingDecisions)
        if (!missingDecisionsMap.containsKey(pvalue.slot))
            missingDecisionsMap.put(pvalue.slot, pvalue);

    // replace meta decisions with actual decisions
    getActualDecisions(missingDecisionsMap);

    assert (missingDecisionsMap.isEmpty()
            || missingDecisionsMap.values().toArray(new PaxosPacket[0]).length > 0) : missingDecisions;
    for (PValuePacket pvalue : missingDecisionsMap.values()) {
        pvalue.setNoCoalesce();
        assert (pvalue.hasRequestValue());
    }
    // the list of missing decisions to be sent
    MessagingTask unicasts = missingDecisionsMap.isEmpty() ? null
            : new MessagingTask(syncReply.nodeID, (missingDecisionsMap.values().toArray(new PaxosPacket[0])));

    log.log(Level.INFO, "{0} sending {1} missing decision(s) to node {2} in response to {3}", new Object[] {
            this, unicasts == null ? 0 : unicasts.msgs.length, syncReply.nodeID, syncReply.getSummary() });
    if (checkpoint != null)
        log.log(Level.INFO, "{0} sending checkpoint for slot {1} to node {2} in response to {3}",
                new Object[] { this, minMissingSlot - 1, syncReply.nodeID, syncReply.getSummary() });

    // combine checkpoint and missing decisions in unicasts
    MessagingTask mtask =
            // both nonempty => combine
            (checkpoint != null && unicasts != null && !checkpoint.isEmpty() && !unicasts.isEmpty())
                    ? mtask = new MessagingTask(syncReply.nodeID,
                            MessagingTask.toPaxosPacketArray(checkpoint.msgs, unicasts.msgs))
                    :
                    // nonempty checkpoint
                    (checkpoint != null && !checkpoint.isEmpty()) ? checkpoint :
                    // unicasts (possibly also empty or null)
                            unicasts;
    log.log(Level.FINE, "{0} sending mtask: ", new Object[] { this, mtask });
    return mtask;
}

From source file:com.ecyrd.jspwiki.parser.JSPWikiMarkupParser.java

/**
 *  Checks out that the first paragraph is correctly installed.
 *
 *  @param rootElement// ww  w  . j av  a 2s  .  c  om
 */
private void paragraphify(Element rootElement) {
    //
    //  Add the paragraph tag to the first paragraph
    //
    List kids = rootElement.getContent();

    if (rootElement.getChild("p") != null) {
        ArrayList<Content> ls = new ArrayList<Content>();
        int idxOfFirstContent = 0;
        int count = 0;

        for (Iterator i = kids.iterator(); i.hasNext(); count++) {
            Content c = (Content) i.next();
            if (c instanceof Element) {
                String name = ((Element) c).getName();
                if (isBlockLevel(name))
                    break;
            }

            if (!(c instanceof ProcessingInstruction)) {
                ls.add(c);
                if (idxOfFirstContent == 0)
                    idxOfFirstContent = count;
            }
        }

        //
        //  If there were any elements, then add a new <p> (unless it would
        //  be an empty one)
        //
        if (ls.size() > 0) {
            Element newel = new Element("p");

            for (Iterator i = ls.iterator(); i.hasNext();) {
                Content c = (Content) i.next();

                c.detach();
                newel.addContent(c);
            }

            //
            // Make sure there are no empty <p/> tags added.
            //
            if (newel.getTextTrim().length() > 0 || !newel.getChildren().isEmpty())
                rootElement.addContent(idxOfFirstContent, newel);
        }
    }
}