Example usage for java.util LinkedList size

List of usage examples for java.util LinkedList size

Introduction

In this page you can find the example usage for java.util LinkedList size.

Prototype

int size

To view the source code for java.util LinkedList size.

Click Source Link

Usage

From source file:com.google.ie.business.service.impl.IdeaServiceImpl.java

@SuppressWarnings("unchecked")
@Override//from  w w w .j  ava  2  s  . c  om
public LinkedList<Idea> getRecentIdeas() {
    /* Check the cache for the data */
    LinkedList<Idea> listOfRecentIdeas = (LinkedList<Idea>) CacheHelper.getObject(CacheConstants.IDEA_NAMESPACE,
            CacheConstants.RECENT_IDEAS);
    if (listOfRecentIdeas != null && listOfRecentIdeas.size() > ServiceConstants.ZERO) {
        logger.info("Recent ideas successfully fetched from cache");
        return listOfRecentIdeas;
    }
    /* If not found in cache then retrieve from data store. */
    RetrievalInfo retrievalInfo = new RetrievalInfo();
    retrievalInfo.setNoOfRecords(DEFAULT_NO_OF_RECENT_IDEAS);
    retrievalInfo.setOrderBy(ServiceConstants.DEFAULT_IDEA_ORDERING_FIELD);
    retrievalInfo.setOrderType(ServiceConstants.ORDERING_TYPE_FOR_RECENT_IDEAS);
    /* Fetch the ideas and create a linked list from the fetched data */
    listOfRecentIdeas = createLinkedListFromTheFetchedData(getIdeas(retrievalInfo));
    /* If the list contains data, add it to the cache */
    if (listOfRecentIdeas.size() > ServiceConstants.ZERO) {
        CacheHelper.putObject(CacheConstants.IDEA_NAMESPACE, CacheConstants.RECENT_IDEAS, listOfRecentIdeas,
                CacheConstants.RECENT_IDEAS_EXPIRATION_DELAY);
        logger.info("Recent ideas successfully added to the cache");
    }
    return listOfRecentIdeas;
}

From source file:com.mirth.connect.plugins.dashboardstatus.DashboardConnectorStatusMonitor.java

