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:edu.virginia.iath.snac.helpers.GeoNamesHelper.java

/**
 * Orders the candidate results from Cheshire to produce a better resulting set.  Given the first part of the
 * query string and the length of ngrams used, this method breaks <code>first</code> into ngrams.  It then
 * breaks the GeoName <code>name</code> for each of the Cheshire results into ngrams as well.  It then adds
 * all results that have at least 1 ngram-overlap with <code>first</code> to a list, then sorts them using
 * the FlexibleNGramsComparator, which sorts in the following order:
 * <ol>//from ww  w.  ja va2  s .co m
 * <li> Sort by alternate names (descending)
 * <li> Sort by string length (descending)
 * <li> Sort by population (descending)
 * </ol>
 * 
 * @param first First part of the query string
 * @param ngramLength Number of characters per ngram
 * @return List of ordered results
 */
@SuppressWarnings("unused")
private ArrayList<String> getOrderedResultsByNGramsFlexible(String first, int ngramLength) {
    ArrayList<String> ret = new ArrayList<String>();
    ArrayList<GeolocationString> toSort = new ArrayList<GeolocationString>();

    GeolocationString ngramFirst = new GeolocationString(first.toLowerCase().trim(), ngramLength);

    // Put each candidate from overkill into the new object
    for (String candidateXML : this.overkill) {
        if (candidateXML != null) {
            String candidate = getGeonamesName(candidateXML);
            if (candidate != null) {
                GeolocationString tmp = new GeolocationString(
                        candidate.toLowerCase().replace("(historical)", "").trim(), ngramLength);
                tmp.setNGramMaster(ngramFirst);
                tmp.storeData(candidateXML);
                tmp.setPopulation(getGeonamesPop(candidateXML));
                tmp.setNumAltNames(getGeonamesNumAltNames(candidateXML));
                if (tmp.getOverlap() > 1)
                    toSort.add(tmp);
            }
        }
    }

    if (!toSort.isEmpty()) {
        Collections.sort(toSort, new OriginalNGramsComparator());

        int maxOverlap = toSort.get(0).getOverlap();
        int flexOverlap = maxOverlap - 1;

        // Remove all items that have overlap less than flexOverlap
        Iterator<GeolocationString> itr = toSort.iterator();
        while (itr.hasNext()) {
            GeolocationString cur = itr.next();
            if (cur.getOverlap() < flexOverlap)
                itr.remove();
        }

        Collections.sort(toSort, new FlexibleNGramsComparator());

        for (GeolocationString sorted : toSort) {
            ret.add((String) sorted.getData());
        }
    }

    return ret;

}

From source file:CB_Core.Api.GroundspeakAPI.java

/**
 * Gets the Status for the given Caches/*from  w  ww . ja  v a  2s.  c  om*/
 * 
 * Staging
 *            Config.settings.StagingAPI.getValue()
 * accessToken
 * conectionTimeout
 *            Config.settings.conection_timeout.getValue()
 * socketTimeout
 *            Config.settings.socket_timeout.getValue()
 * @param caches is also for return
 * @return
 */