public synchronized Object invoke(String method, Object object, String sessionId) {
    if (method.equals(METHOD_GET_STATES)) {
        return connectorStateMap;
    } else if (method.equals(METHOD_GET_CONNECTION_INFO_LOGS)) {
        String channelName;/*w w  w .  j a v  a  2s.c o m*/
        LinkedList<String[]> channelLog;

        if (object == null) {
            /*
             * object is null - no channel is selected. return the latest
             * entire log entries of all channels combined. ONLY new
             * entries.
             */
            channelName = STATE_NO_SELECTION;
            channelLog = entireConnectorInfoLogs;
        } else {
            // object is not null - a channel is selected. return the latest
            // (LOG_SIZE) of that particular channel.
            channelName = object.toString();
            // return only the newly added log entries for the client with
            // matching sessionId.
            channelLog = connectorInfoLogs.get(channelName);

            if (channelLog == null) {
                channelLog = new LinkedList<String[]>();
                connectorInfoLogs.put(channelName, channelLog);
            }
        }

        HashMap<String, Long> lastDisplayedLogIdByChannel;

        if (lastDisplayedLogIndexBySessionId.containsKey(sessionId)) {
            // client exist with the sessionId.
            lastDisplayedLogIdByChannel = lastDisplayedLogIndexBySessionId.get(sessionId);

            if (lastDisplayedLogIdByChannel.containsKey(channelName)) {
                // existing channel on an already open client.
                // -> only display new log entries.
                long lastDisplayedLogId = lastDisplayedLogIdByChannel.get(channelName);
                LinkedList<String[]> newChannelLogEntries = new LinkedList<String[]>();

                // FYI, channelLog.size() will never be larger than LOG_SIZE
                // = 1000.
                for (String[] aChannelLog : channelLog) {
                    if (lastDisplayedLogId < Long.parseLong(aChannelLog[0])) {
                        newChannelLogEntries.addLast(aChannelLog);
                    }
                }

                if (newChannelLogEntries.size() > 0) {
                    /*
                     * put the lastDisplayedLogId into the HashMap. index 0
                     * is the most recent entry, and index0 of that entry
                     * contains the logId.
                     */
                    lastDisplayedLogIdByChannel.put(channelName,
                            Long.parseLong(newChannelLogEntries.get(0)[0]));
                    lastDisplayedLogIndexBySessionId.put(sessionId, lastDisplayedLogIdByChannel);
                }

                try {
                    return SerializationUtils.clone(newChannelLogEntries);
                } catch (SerializationException e) {
                    logger.error(e);
                }
            } else {
                /*
                 * new channel viewing on an already open client. -> all log
                 * entries are new. display them all. put the
                 * lastDisplayedLogId into the HashMap. index0 is the most
                 * recent entry, and index0 of that entry object contains
                 * the logId.
                 */
                if (channelLog.size() > 0) {
                    lastDisplayedLogIdByChannel.put(channelName, Long.parseLong(channelLog.get(0)[0]));
                    lastDisplayedLogIndexBySessionId.put(sessionId, lastDisplayedLogIdByChannel);
                }

                try {
                    return SerializationUtils.clone(channelLog);
                } catch (SerializationException e) {
                    logger.error(e);
                }
            }

        } else {
            // brand new client.
            // thus also new channel viewing.
            // -> all log entries are new. display them all.
            lastDisplayedLogIdByChannel = new HashMap<String, Long>();

            if (channelLog.size() > 0) {
                lastDisplayedLogIdByChannel.put(channelName, Long.parseLong(channelLog.get(0)[0]));
            } else {
                // no log exist at all. put the currentLogId-1, which is the
                // very latest logId.
                lastDisplayedLogIdByChannel.put(channelName, logId - 1);
            }

            lastDisplayedLogIndexBySessionId.put(sessionId, lastDisplayedLogIdByChannel);

            try {
                return SerializationUtils.clone(channelLog);
            } catch (SerializationException e) {
                logger.error(e);
            }
        }

    } else if (method.equals(METHOD_CHANNELS_DEPLOYED)) {
        if (channelsDeployedFlagForEachClient.containsKey(sessionId)) {
            // sessionId found. no (re)deploy occurred.
            return false;
        } else {
            // no sessionId found, which means channels have just been
            // (re)deployed - clear out all clients' Dashboard Connector
            // Logs.
            channelsDeployedFlagForEachClient.put(sessionId, true);
            return true;
        }
    } else if (method.equals(METHOD_REMOVE_SESSIONID)) {
        // client shut down, or user logged out -> remove everything
        // involving this sessionId.
        if (lastDisplayedLogIndexBySessionId.containsKey(sessionId)) {
            lastDisplayedLogIndexBySessionId.remove(sessionId);
        }

        if (channelsDeployedFlagForEachClient.containsKey(sessionId)) {
            channelsDeployedFlagForEachClient.remove(sessionId);
        }

        return null;
    }

    return null;
}

From source file:comingle.dragracing.TrackActivity.java

private void initMarkers(LinkedList<Integer> locs) {
    Paint text_paint = new Paint();
    text_paint.setColor(Color.BLACK);
    text_paint.setTextSize(20);/*  ww  w.  j  a v  a2 s  . c  o  m*/

    String prev = "Start";
    String next = "End";
    int x = locs.indexOf(getLocation());

    if (x == locs.size() - 1) {
        initEndFlag();
    }

    if (x == 0) {
        initStartFlag();
    }

    if (x > 0) {
        prev = String.format("<< %s", INTERVAL_MARKERS[x - 1]);
    }

    if (x < locs.size() - 1) {
        next = String.format("%s >>", INTERVAL_MARKERS[x]);
    }

    //adjusted placement of markers
    track_canvas.drawText(prev, 20, TOP_MARGIN - 70, text_paint);
    track_canvas.drawText(next, 800 - 50, TOP_MARGIN - 70, text_paint);

}

From source file:org.testmp.datastore.client.DataStoreClient.java

/**
 * Save data in data store into specified file with JSON representation
 * /*from w w  w. j a  v  a  2 s  .  c  om*/
 * @param filepath
 * @throws DataStoreClientException
 */