public static int GetGeocacheStatus(ArrayList<Cache> caches, final ICancel icancel) {
    int chk = chkMembership(false);
    if (chk < 0)
        return chk;

    try {
        Thread.sleep(2500);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    String URL = CB_Core_Settings.StagingAPI.getValue() ? STAGING_GS_LIVE_URL : GS_LIVE_URL;

    try {
        HttpPost httppost = new HttpPost(URL + "GetGeocacheStatus?format=json");
        String requestString = "";
        requestString = "{";
        requestString += "\"AccessToken\":\"" + GetAccessToken() + "\",";
        requestString += "\"CacheCodes\":[";

        int i = 0;
        for (Cache cache : caches) {
            requestString += "\"" + cache.getGcCode() + "\"";
            if (i < caches.size() - 1)
                requestString += ",";
            i++;
        }

        requestString += "]";
        requestString += "}";

        httppost.setEntity(new ByteArrayEntity(requestString.getBytes("UTF8")));

        // set time outs
        HttpUtils.conectionTimeout = CB_Core_Settings.conection_timeout.getValue();
        HttpUtils.socketTimeout = CB_Core_Settings.socket_timeout.getValue();

        // Execute HTTP Post Request
        String result = HttpUtils.Execute(httppost, icancel);

        if (result.contains("The service is unavailable")) {
            return API_IS_UNAVAILABLE;
        }
        try
        // Parse JSON Result
        {
            JSONTokener tokener = new JSONTokener(result);
            JSONObject json = (JSONObject) tokener.nextValue();
            JSONObject status = json.getJSONObject("Status");
            if (status.getInt("StatusCode") == 0) {
                result = "";
                JSONArray geocacheStatuses = json.getJSONArray("GeocacheStatuses");
                for (int ii = 0; ii < geocacheStatuses.length(); ii++) {
                    JSONObject jCache = (JSONObject) geocacheStatuses.get(ii);

                    Iterator<Cache> iterator = caches.iterator();
                    do {
                        Cache tmp = iterator.next();
                        if (jCache.getString("CacheCode").equals(tmp.getGcCode())) {
                            tmp.setArchived(jCache.getBoolean("Archived"));
                            tmp.setAvailable(jCache.getBoolean("Available"));
                            tmp.NumTravelbugs = jCache.getInt("TrackableCount");
                            // weitere Infos in diesem Json record
                            // CacheName (getString)
                            // CacheType (getDouble / getLong ?)
                            // Premium   (getBoolean)
                            break;
                        }
                    } while (iterator.hasNext());

                }

                return 0;
            } else {
                result = "StatusCode = " + status.getInt("StatusCode") + "\n";
                result += status.getString("StatusMessage") + "\n";
                result += status.getString("ExceptionDetails");
                LastAPIError = result;
                return (-1);
            }

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

    } catch (ConnectTimeoutException e) {
        logger.error("GetGeocacheStatus ConnectTimeoutException", e);
        return CONNECTION_TIMEOUT;
    } catch (UnsupportedEncodingException e) {
        logger.error("GetGeocacheStatus UnsupportedEncodingException", e);
        return ERROR;
    } catch (ClientProtocolException e) {
        logger.error("GetGeocacheStatus ClientProtocolException", e);
        return ERROR;
    } catch (IOException e) {
        logger.error("GetGeocacheStatus IOException", e);
        return ERROR;
    }

    return (-1);
}

From source file:net.java.sip.communicator.impl.gui.main.chat.ChatWritePanel.java

/**
 * When CTRL+Z is pressed invokes the <code>ChatWritePanel.undo()</code>
 * method, when CTRL+R is pressed invokes the
 * <code>ChatWritePanel.redo()</code> method.
 *
 * @param e the <tt>KeyEvent</tt> that notified us
 *//*from w w w  .  j  a  v a  2s  .  co m*/
public void keyPressed(KeyEvent e) {
    if ((e.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK && (e.getKeyCode() == KeyEvent.VK_Z)
    // And not ALT(right ALT gives CTRL + ALT).
            && (e.getModifiers() & KeyEvent.ALT_MASK) != KeyEvent.ALT_MASK) {
        if (undo.canUndo())
            undo();
    } else if ((e.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK
            && (e.getKeyCode() == KeyEvent.VK_R)
            // And not ALT(right ALT gives CTRL + ALT).
            && (e.getModifiers() & KeyEvent.ALT_MASK) != KeyEvent.ALT_MASK) {
        if (undo.canRedo())
            redo();
    } else if (e.getKeyCode() == KeyEvent.VK_TAB) {
        if (!(chatPanel.getChatSession() instanceof ConferenceChatSession))
            return;

        e.consume();
        int index = ((JEditorPane) e.getSource()).getCaretPosition();

        StringBuffer message = new StringBuffer(chatPanel.getMessage());

        int position = index - 1;

        while (position > 0 && (message.charAt(position) != ' ')) {
            position--;
        }

        if (position != 0)
            position++;

        String sequence = message.substring(position, index);

        if (sequence.length() <= 0) {
            // Do not look for matching contacts if the matching pattern is
            // 0 chars long, since all contacts will match.
            return;
        }

        Iterator<ChatContact<?>> iter = chatPanel.getChatSession().getParticipants();
        ArrayList<String> contacts = new ArrayList<String>();
        while (iter.hasNext()) {
            ChatContact<?> c = iter.next();
            if (c.getName().length() >= (index - position)
                    && c.getName().substring(0, index - position).equals(sequence)) {
                message.replace(position, index, c.getName().substring(0, index - position));
                contacts.add(c.getName());
            }
        }

        if (contacts.size() > 1) {
            char key = contacts.get(0).charAt(index - position - 1);
            int pos = index - position - 1;
            boolean flag = true;

            while (flag) {
                try {
                    for (String name : contacts) {
                        if (key != name.charAt(pos)) {
                            flag = false;
                        }
                    }

                    if (flag) {
                        pos++;
                        key = contacts.get(0).charAt(pos);
                    }
                } catch (IndexOutOfBoundsException exp) {
                    flag = false;
                }
            }

            message.replace(position, index, contacts.get(0).substring(0, pos));

            Iterator<String> contactIter = contacts.iterator();
            String contactList = "<DIV align='left'><h5>";
            while (contactIter.hasNext()) {
                contactList += contactIter.next() + " ";
            }
            contactList += "</h5></DIV>";

            chatPanel.getChatConversationPanel().appendMessageToEnd(contactList,
                    ChatHtmlUtils.HTML_CONTENT_TYPE);
        } else if (contacts.size() == 1) {
            String limiter = (position == 0) ? ": " : "";
            message.replace(position, index, contacts.get(0) + limiter);
        }

        try {
            ((JEditorPane) e.getSource()).getDocument().remove(0,
                    ((JEditorPane) e.getSource()).getDocument().getLength());
            ((JEditorPane) e.getSource()).getDocument().insertString(0, message.toString(), null);
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    } else if (e.getKeyCode() == KeyEvent.VK_UP) {
        // Only enters editing mode if the write panel is empty in
        // order not to lose the current message contents, if any.
        if (this.chatPanel.getLastSentMessageUID() != null && this.chatPanel.isWriteAreaEmpty()) {
            this.chatPanel.startLastMessageCorrection();
            e.consume();
        }
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
        if (chatPanel.isMessageCorrectionActive()) {
            Document doc = editorPane.getDocument();
            if (editorPane.getCaretPosition() == doc.getLength()) {
                chatPanel.stopMessageCorrection();
            }
        }
    }
}

From source file:com.clustercontrol.http.factory.RunMonitorHttpScenario.java

/**
 * []????/*from w  w w .ja va 2s .  c o m*/
 *
 * ??1??ID??????ID??????????
 * ????????runMonitorInfo???
 *
 */
@Override
protected boolean runMonitorInfo()
        throws FacilityNotFound, MonitorNotFound, EntityExistsException, InvalidRole, HinemosUnknown {
    m_log.debug("runMonitorInfo()");

    m_now = new Date(HinemosTime.currentTimeMillis());

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

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

        // 
        setJudgementInfo();

        // ??
        setCheckInfo();

        ArrayList<String> facilityList = null;
        ExecutorCompletionService<ArrayList<MonitorRunResultInfo>> ecs = new ExecutorCompletionService<ArrayList<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);

            String facilityId = null;

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

                    // ???RunMonitor????
                    // ?????????????
                    RunMonitorHttpScenario runMonitor = new RunMonitorHttpScenario();

                    // ?????
                    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 CallableTaskHttpScenario(runMonitor, facilityId));
                    taskCount++;
                } else {
                    itr.remove();
                }
            }
        } 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 = new RepositoryControllerBean().isNode(m_facilityId);

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

            /**
             * ?
             */
            // ???RunMonitor????
            // ?????????????
            RunMonitorHttpScenario runMonitor = new RunMonitorHttpScenario();

            // ?????
            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;

            ecs.submit(new CallableTaskHttpScenario(runMonitor, m_facilityId));
            taskCount++;
        }
        /**
         * ??
         */
        ArrayList<MonitorRunResultInfo> resultList = null;

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

        // ???
        List<Sample> sampleList = new ArrayList<Sample>();
        Sample sample = null;
        if (m_monitor.getCollectorFlg()) {
            sample = new Sample(HinemosTime.getDateInstance(), m_monitor.getMonitorId());
        }

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

            for (MonitorRunResultInfo result : resultList) {
                m_nodeDate = result.getNodeDate();

                String facilityId = result.getFacilityId();

                // ?
                if (!m_isMonitorJob) {
                    if (result.getMonitorFlg()) {
                        notify(true, facilityId, result.getCheckResult(), new Date(m_nodeDate), result);
                    }
                } 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()));
                }

                // ???
                if (sample != null && result.getCollectorFlg()) {
                    int errorCode = -1;
                    if (result.isCollectorResult()) {
                        errorCode = CollectedDataErrorTypeConstant.NOT_ERROR;
                    } else {
                        errorCode = CollectedDataErrorTypeConstant.UNKNOWN;
                    }
                    sample.set(facilityId, m_monitor.getItemName(), result.getValue(), errorCode,
                            result.getDisplayName());
                }
            }
        }

        // ?????
        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 (EntityExistsException e) {
        throw e;
    } catch (FacilityNotFound e) {
        throw e;
    } catch (InvalidRole 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:net.floodlightcontroller.devicemanager.internal.DeviceManagerImpl.java

@Override
public Iterator<? extends IDevice> queryClassDevices(IEntityClass entityClass, Long macAddress, Short vlan,
        Integer ipv4Address, Long switchDPID, Integer switchPort) {
    ArrayList<Iterator<Device>> iterators = new ArrayList<Iterator<Device>>();
    ClassState classState = getClassState(entityClass);

    DeviceIndex index = null;/*from   w w  w . j a  v  a  2  s.  c o  m*/
    if (classState.secondaryIndexMap.size() > 0) {
        EnumSet<DeviceField> keys = getEntityKeys(macAddress, vlan, ipv4Address, switchDPID, switchPort);
        index = classState.secondaryIndexMap.get(keys);
    }

    Iterator<Device> iter;
    if (index == null) {
        index = classState.classIndex;
        if (index == null) {
            // scan all devices
            return new DeviceIterator(deviceMap.values().iterator(), new IEntityClass[] { entityClass },
                    macAddress, vlan, ipv4Address, switchDPID, switchPort);
        } else {
            // scan the entire class
            iter = new DeviceIndexInterator(this, index.getAll());
        }
    } else {
        // index lookup
        Entity entity = new Entity((macAddress == null ? 0 : macAddress), vlan, ipv4Address, switchDPID,
                switchPort, null);
        iter = new DeviceIndexInterator(this, index.queryByEntity(entity));
    }
    iterators.add(iter);

    return new MultiIterator<Device>(iterators.iterator());
}

From source file:com.ibm.bi.dml.parser.DMLTranslator.java

public void refreshMemEstimates(StatementBlock current) throws ParseException, HopsException {

    MemoTable memo = new MemoTable();
    ArrayList<Hop> hopsDAG = current.get_hops();
    if (hopsDAG != null && !hopsDAG.isEmpty()) {
        Iterator<Hop> iter = hopsDAG.iterator();
        while (iter.hasNext()) {
            iter.next().refreshMemEstimates(memo);
        }/*w  ww .  j  a  v  a2s. c om*/
    }

    if (current instanceof FunctionStatementBlock) {

        FunctionStatement fstmt = (FunctionStatement) current.getStatement(0);
        for (StatementBlock sb : fstmt.getBody()) {
            refreshMemEstimates(sb);
        }
    }

    if (current instanceof WhileStatementBlock) {
        // handle predicate
        WhileStatementBlock wstb = (WhileStatementBlock) current;
        wstb.getPredicateHops().refreshMemEstimates(new MemoTable());

        if (wstb.getNumStatements() > 1)
            LOG.debug("While statement block has more than 1 stmt");
        WhileStatement ws = (WhileStatement) wstb.getStatement(0);

        for (StatementBlock sb : ws.getBody()) {
            refreshMemEstimates(sb);
        }
    }

    if (current instanceof IfStatementBlock) {
        // handle predicate
        IfStatementBlock istb = (IfStatementBlock) current;
        istb.getPredicateHops().refreshMemEstimates(new MemoTable());

        if (istb.getNumStatements() > 1)
            LOG.debug("If statement block has more than 1 stmt");
        IfStatement is = (IfStatement) istb.getStatement(0);

        for (StatementBlock sb : is.getIfBody()) {
            refreshMemEstimates(sb);
        }
        for (StatementBlock sb : is.getElseBody()) {
            refreshMemEstimates(sb);
        }
    }

    if (current instanceof ForStatementBlock) {
        // handle predicate
        ForStatementBlock fsb = (ForStatementBlock) current;
        if (fsb.getFromHops() != null)
            fsb.getFromHops().refreshMemEstimates(new MemoTable());
        if (fsb.getToHops() != null)
            fsb.getToHops().refreshMemEstimates(new MemoTable());
        if (fsb.getIncrementHops() != null)
            fsb.getIncrementHops().refreshMemEstimates(new MemoTable());

        if (fsb.getNumStatements() > 1)
            LOG.debug("For statement block has more than 1 stmt");
        ForStatement ws = (ForStatement) fsb.getStatement(0);

        for (StatementBlock sb : ws.getBody()) {
            refreshMemEstimates(sb);
        }
    }
}

From source file:com.ibm.bi.dml.parser.DMLTranslator.java

public void resetLopsDAGVisitStatus(StatementBlock current) throws HopsException {

    ArrayList<Hop> hopsDAG = current.get_hops();

    if (hopsDAG != null && !hopsDAG.isEmpty()) {
        Iterator<Hop> iter = hopsDAG.iterator();
        while (iter.hasNext()) {
            Hop currentHop = iter.next();
            currentHop.getLops().resetVisitStatus();
        }/*  w  w  w  . jav  a  2  s . c  o  m*/
    }

    if (current instanceof FunctionStatementBlock) {
        FunctionStatementBlock fsb = (FunctionStatementBlock) current;
        FunctionStatement fs = (FunctionStatement) fsb.getStatement(0);

        for (StatementBlock sb : fs.getBody()) {
            resetLopsDAGVisitStatus(sb);
        }
    }

    if (current instanceof WhileStatementBlock) {
        WhileStatementBlock wstb = (WhileStatementBlock) current;
        wstb.get_predicateLops().resetVisitStatus();
        if (wstb.getNumStatements() > 1)
            LOG.debug("While statement block has more than 1 stmt");
        WhileStatement ws = (WhileStatement) wstb.getStatement(0);

        for (StatementBlock sb : ws.getBody()) {
            resetLopsDAGVisitStatus(sb);
        }
    }

    if (current instanceof IfStatementBlock) {
        IfStatementBlock istb = (IfStatementBlock) current;
        istb.get_predicateLops().resetVisitStatus();
        if (istb.getNumStatements() > 1)
            LOG.debug("If statement block has more than 1 stmt");
        IfStatement is = (IfStatement) istb.getStatement(0);

        for (StatementBlock sb : is.getIfBody()) {
            resetLopsDAGVisitStatus(sb);
        }

        for (StatementBlock sb : is.getElseBody()) {
            resetLopsDAGVisitStatus(sb);
        }
    }

    if (current instanceof ForStatementBlock) {
        ForStatementBlock fsb = (ForStatementBlock) current;

        if (fsb.getFromLops() != null)
            fsb.getFromLops().resetVisitStatus();
        if (fsb.getToLops() != null)
            fsb.getToLops().resetVisitStatus();
        if (fsb.getIncrementLops() != null)
            fsb.getIncrementLops().resetVisitStatus();

        if (fsb.getNumStatements() > 1)
            LOG.debug("For statement block has more than 1 stmt");
        ForStatement ws = (ForStatement) fsb.getStatement(0);

        for (StatementBlock sb : ws.getBody()) {
            resetLopsDAGVisitStatus(sb);
        }
    }
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.blockcharts.TimeBlockChart.java

@Override
public DatasetMap calculateValue() throws Exception {
    logger.debug("IN");
    super.calculateValue();
    DatasetMap datasetMap = new DatasetMap();
    String res = DataSetAccessFunctions.getDataSetResultFromId(profile, getData(), parametersObject);

    ArrayList<Activity> activities = new ArrayList<Activity>();

    RegularTimePeriod timePeriod = null;

    SourceBean sbRows = SourceBean.fromXMLString(res);
    List listAtts = sbRows.getAttributeAsList("ROW");
    // Run all rows
    if (listAtts == null) {
        logger.error("Null rows retrieved from dataset");
        return null;
    }/*from   www  .java2 s  .  co  m*/
    int j = 0;
    // for each activity
    logger.debug("retrieved number rows: " + listAtts.size());
    for (Iterator iterator = listAtts.iterator(); iterator.hasNext();) {
        SourceBean row = (SourceBean) iterator.next();
        Activity activity = new Activity(row, beginDateFormat, beginHourFormat);
        activities.add(activity);
        logger.debug(
                "Activity built from " + activity.getBeginDate() + " minutes" + activity.getMinutes() != null
                        ? activity.getMinutes().toString()
                        : "");
        if (maxDateFound != null && !activity.getBeginDate().after(maxDateFound)) {
        } else {
            maxDateFound = activity.getBeginDate();
        }

        if (minDateFound != null && !activity.getBeginDate().before(minDateFound)) {
        } else {
            minDateFound = activity.getBeginDate();
        }
    }

    //      count days
    long daysBetween;
    if (dateMin != null && dateMax != null) {
        logger.debug(
                "use date limit defined in template: from " + dateMin.toString() + " to " + dateMax.toString());
        daysBetween = daysBetween(dateMin, dateMax);
    } else {
        logger.debug(
                "use date limit found: from " + minDateFound.toString() + " to " + maxDateFound.toString());
        daysBetween = daysBetween(minDateFound, maxDateFound);
    }
    logger.debug("Days between the two dates " + daysBetween);
    // add a date to include extremis
    long minutesBetweenLong = daysBetween * 24 * 60 * 2; // raddoppio in caso di sovrapposizioni
    int mbl = Long.valueOf(minutesBetweenLong).intValue();

    DefaultXYZDataset dataset = new DefaultXYZDataset();

    ArrayList<Long> xValuesList = new ArrayList<Long>();
    ArrayList<Double> yValuesList = new ArrayList<Double>();
    ArrayList<Double> zValuesList = new ArrayList<Double>();

    annotations = new HashMap<String, AnnotationBlock>();
    // run all the activities
    for (Iterator iterator = activities.iterator(); iterator.hasNext();) {
        Activity activity = (Activity) iterator.next();

        // insert only if activty falls inside the min and max Range (idf defined)
        if (dateMin != null && dateMax != null
                && (activity.getBeginDate().after(dateMax) || activity.getBeginDate().before(dateMin))) {
            logger.debug(
                    "Activity discarde because starting out of selected bounds in " + activity.getBeginDate());
        } else {
            logger.debug("Inserting activity with begin date " + activity.getBeginDate() + " adn pattern "
                    + activity.getPattern());
            RegularTimePeriod rtp = new Day(activity.getBeginDate());
            long secondmills = rtp.getFirstMillisecond();

            Minute minute = activity.getMinutes();
            for (int i = 0; i < activity.getDuration(); i++) {
                // convert from hour to number axis (da sessantesimi a centesimi!)
                Integer hour = Integer.valueOf(minute.getHourValue());
                Integer minuteValue = Integer.valueOf(minute.getMinute());
                Double doubleMinuteValue = Double.valueOf(((double) minuteValue.intValue()));
                // minuteValue : 60 = x :100
                double convertedMinuteValue = (doubleMinuteValue * 100) / 60.0;
                double convertedMinuteValueCent = convertedMinuteValue / 100;

                double hourD = (double) hour.intValue();
                double converted = hourD + convertedMinuteValueCent;

                String yVal = Double.valueOf(converted).toString();

                xValuesList.add(new Long(secondmills));
                yValuesList.add(Double.valueOf(yVal));

                Object cosa = patternRangeIndex.get(activity.getPattern());

                if (cosa != null) {
                    zValuesList.add(
                            Double.valueOf(patternRangeIndex.get(activity.getPattern())).doubleValue() + 0.5);
                } else {
                    zValuesList.add(-1.0);
                }
                //               xvalues[j]=secondmills;
                //               yvalues[j]=Double.valueOf(yVal);
                //               zvalues[j]=patternRangeIndex.get(activity.getPattern())+0.5;

                //System.out.println("Date: "+activity.getBeginDate()+":"+Double.valueOf(xvalues[j]).toString()+", Hour: "+Double.valueOf(yvalues[j]).toString()+", Value: "+Double.valueOf(zvalues[j]).toString());
                if (annotations.get(activity.getCode()) == null) {
                    AnnotationBlock annotation = new AnnotationBlock(activity.getCode());
                    annotation.setXPosition(xValuesList.get(j).doubleValue());
                    annotation.setYPosition(yValuesList.get(j).doubleValue());
                    annotations.put(annotation.getAnnotation(), annotation);
                }
                minute = (Minute) minute.next();
                j++;
            }
        }

    }
    //      create arrays
    double[] xvalues = new double[xValuesList.size()];
    double[] yvalues = new double[yValuesList.size()];
    double[] zvalues = new double[zValuesList.size()];

    for (int i = 0; i < zValuesList.size(); i++) {
        Long l = xValuesList.get(i);
        xvalues[i] = l;
        Double d2 = yValuesList.get(i);
        yvalues[i] = d2;
        Double d = zValuesList.get(i);
        zvalues[i] = d;
    }

    logger.debug("adding the serie");
    dataset.addSeries("Series 1", new double[][] { xvalues, yvalues, zvalues });

    datasetMap.getDatasets().put("1", dataset);
    logger.debug("OUT");
    return datasetMap;
}

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

public void run() {

    BufferedReader d = null;//from   ww  w .j a  v  a2 s  . c om
    Connection conn = null;

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

    if (conn != null) {

        try {

            Statement stmt = null;
            //                ResultSet rs = null;
            //                ResultSet rs2 = null;

            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            stmt.execute("SET AUTOCOMMIT=0");
            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;

            populateLocalInfo(conn);

            for (int repeat = 0; repeat <= repeatNumber; repeat++) {
                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 = 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();
                    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");
                    //                            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:org.apache.manifoldcf.crawler.connectors.meridio.MeridioConnector.java

private static String[] getMIMETypes(Specification spec) {
    ArrayList al = new ArrayList();

    for (int i = 0; i < spec.getChildCount(); i++) {
        SpecificationNode sn = spec.getChild(i);

        if (sn.getType().equals("MIMEType")) {
            al.add(sn.getAttributeValue("type"));
        }//w  w w.  j  a v  a  2s. c  o m
    }

    String[] mimeTypes = new String[al.size()];
    Iterator it = al.iterator();
    for (int i = 0; it.hasNext(); i++) {
        mimeTypes[i] = (String) it.next();
    }

    return mimeTypes;
}