public void saveDataToFile(String filepath) throws DataStoreClientException {
    List<Tag> tags = getTags();
    HashSet<Integer> idSet = new HashSet<Integer>();
    for (Tag tag : tags) {
        idSet.addAll(tag.getRelatedDataIds());
    }
    LinkedList<Integer> idList = new LinkedList<Integer>(idSet);
    Collections.sort(idList);
    int maxDataToGetEachTime = 500, i = 0;
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(filepath, "UTF-8");
        writer.print("[");
        boolean isFirst = true;
        while (i < idList.size()) {
            int startId = idList.get(i);
            i = i + maxDataToGetEachTime - 1;
            int endId = (i >= idList.size() ? idList.getLast() : idList.get(i));
            i++;
            List<DataInfo<Object>> dataInfoList = getDataByRange(Object.class, startId, endId);
            for (DataInfo<Object> dataInfo : dataInfoList) {
                if (!isFirst) {
                    writer.println(",");
                } else {
                    isFirst = false;
                }
                writer.print(dataInfo.toString());
            }
        }
        writer.println("]");
    } catch (Exception e) {
        throw new DataStoreClientException("Failed to save data to file", e);
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:com.google.enterprise.connector.filesystem.FileConnectorTypeTest.java

/**
 * Make sure HTML tags in {@code s} are balanced.
 *
 * @param s/* w ww.  ja  v a2  s.  c om*/
 */
private void assertBalancedTags(String s) {
    LinkedList<String> stack = Lists.newLinkedList();
    Matcher m = TAG.matcher(s);
    int start = 0;
    while (m.find(start)) {
        String tag = s.substring(m.start(), m.end());

        if (isOpenTag(tag)) {
            stack.addFirst(tag);
        } else if (isCloseTag(tag)) {
            String open = stack.poll();
            assertNotNull(String.format("extra tag: %s", tag), open);
            assertEquals(String.format("mismatched tags: %s vs %s", open, tag), getName(open), getName(tag));
        } else {
            // Ignore open-closed tags (<tag/>).
        }
        start = m.end();
    }
    assertEquals("Open tags at end of input", 0, stack.size());
}

From source file:com.google.ie.business.service.impl.IdeaServiceImpl.java

@SuppressWarnings("unchecked")
@Override//from   w  ww  .j av  a2  s  .  c  o  m
public LinkedList<Idea> getRecentlyPickedIdeas() {
    /* First check the cache for the data */
    LinkedList<Idea> recentlyPickedIdeas = (LinkedList<Idea>) CacheHelper
            .getObject(CacheConstants.IDEA_NAMESPACE, CacheConstants.RECENTLY_PICKED_IDEAS);
    if (recentlyPickedIdeas != null && recentlyPickedIdeas.size() > ServiceConstants.ZERO) {
        logger.info("Recently picked ideas successfully fetched from cache");
        return recentlyPickedIdeas;
    }
    /*
     * Get the recently created projects.Iterate through the list and fetch
     * key of idea related to the project
     */
    List<Project> recentProjects = projectService.getRecentProjects();
    List<Idea> ideas = new ArrayList<Idea>();
    Iterator<Project> iterator = recentProjects.iterator();
    Set<String> setOfIdeaKeys = new HashSet<String>();
    while (iterator.hasNext()) {
        String ideaKey = iterator.next().getIdeaKey();
        if (!setOfIdeaKeys.contains(ideaKey)) {
            setOfIdeaKeys.add(ideaKey);
            ideas.add(getIdeaByKey(ideaKey));
        }
    }
    recentlyPickedIdeas = createLinkedListFromTheFetchedData(ideas);
    if (recentlyPickedIdeas.size() > ServiceConstants.ZERO) {
        /* Put the recently picked ideas into the cache */
        CacheHelper.putObject(CacheConstants.IDEA_NAMESPACE, CacheConstants.RECENTLY_PICKED_IDEAS,
                recentlyPickedIdeas, CacheConstants.RECENTLY_PICKED_IDEAS_EXPIRATION_DELAY);
        logger.info("Recently picked ideas successfully added to the cache");
    }
    return recentlyPickedIdeas;
}

From source file:com.commander4j.thread.AutoLabellerThread.java

public void run() {
    logger.debug("AutoLabeller Thread running");
    setSessionID(JUnique.getUniqueID());
    JDBUser user = new JDBUser(getHostID(), getSessionID());
    user.setUserId("interface");
    user.setPassword("interface");
    user.setLoginPassword("interface");
    Common.userList.addUser(getSessionID(), user);
    Common.sd.setData(getSessionID(), "silentExceptions", "Yes", true);

    Boolean dbconnected = false;//from  w ww  . j a v a  2s .  com

    if (Common.hostList.getHost(hostID).isConnected(sessionID) == false) {

        dbconnected = Common.hostList.getHost(hostID).connect(sessionID, hostID);

    } else {
        dbconnected = true;
    }

    if (dbconnected) {

        JDBViewAutoLabellerPrinter alp = new JDBViewAutoLabellerPrinter(getHostID(), getSessionID());
        LinkedList<JDBViewAutoLabellerPrinter> autolabellerList = new LinkedList<JDBViewAutoLabellerPrinter>();

        int noOfMessages = 0;

        while (true) {

            JWait.milliSec(500);

            if (allDone) {
                if (dbconnected) {
                    Common.hostList.getHost(hostID).disconnect(getSessionID());
                }
                return;
            }

            autolabellerList.clear();
            autolabellerList = alp.getModifiedPrinterLines();
            noOfMessages = autolabellerList.size();

            if (noOfMessages > 0) {
                for (int x = 0; x < noOfMessages; x++) {
                    JWait.milliSec(100);

                    JDBViewAutoLabellerPrinter autolabview = autolabellerList.get(x);

                    messageProcessedOK = true;
                    messageError = "";

                    if (autolabview.getPrinterObj().isEnabled()) {
                        logger.debug("Line             =" + autolabview.getAutoLabellerObj().getLine());
                        logger.debug("Line Description =" + autolabview.getAutoLabellerObj().getDescription());
                        logger.debug("Printer ID       =" + autolabview.getPrinterObj().getPrinterID());
                        logger.debug("Printer Enabled  =" + autolabview.getPrinterObj().isEnabled());
                        logger.debug("Export Path      =" + autolabview.getPrinterObj().getExportRealPath());
                        logger.debug("Export Enabled   =" + autolabview.getPrinterObj().isExportEnabled());
                        logger.debug("Export Format    =" + autolabview.getPrinterObj().getExportFormat());
                        logger.debug("Direct Print     =" + autolabview.getPrinterObj().isDirectPrintEnabled());
                        logger.debug("Printer Type     =" + autolabview.getPrinterObj().getPrinterType());
                        logger.debug("Printer IP       =" + autolabview.getPrinterObj().getIPAddress());
                        logger.debug("Printer Port     =" + autolabview.getPrinterObj().getPort());
                        logger.debug("Process Order    =" + autolabview.getLabelDataObj().getProcessOrder());
                        logger.debug("Material         =" + autolabview.getLabelDataObj().getMaterial());
                        logger.debug("Module ID        =" + autolabview.getModuleObj().getModuleId());
                        logger.debug("Module Type      =" + autolabview.getModuleObj().getType());

                        if (autolabview.getPrinterObj().isExportEnabled()) {
                            String exportPath = JUtility.replaceNullStringwithBlank(
                                    JUtility.formatPath(autolabview.getPrinterObj().getExportRealPath()));
                            if (exportPath.equals("") == false) {
                                if (exportPath.substring(exportPath.length() - 1)
                                        .equals(File.separator) == false) {
                                    exportPath = exportPath + File.separator;
                                }
                            } else {
                                exportPath = Common.interface_output_path + "Auto Labeller" + File.separator;
                            }

                            String exportFilename = exportPath
                                    + JUtility.removePathSeparators(autolabview.getAutoLabellerObj().getLine())
                                    + "_"
                                    + JUtility.removePathSeparators(autolabview.getPrinterObj().getPrinterID())
                                    + "." + autolabview.getPrinterObj().getExportFormat();

                            String exportFilenameTemp = exportFilename + ".out";

                            logger.debug("Export Filename  =" + exportFilename);

                            /* ================CSV================ */

                            if (autolabview.getPrinterObj().getExportFormat().equals("CSV")) {
                                try {
                                    PreparedStatement stmt = null;
                                    ResultSet rs;
                                    String labelType = autolabview.getLabelDataObj().getLabelType();
                                    stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID())
                                            .prepareStatement(
                                                    Common.hostList.getHost(getHostID()).getSqlstatements()
                                                            .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties"
                                                                    + "_" + labelType));
                                    stmt.setString(1, autolabview.getAutoLabellerObj().getLine());
                                    stmt.setString(2, autolabview.getPrinterObj().getPrinterID());
                                    stmt.setFetchSize(50);

                                    rs = stmt.executeQuery();

                                    logger.debug("Writing CSV");

                                    CSVWriter writer = new CSVWriter(new FileWriter(exportFilenameTemp),
                                            CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER,
                                            CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);

                                    writer.writeAll(rs, true);

                                    rs.close();

                                    stmt.close();

                                    writer.close();

                                    File fromFile = new File(exportFilenameTemp);
                                    File toFile = new File(exportFilename);

                                    FileUtils.deleteQuietly(toFile);
                                    FileUtils.moveFile(fromFile, toFile);

                                    fromFile = null;
                                    toFile = null;

                                } catch (Exception e) {
                                    messageProcessedOK = false;
                                    messageError = e.getMessage();
                                }
                            }

                            /* ================XML================ */

                            if (autolabview.getPrinterObj().getExportFormat().equals("XML")) {
                                try {
                                    PreparedStatement stmt = null;
                                    ResultSet rs;

                                    stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID())
                                            .prepareStatement(Common.hostList.getHost(getHostID())
                                                    .getSqlstatements()
                                                    .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties"));
                                    stmt.setString(1, autolabview.getAutoLabellerObj().getLine());
                                    stmt.setString(2, autolabview.getPrinterObj().getPrinterID());
                                    stmt.setFetchSize(50);

                                    rs = stmt.executeQuery();
                                    ResultSetMetaData rsmd = rs.getMetaData();
                                    int colCount = rsmd.getColumnCount();

                                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                                    DocumentBuilder builder = factory.newDocumentBuilder();
                                    Document document = builder.newDocument();

                                    Element message = (Element) document.createElement("message");

                                    Element hostUniqueID = addElement(document, "hostRef",
                                            Common.hostList.getHost(getHostID()).getUniqueID());
                                    message.appendChild(hostUniqueID);

                                    Element messageRef = addElement(document, "messageRef",
                                            autolabview.getAutoLabellerObj().getUniqueID());
                                    message.appendChild(messageRef);

                                    Element messageType = addElement(document, "interfaceType",
                                            "Auto Labeller Data");
                                    message.appendChild(messageType);

                                    Element messageInformation = addElement(document, "messageInformation",
                                            "Unique ID=" + autolabview.getAutoLabellerObj().getUniqueID());
                                    message.appendChild(messageInformation);

                                    Element messageDirection = addElement(document, "interfaceDirection",
                                            "Output");
                                    message.appendChild(messageDirection);

                                    Element messageDate = addElement(document, "messageDate",
                                            JUtility.getISOTimeStampStringFormat(JUtility.getSQLDateTime()));
                                    message.appendChild(messageDate);

                                    if (rs.first()) {

                                        Element labelData = (Element) document.createElement("LabelData");

                                        Element row = document.createElement("Row");
                                        labelData.appendChild(row);
                                        for (int i = 1; i <= colCount; i++) {
                                            String columnName = rsmd.getColumnName(i);
                                            Object value = rs.getObject(i);
                                            Element node = document.createElement(columnName);
                                            node.appendChild(document.createTextNode(value.toString()));
                                            row.appendChild(node);
                                        }

                                        message.appendChild(labelData);

                                        document.appendChild(message);

                                        JXMLDocument xmld = new JXMLDocument();
                                        xmld.setDocument(document);

                                        // ===============================

                                        DOMImplementationLS DOMiLS = null;
                                        FileOutputStream FOS = null;

                                        // testing the support for DOM
                                        // Load and Save
                                        if ((document.getFeature("Core", "3.0") != null)
                                                && (document.getFeature("LS", "3.0") != null)) {
                                            DOMiLS = (DOMImplementationLS) (document.getImplementation())
                                                    .getFeature("LS", "3.0");

                                            // get a LSOutput object
                                            LSOutput LSO = DOMiLS.createLSOutput();

                                            FOS = new FileOutputStream(exportFilename);
                                            LSO.setByteStream((OutputStream) FOS);

                                            // get a LSSerializer object
                                            LSSerializer LSS = DOMiLS.createLSSerializer();

                                            // do the serialization
                                            LSS.write(document, LSO);

                                            FOS.close();
                                        }

                                        // ===============================

                                    }
                                    rs.close();
                                    stmt.close();

                                } catch (Exception e) {
                                    messageError = e.getMessage();
                                }

                            }

                            if (autolabview.getPrinterObj().getExportFormat().equals("LQF")) {

                            }
                        }

                        if (autolabview.getPrinterObj().isDirectPrintEnabled()) {

                        }

                    }

                    if (messageProcessedOK == true) {
                        autolabview.getAutoLabellerObj().setModified(false);
                        autolabview.getAutoLabellerObj().update();
                    } else {
                        logger.debug(messageError);
                    }

                    autolabview = null;
                }
            }
        }
    }
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcMultiRowRecordWriter.java

@SuppressWarnings("unchecked")
private void processPartition(Connection connection, Multimap<Long, Record> partitions, Long partitionKey,
        List<OnRecordErrorException> errorRecords) throws SQLException, OnRecordErrorException {
    Collection<Record> partition = partitions.get(partitionKey);
    // Fetch the base insert query for this partition.
    SortedMap<String, String> columnsToParameters = getFilteredColumnsToParameters(getColumnsToParameters(),
            partition.iterator().next());

    // put all the records in a queue for consumption
    LinkedList<Record> queue = new LinkedList<>(partition);

    // compute number of rows per batch
    if (columnsToParameters.isEmpty()) {
        throw new OnRecordErrorException(Errors.JDBCDEST_22);
    }//  www  . ja  va2s. co  m
    int maxRowsPerBatch = maxPrepStmtParameters / columnsToParameters.size();

    PreparedStatement statement = null;

    // parameters are indexed starting with 1
    int paramIdx = 1;
    int rowCount = 0;
    while (!queue.isEmpty()) {
        // we're at the start of a batch.
        if (statement == null) {
            // instantiate the new statement
            statement = generatePreparedStatement(columnsToParameters,
                    // the next batch will have either the max number of records, or however many are left.
                    Math.min(maxRowsPerBatch, queue.size()), getTableName(), connection);
        }

        // process the next record into the current statement
        Record record = queue.removeFirst();
        for (String column : columnsToParameters.keySet()) {
            Field field = record.get(getColumnsToFields().get(column));
            Field.Type fieldType = field.getType();
            Object value = field.getValue();

            try {
                switch (fieldType) {
                case LIST:
                    List<Object> unpackedList = unpackList((List<Field>) value);
                    Array array = connection.createArrayOf(getSQLTypeName(fieldType), unpackedList.toArray());
                    statement.setArray(paramIdx, array);
                    break;
                case DATE:
                case DATETIME:
                    // Java Date types are not accepted by JDBC drivers, so we need to convert to java.sql.Date
                    java.util.Date date = field.getValueAsDatetime();
                    statement.setObject(paramIdx, new java.sql.Date(date.getTime()));
                    break;
                default:
                    statement.setObject(paramIdx, value, getColumnType(column));
                    break;
                }
            } catch (SQLException e) {
                LOG.error(Errors.JDBCDEST_23.getMessage(), column, fieldType.toString(), e);
                throw new OnRecordErrorException(record, Errors.JDBCDEST_23, column, fieldType.toString());
            }
            ++paramIdx;
        }

        rowCount++;

        // check if we've filled up the current batch
        if (rowCount == maxRowsPerBatch) {
            // time to execute the current batch
            statement.addBatch();
            statement.executeBatch();
            statement.close();
            statement = null;

            // reset our counters
            rowCount = 0;
            paramIdx = 1;
        }
    }

    // check if there are any records left. this should occur whenever there isn't *exactly* maxRowsPerBatch records in
    // this partition.
    if (statement != null) {
        statement.addBatch();
        statement.executeBatch();
        statement.close();
    }
}

From source file:com.facebook.react.views.textinput.ReactTextInputManager.java

@ReactProp(name = "maxLength")
public void setMaxLength(ReactEditText view, @Nullable Integer maxLength) {
    InputFilter[] currentFilters = view.getFilters();
    InputFilter[] newFilters = EMPTY_FILTERS;

    if (maxLength == null) {
        if (currentFilters.length > 0) {
            LinkedList<InputFilter> list = new LinkedList<>();
            for (int i = 0; i < currentFilters.length; i++) {
                if (!(currentFilters[i] instanceof InputFilter.LengthFilter)) {
                    list.add(currentFilters[i]);
                }/*from   www  . j a v  a 2 s  . c  om*/
            }
            if (!list.isEmpty()) {
                newFilters = (InputFilter[]) list.toArray(new InputFilter[list.size()]);
            }
        }
    } else {
        if (currentFilters.length > 0) {
            newFilters = currentFilters;
            boolean replaced = false;
            for (int i = 0; i < currentFilters.length; i++) {
                if (currentFilters[i] instanceof InputFilter.LengthFilter) {
                    currentFilters[i] = new InputFilter.LengthFilter(maxLength);
                    replaced = true;
                }
            }
            if (!replaced) {
                newFilters = new InputFilter[currentFilters.length + 1];
                System.arraycopy(currentFilters, 0, newFilters, 0, currentFilters.length);
                currentFilters[currentFilters.length] = new InputFilter.LengthFilter(maxLength);
            }
        } else {
            newFilters = new InputFilter[1];
            newFilters[0] = new InputFilter.LengthFilter(maxLength);
        }
    }

    view.setFilters(newFilters);
}

From source file:com.bluros.updater.service.UpdateCheckService.java

private void recordAvailableUpdates(LinkedList<UpdateInfo> availableUpdates, Intent finishedIntent) {

    if (availableUpdates == null) {
        sendBroadcast(finishedIntent);/*from   w w  w  .  java  2s .co m*/
        return;
    }

    // Store the last update check time and ensure boot check completed is true
    Date d = new Date();
    PreferenceManager.getDefaultSharedPreferences(UpdateCheckService.this).edit()
            .putLong(Constants.LAST_UPDATE_CHECK_PREF, d.getTime())
            .putBoolean(Constants.BOOT_CHECK_COMPLETED, true).apply();

    int realUpdateCount = finishedIntent.getIntExtra(EXTRA_REAL_UPDATE_COUNT, 0);
    UpdateApplication app = (UpdateApplication) getApplicationContext();

    // Write to log
    Log.i(TAG, "The update check successfully completed at " + d + " and found " + availableUpdates.size()
            + " updates (" + realUpdateCount + " newer than installed)");

    if (realUpdateCount != 0 && !app.isMainActivityActive()) {
        // There are updates available
        // The notification should launch the main app
        Intent i = new Intent(this, UpdatesSettings.class);
        i.putExtra(UpdatesSettings.EXTRA_UPDATE_LIST_UPDATED, true);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_ONE_SHOT);

        Resources res = getResources();
        String text = res.getQuantityString(R.plurals.not_new_updates_found_body, realUpdateCount,
                realUpdateCount);

        // Get the notification ready
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_system_update).setWhen(System.currentTimeMillis())
                .setTicker(res.getString(R.string.not_new_updates_found_ticker))
                .setContentTitle(res.getString(R.string.not_new_updates_found_title)).setContentText(text)
                .setContentIntent(contentIntent).setLocalOnly(true).setAutoCancel(true);

        LinkedList<UpdateInfo> realUpdates = new LinkedList<UpdateInfo>();
        for (UpdateInfo ui : availableUpdates) {
            if (ui.isNewerThanInstalled()) {
                realUpdates.add(ui);
            }
        }

        Collections.sort(realUpdates, new Comparator<UpdateInfo>() {
            @Override
            public int compare(UpdateInfo lhs, UpdateInfo rhs) {
                /* sort by date descending */
                long lhsDate = lhs.getDate();
                long rhsDate = rhs.getDate();
                if (lhsDate == rhsDate) {
                    return 0;
                }
                return lhsDate < rhsDate ? 1 : -1;
            }
        });

        NotificationCompat.InboxStyle inbox = new NotificationCompat.InboxStyle(builder)
                .setBigContentTitle(text);
        int added = 0, count = realUpdates.size();

        for (UpdateInfo ui : realUpdates) {
            if (added < EXPANDED_NOTIF_UPDATE_COUNT) {
                inbox.addLine(ui.getName());
                added++;
            }
        }
        if (added != count) {
            inbox.setSummaryText(
                    res.getQuantityString(R.plurals.not_additional_count, count - added, count - added));
        }
        builder.setStyle(inbox);
        builder.setNumber(availableUpdates.size());

        if (count == 1) {
            i = new Intent(this, DownloadReceiver.class);
            i.setAction(DownloadReceiver.ACTION_START_DOWNLOAD);
            i.putExtra(DownloadReceiver.EXTRA_UPDATE_INFO, (Parcelable) realUpdates.getFirst());
            PendingIntent downloadIntent = PendingIntent.getBroadcast(this, 0, i,
                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

            builder.addAction(R.drawable.ic_tab_download, res.getString(R.string.not_action_download),
                    downloadIntent);
        }

        // Trigger the notification
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.notify(R.string.not_new_updates_found_title, builder.build());
    }

    sendBroadcast(finishedIntent);
}