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:de.vandermeer.asciitable.AT_Renderer.java

/**
 * Renders an {@link AsciiTable}.//ww w  . ja v  a 2  s  . c  om
 * @param rows table rows to render, cannot be null
 * @param colNumbers number of columns in the table
 * @param ctx context of the original table with relevant settings, cannot be null
 * @param width maximum line width, excluding any extra padding
 * @return collection of lines, each as a {@link StrBuilder}
 * @throws {@link NullPointerException} if rows or context where null
 */
default Collection<StrBuilder> renderAsCollection(LinkedList<AT_Row> rows, int colNumbers, AT_Context ctx,
        int width) {
    Validate.notNull(rows);
    Validate.notNull(ctx);

    ArrayList<Object> table = new ArrayList<>();
    int[] colWidth = this.getCWC().calculateColumnWidths(rows, colNumbers, ctx.getTextWidth(width));

    for (AT_Row row : rows) {
        int ruleset = 0;
        switch (row.getStyle()) {
        case NORMAL:
            ruleset = TA_GridConfig.RULESET_NORMAL;
            break;
        case STRONG:
            ruleset = TA_GridConfig.RULESET_STRONG;
            break;
        case LIGHT:
            ruleset = TA_GridConfig.RULESET_LIGHT;
            break;
        case HEAVY:
            ruleset = TA_GridConfig.RULESET_HEAVY;
            break;
        case UNKNOWN:
            throw new AsciiTableException("AT_Renderer: cannot render unknown row style",
                    "table row style set to 'unknown'");
        default:
            throw new AsciiTableException("AT_Renderer: cannot render unknown row style",
                    "table row style not specified or type not processed");
        }

        switch (row.getType()) {
        case RULE:
            table.add(ruleset);
            break;
        case CONTENT:
            String[][] cAr = new String[colNumbers][];
            LinkedList<AT_Cell> cells = row.getCells();
            if (cells == null) {
                throw new AsciiTableException("cannot render table", "row content (cells) was null");
            }

            int length = 0;
            for (int i = 0; i < cells.size(); i++) {
                length += colWidth[i];

                Object content = cells.get(i).getContent();
                if (content == null) {
                    length++;
                    continue;
                }

                int realWidth = length;
                length -= cells.get(i).getContext().getPaddingLeft();
                length -= cells.get(i).getContext().getPaddingRight();

                if (content instanceof RendersToClusterWidth) {
                    cAr[i] = ((RendersToClusterWidth) content).renderAsArray(length);
                }
                if (content instanceof DoesRenderToWidth) {
                    cAr[i] = new StrTokenizer(((DoesRenderToWidth) content).render(length))
                            .setDelimiterChar('\n').setIgnoreEmptyTokens(false).getTokenArray();
                } else {
                    //create text from cell object
                    String text = Object_To_StrBuilder.convert(content).toString().replaceAll("\\s+", " ");

                    //check for translators, use what is available
                    if (cells.get(i).getContext().getTargetTranslator() != null) {
                        if (cells.get(i).getContext().getTargetTranslator().getCombinedTranslator() != null) {
                            text = cells.get(i).getContext().getTargetTranslator().getCombinedTranslator()
                                    .translate(text);
                        }
                    } else if (cells.get(i).getContext().getHtmlElementTranslator() != null) {
                        text = cells.get(i).getContext().getHtmlElementTranslator().translateHtmlElements(text);
                    } else if (cells.get(i).getContext().getCharTranslator() != null) {
                        text = cells.get(i).getContext().getCharTranslator().translateCharacters(text);
                    }

                    Collection<StrBuilder> csb = Text_To_FormattedText
                            .create(length, cells.get(i).getContext().getTextAlignment().getMapping(),
                                    TextFormat.NONE.getMapping(), null, null, null, 0, 0, null, 0, 0, null)
                            .transform(text);
                    for (StrBuilder sb : csb) {
                        sb.insert(0, new StrBuilder().appendPadding(cells.get(i).getContext().getPaddingLeft(),
                                cells.get(i).getContext().getPaddingLeftChar()));
                        sb.appendPadding(cells.get(i).getContext().getPaddingRight(),
                                cells.get(i).getContext().getPaddingRightChar());
                    }
                    for (int k = 0; k < cells.get(i).getContext().getPaddingTop(); k++) {
                        ((ArrayList<StrBuilder>) csb).add(0, new StrBuilder().appendPadding(realWidth,
                                cells.get(i).getContext().getPaddingTopChar()));
                    }
                    for (int k = 0; k < cells.get(i).getContext().getPaddingBottom(); k++) {
                        ((ArrayList<StrBuilder>) csb).add(new StrBuilder().appendPadding(realWidth,
                                cells.get(i).getContext().getPaddingBottomChar()));
                    }

                    cAr[i] = ClusterElementTransformer.create()
                            .transform(csb, StrBuilder_To_String.create(), ArrayListStrategy.create())
                            .toArray(new String[0]);
                }
                length = 0;
            }
            cAr = Array2D_To_NormalizedArray.create(colNumbers).transform(cAr);
            cAr = Array2D_To_FlipArray.create().transform(cAr);
            table.add(Pair.of(ruleset, cAr));
            break;
        case UNKNOWN:
            throw new AsciiTableException("AT_Renderer: cannot render unknown row type",
                    "table row type set to 'unknown'");
        default:
            throw new AsciiTableException("AT_Renderer: cannot render unknown row type",
                    "table row type not specified or type not processed");
        }
    }

    ArrayList<StrBuilder> ret = ctx.getGrid().addGrid(table, ctx.getGridTheme() | ctx.getGridThemeOptions());
    int max = ret.get(0).length() + ctx.getFrameLeftMargin() + ctx.getFrameRightMargin();
    for (StrBuilder sb : ret) {
        sb.insert(0, new StrBuilder().appendPadding(ctx.getFrameLeftMargin(), ctx.getFrameLeftChar()));
        sb.appendPadding(ctx.getFrameRightMargin(), ctx.getFrameRightChar());
    }
    for (int k = 0; k < ctx.getFrameTopMargin(); k++) {
        ret.add(0, new StrBuilder().appendPadding(max, ctx.getFrameTopChar()));
    }
    for (int k = 0; k < ctx.getFrameBottomMargin(); k++) {
        ret.add(new StrBuilder().appendPadding(max, ctx.getFrameBottomChar()));
    }

    return ret;
}

From source file:com.espertech.esper.epl.core.ResultSetProcessorSimple.java

/**
 * Applies the select-clause to the given events returning the selected events. The number of events stays the
 * same, i.e. this method does not filter it just transforms the result set.
 * <p>/*from  w  w w.  j  a v  a  2 s .c o m*/
 * Also applies a having clause.
 * @param exprProcessor - processes each input event and returns output event
 * @param orderByProcessor - for sorting output events according to the order-by clause
 * @param events - input events
 * @param optionalHavingNode - supplies the having-clause expression
 * @param isNewData - indicates whether we are dealing with new data (istream) or old data (rstream)
 * @param isSynthesize - set to true to indicate that synthetic events are required for an iterator result set
 * @param exprEvaluatorContext context for expression evalauation
 * @return output events, one for each input event
 */
protected static EventBean[] getSelectEventsHaving(SelectExprProcessor exprProcessor,
        OrderByProcessor orderByProcessor, Set<MultiKey<EventBean>> events, ExprEvaluator optionalHavingNode,
        boolean isNewData, boolean isSynthesize, ExprEvaluatorContext exprEvaluatorContext) {
    if ((events == null) || (events.isEmpty())) {
        return null;
    }

    LinkedList<EventBean> result = new LinkedList<EventBean>();
    List<EventBean[]> eventGenerators = null;
    if (orderByProcessor != null) {
        eventGenerators = new ArrayList<EventBean[]>();
    }

    for (MultiKey<EventBean> key : events) {
        EventBean[] eventsPerStream = key.getArray();

        Boolean passesHaving = (Boolean) optionalHavingNode.evaluate(eventsPerStream, isNewData,
                exprEvaluatorContext);
        if ((passesHaving == null) || (!passesHaving)) {
            continue;
        }

        EventBean resultEvent = exprProcessor.process(eventsPerStream, isNewData, isSynthesize,
                exprEvaluatorContext);
        result.add(resultEvent);
        if (orderByProcessor != null) {
            eventGenerators.add(eventsPerStream);
        }
    }

    if (!result.isEmpty()) {
        if (orderByProcessor != null) {
            return orderByProcessor.sort(result.toArray(new EventBean[result.size()]),
                    eventGenerators.toArray(new EventBean[eventGenerators.size()][]), isNewData,
                    exprEvaluatorContext);
        } else {
            return result.toArray(new EventBean[result.size()]);
        }
    } else {
        return null;
    }
}

From source file:com.swordlord.gozer.databinding.DataBindingManager.java

/**
 * TODO need to merge with getResolvedRow(LinkedList<DataBindingElement>
 * elements, String strTableName, DataRowBase rowFather). Today there is too
 * many risk. We need a better Parser and a lot of JUnit Tests.
 * //from   w  ww.  j av  a  2  s  .co m
 * @param elements
 * @param strTableName
 * @param rowFather
 * @return
 */
public DataRowBase[] getResolvedRows(LinkedList<DataBindingElement> elements, String strTableName,
        DataRowBase rowFather) {
    if ((elements == null) || (elements.size() == 0)) {
        LOG.error("elements is empty");
    }

    ArrayList<DataRowBase> dataRowBaseLst = new ArrayList<DataRowBase>();
    boolean rowFound = false;
    for (DataBindingElement element : elements) {
        if (!element.isField()) {
            String strPathElement = element.getPathElement();

            // ignore the same level
            if (strPathElement.compareToIgnoreCase(strTableName) != 0) {
                Object property = rowFather.getProperty(strPathElement);
                if (property == null) {
                    return new DataRowBase[0];
                } else {
                    if (property instanceof DataRowBase) {
                        rowFather = (DataRowBase) property;
                        rowFound = true;
                    } else if (property instanceof ToManyList) {
                        ToManyList list = (ToManyList) property;
                        if (list.size() > 0) {
                            if (elements.get(elements.size() - 2).equals(element)) { // Last element without field name
                                if (list.getValueDirectly() == null) {
                                    try {
                                        rowFather = (DataRowBase) list.get(element.getRowNumber());
                                        rowFound = true;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        return new DataRowBase[0];
                                    }
                                    dataRowBaseLst.add(rowFather);
                                    return dataRowBaseLst.toArray(new DataRowBase[dataRowBaseLst.size()]);
                                } else {
                                    List<DataRowBase> lst = (List) list.getValueDirectly();
                                    return lst.toArray(new DataRowBase[lst.size()]);
                                }
                            } else {
                                rowFather = (DataRowBase) list.get(element.getRowNumber());
                                rowFound = true;
                            }
                        }
                    }
                }
                // this is some nice side effect where we just loop as long
                // as we
                // are not at the right level
            }
        }
    }

    if (rowFound) {
        dataRowBaseLst.add(rowFather);
        return dataRowBaseLst.toArray(new DataRowBase[dataRowBaseLst.size()]);
    } else {
        return new DataRowBase[0];
    }
}

From source file:org.elasticwarehouse.core.ElasticWarehouseAPIProcessorTask.java

public boolean processRequest(Client esClient, OutputStream os, ElasticWarehouseAPIProcessorTaskParams params)
        throws IOException {
    if (params.action == null && params.status == null && params.list == null && params.cancel == null) {
        os.write(responser.errorMessage("'action', 'status', 'cancel' or 'list' are expected.",
                ElasticWarehouseConf.URL_GUIDE_TASK));
    } else if (params.action != null) {
        params.action = params.action.toLowerCase();
        if (params.action.equals("scan")) {
            /*String path = request.getParameter("path");
            String targetfolder = request.getParameter("targetfolder");
            String recurrence = request.getParameter("recurrence");
            boolean brecurrence = false;
            //if( targetfolder == null )
            //   targetfolder = ResourceTools.preprocessFolderName(path);
            if( recurrence != null )/*from  www  . j a  v  a 2  s  .c om*/
               brecurrence = Boolean.parseBoolean(recurrence);*/

            if (params.path == null) {
                os.write(responser.errorMessage("path is needed for scan action.",
                        ElasticWarehouseConf.URL_GUIDE_TASK));
            } else {
                ElasticWarehouseTask taskUUID = tasksManager_.launchScan(params.path, params.targetfolder,
                        params.recurrence, params.keepalive, params.newerthan);
                os.write(responser.taskAcceptedMessage("Scanning " + params.path, 0, taskUUID));
            }
        } else if (params.action.equals("rethumb")) {
            ElasticWarehouseTask taskUUID = tasksManager_.launchRethumb();
            os.write(responser.taskAcceptedMessage("Started thumbnails regeneration", 0, taskUUID));
        } else if (params.action.equals("mkdir")) {
            //String folder = request.getParameter("folder");
            if (params.folder == null) {
                os.write(responser.errorMessage("folder is needed for mkdir action.",
                        ElasticWarehouseConf.URL_GUIDE_TASK));
            } else {
                ElasticWarehouseTask taskUUID = tasksManager_.createFolder(params.folder);
                os.write(responser.taskAcceptedMessage("mkdir " + params.folder, 0, taskUUID));
            }
        } else if (params.action.equals("rmdir")) {
            //String folder = request.getParameter("folder");
            if (params.folder == null) {
                os.write(responser.errorMessage("folder is needed for rmdir action.",
                        ElasticWarehouseConf.URL_GUIDE_TASK));
            } else {
                ElasticWarehouseTask taskUUID = tasksManager_.removeFolder(params.folder);
                os.write(responser.taskAcceptedMessage("rmdir " + params.folder, 0, taskUUID));
            }
        } else if (params.action.equals("move")) {
            //String folder = request.getParameter("folder");
            //String id = request.getParameter("id");
            if (params.id == null) {
                os.write(responser.errorMessage("Please provide id of file to be moved.",
                        ElasticWarehouseConf.URL_GUIDE_TASK));
            } else if (params.folder == null) {
                os.write(responser.errorMessage("folder is needed for move action.",
                        ElasticWarehouseConf.URL_GUIDE_TASK));
            } else {
                ElasticWarehouseTask taskUUID = tasksManager_.moveTo(params.id, params.folder);
                os.write(responser.taskAcceptedMessage("move id=" + params.id + " to " + params.folder, 0,
                        taskUUID));
            }
        } else if (params.action.equals("rename")) {
            if (params.id == null) {
                os.write(responser.errorMessage("Please provide id of file or folder to be renamed.",
                        ElasticWarehouseConf.URL_GUIDE_TASK));
            } else if (params.targetname == null || params.targetname.length() == 0) {
                os.write(responser.errorMessage("targetname cannot be empty.",
                        ElasticWarehouseConf.URL_GUIDE_TASK));
            } else {
                //check if any other task is running on current item
                LinkedList<String> ctasks = tasksManager_.getTasks(false,
                        conf_.getNodeName()/* NetworkTools.getHostName()*/, 999, 0, false, true, params.id);
                if (ctasks.size() > 0) {
                    os.write(responser.errorMessage(
                            "Another task is running on current item. Try again later or cancel tasks:"
                                    + ctasks.toString(),
                            ElasticWarehouseConf.URL_GUIDE_TASK));
                } else {
                    ElasticWarehouseTask taskUUID = tasksManager_.rename(params.id, params.targetname);
                    os.write(responser.taskAcceptedMessage("rename id=" + params.id, 0, taskUUID));
                }
            }
        } else if (params.action.equals("delete")) {
            //String id = request.getParameter("id");
            if (params.id == null) {
                os.write(responser.errorMessage("Please provide id of file to be deleted.",
                        ElasticWarehouseConf.URL_GUIDE_TASK));
            } else {
                ElasticWarehouseTask taskUUID = tasksManager_.delete(params.id);
                os.write(responser.taskAcceptedMessage("delete id=" + params.id, 0, taskUUID));
            }
        } else {
            os.write(responser.errorMessage("Unknown task action.", ElasticWarehouseConf.URL_GUIDE_TASK));
        }
    } else if (params.status != null) {
        ElasticWarehouseTask task = tasksManager_.getTask(params.status, true);
        if (task != null) {
            os.write(task.getJsonSourceBuilder().string().getBytes());
        } else {
            os.write(responser.errorMessage("Unknown task Id " + params.status,
                    ElasticWarehouseConf.URL_GUIDE_TASK));
        }
    } else if (params.cancel != null) {
        ElasticWarehouseTask task = tasksManager_.getTask(params.cancel, true);
        if (task != null) {
            if (task.finished()) {
                os.write(responser.errorMessage(
                        "Task Id " + params.cancel + " is finished and cannot be cancelled.",
                        ElasticWarehouseConf.URL_GUIDE_TASK));
            } else {
                task = tasksManager_.cancelTask(params.cancel);
                if (task == null)
                    os.write(responser.errorMessage(
                            "Task Id: " + params.cancel + " is no longer running and cannot be cancelled.",
                            ElasticWarehouseConf.URL_GUIDE_TASK));
                else
                    os.write(task.getJsonSourceBuilder().string().getBytes());
            }
        } else {
            os.write(responser.errorMessage("Unknown task Id " + params.status,
                    ElasticWarehouseConf.URL_GUIDE_TASK));
        }
    } else if (params.list != null) {
        params.list = params.list.toLowerCase();

        //int size = ParseTools.parseIntDirect(request.getParameter("size"), ElasticWarehouseConf.TASKLISTSIZE);
        //int from = ParseTools.parseIntDirect(request.getParameter("from"), 0);

        LinkedList<String> tasks = null;
        if (params.list.equals("active"))
            tasks = tasksManager_.getTasks(false, conf_.getNodeName()/* NetworkTools.getHostName()*/,
                    params.size, params.from, params.showrequest, params.allhosts);
        else
            tasks = tasksManager_.getTasks(null, conf_.getNodeName() /*NetworkTools.getHostName()*/,
                    params.size, params.from, params.showrequest, params.allhosts);

        XContentBuilder builder = jsonBuilder().startArray();
        for (String taskid : tasks) {
            ElasticWarehouseTask task = tasksManager_.getTask(taskid, true);
            if (task == null) {
                throw new IOException("Cannot fetch taskId: " + taskid);
            } else {
                builder = task.getJsonSourceBuilder(builder, true);
            }
        }
        builder.endArray();
        os.write(builder.string().getBytes());
    }
    return true;
}

From source file:com.mirth.connect.client.ui.components.MirthTree.java

/**
 * Construct a path for a specific node.
 * //  www .j  av  a2  s  .c o m
 * @param parent
 * @param prefix
 * @param suffix
 * @return
 */
public static StringBuilder constructPath(TreeNode parent, String prefix, String suffix) {
    StringBuilder sb = new StringBuilder();
    sb.insert(0, prefix);

    MirthTreeNode node = (MirthTreeNode) parent;
    SerializationType serializationType = node.getSerializationType();

    // Get the parent if the leaf was actually passed in instead of the parent.
    if (node.isLeaf()) {
        node = (MirthTreeNode) node.getParent();
    }

    /*
     * MIRTH-3196 - We now assign nodes types as we iterate from child to parent to add more
     * versatility to namespace drag and drop. The drag and drop can drag nodes, attribute or
     * namespace attributes so the user should be able to correctly do these now. If a node has
     * a namespace then will wildcard it. If an ancestor of the node has an implicit namespace
     * then we will also append a wildcard. The only exception to this is if the implicit
     * namespace is on the root node, we actually set this to the default namespace in
     * JavaScriptBuilder.
     */

    LinkedList<PathNode> nodeQ = new LinkedList<PathNode>();
    while (node != null && node.getParent() != null) {
        if (serializationType.equals(SerializationType.JSON) && node.isArrayElement()) {
            nodeQ.add(new PathNode(String.valueOf(node.getParent().getIndex(node) - 1),
                    PathNode.NodeType.ARRAY_CHILD));
        } else {

            PathNode.NodeType type = PathNode.NodeType.OTHER;
            if (serializationType.equals(SerializationType.XML)) {
                type = getXmlNodeType(node);
            }

            String nodeValue = node.getValue().replaceAll(" \\(.*\\)", "");
            nodeQ.add(new PathNode(nodeValue, type));

            if (serializationType.equals(SerializationType.XML)) {
                int parentIndexValue = getIndexOfNode(node);
                if (parentIndexValue != -1) {
                    nodeQ.add(nodeQ.size() - 1,
                            new PathNode(String.valueOf(parentIndexValue), PathNode.NodeType.ARRAY_CHILD));
                }
            }
        }
        node = (MirthTreeNode) node.getParent();
    }

    boolean foundImplicitNamespace = false;

    while (!nodeQ.isEmpty()) {
        PathNode nodeValue = nodeQ.removeLast();

        //We start at the parent so if any implicit namespaces are reached then the rest of the nodes should wildcard the namespace
        boolean includeNamespace = false;
        PathNode.NodeType type = nodeValue.getType();

        //We don't want to include a wildcard for attributes, ns definitions or array indices
        if (serializationType.equals(SerializationType.XML) && !Arrays
                .asList(PathNode.NodeType.XML_ATTRIBUTE, PathNode.NodeType.XMLNS_DEFINITION,
                        PathNode.NodeType.XML_PREFIX_DEFINITION, PathNode.NodeType.ARRAY_CHILD)
                .contains(type)) {
            if (foundImplicitNamespace) {
                includeNamespace = true;
            } else if (type == PathNode.NodeType.XML_XMLNS_NODE) {
                foundImplicitNamespace = true;
                includeNamespace = true;
            } else if (type == PathNode.NodeType.XML_PREFIXED_NODE) {
                includeNamespace = true;
            }
        }

        if (includeNamespace) {
            int colonIndex = nodeValue.getValue().indexOf(':') + 1;
            sb.append(".*::['" + StringUtils.substring(nodeValue.getValue(), colonIndex) + "']");
        } else if (serializationType.equals(SerializationType.XML)
                && type == PathNode.NodeType.XMLNS_DEFINITION) {
            sb.append(".namespace('')");
        } else if (serializationType.equals(SerializationType.XML)
                && type == PathNode.NodeType.XML_PREFIX_DEFINITION) {
            sb.append(".namespace('" + StringUtils.substringAfter(nodeValue.getValue(), "@xmlns:") + "')");
        } else if (type == PathNode.NodeType.XML_PREFIXED_ATTRIBUTE) {
            sb.append(".@*::['" + StringUtils.substringAfter(nodeValue.getValue(), ":") + "']");
        } else if (type == PathNode.NodeType.ARRAY_CHILD) {
            sb.append("[" + nodeValue.getValue() + "]");
        } else {
            sb.append("['" + nodeValue.getValue() + "']");
        }
    }

    if (!serializationType.equals(SerializationType.JSON)) {
        sb.append(suffix);
    }

    return sb;
}

From source file:com.linkedin.pinot.controller.helix.core.rebalance.ReplicaGroupRebalanceSegmentStrategy.java

/**
 * Uniformly distribute segments across servers in a replica group. It adopts a simple algorithm that pre-computes
 * the number of segments per server after rebalance and tries to assign/remove segments to/from a server until it
 * becomes to have the correct number of segments.
 *
 * @param serversInReplicaGroup A list of servers within the same replica group
 * @param serverToSegments A Mapping of servers to their segments
 *//*from  w ww . j a v  a 2s.  c  o  m*/
private void rebalanceReplicaGroup(List<String> serversInReplicaGroup,
        Map<String, LinkedList<String>> serverToSegments, Set<String> segmentsToCover) {
    // Make sure that all the segments are covered only once within a replica group.
    Set<String> currentCoveredSegments = new HashSet<>();
    for (String server : serversInReplicaGroup) {
        Iterator<String> segmentIter = serverToSegments.get(server).iterator();
        while (segmentIter.hasNext()) {
            String segment = segmentIter.next();
            if (currentCoveredSegments.contains(segment)) {
                segmentIter.remove();
            } else {
                currentCoveredSegments.add(segment);
            }
        }
    }

    // Compute the segments to add
    LinkedList<String> segmentsToAdd = new LinkedList<>(segmentsToCover);
    segmentsToAdd.removeAll(currentCoveredSegments);

    // Compute the number of segments per server after rebalance than numSegmentsPerServer
    int numSegmentsPerServer = segmentsToCover.size() / serversInReplicaGroup.size();

    // Remove segments from servers that has more segments
    for (String server : serversInReplicaGroup) {
        LinkedList<String> segmentsInServer = serverToSegments.get(server);
        int segmentToMove = numSegmentsPerServer - segmentsInServer.size();
        if (segmentToMove < 0) {
            // Server has more segments than needed, remove segments from this server
            for (int i = 0; i < Math.abs(segmentToMove); i++) {
                segmentsToAdd.add(segmentsInServer.pop());
            }
        }
    }

    // Add segments to servers that has less segments than numSegmentsPerServer
    for (String server : serversInReplicaGroup) {
        LinkedList<String> segmentsInServer = serverToSegments.get(server);
        int segmentToMove = numSegmentsPerServer - segmentsInServer.size();
        if (segmentToMove > 0) {
            // Server has less segments than needed, add segments from this server
            for (int i = 0; i < segmentToMove; i++) {
                segmentsInServer.add(segmentsToAdd.pop());
            }
        }
    }

    // Handling the remainder of segments to add
    int count = 0;
    while (!segmentsToAdd.isEmpty()) {
        int serverIndex = count % serversInReplicaGroup.size();
        serverToSegments.get(serversInReplicaGroup.get(serverIndex)).add(segmentsToAdd.pop());
        count++;
    }
}

From source file:com.mtgi.analytics.XmlBehaviorEventPersisterTest.java

@Test
@SuppressWarnings("unchecked")
public void testCompress() throws Exception {
    persister.setBinary(true);/*from   w  w w  . j a va 2 s.  c  om*/
    persister.setCompress(true);
    persister.rotateLog();
    file = new File(persister.getFile());
    assertTrue("persister switched to binary", persister.isBinary());

    //we reuse the test event creation code from jdbc persister test to get ourselves an interesting dataset.
    ArrayList<BehaviorEvent> events = new ArrayList<BehaviorEvent>();
    int[] counter = { 0 };
    for (int i = 0; i < 3; ++i)
        JdbcBehaviorEventPersisterTest.createEvent(null, 1, 3, 3, counter, events);
    LinkedList<BehaviorEvent> queue = new LinkedList<BehaviorEvent>(events);

    persister.persist(queue);
    assertEquals("queue unmodified by persistence operation", 39, queue.size());
    assertEquals("persister reports correct file size", file.length(), persister.getFileSize());

    //unzip and convert binary to flat xml for comparison.  this also verifies that 'rotateLog'
    //leaves a well-formed XML document in its wake.
    String path = persister.rotateLog();
    File source = new File(path);
    assertTrue("log archive data exists", source.isFile());
    assertFalse("archive does not point to active log",
            source.getCanonicalPath().equals(file.getCanonicalPath()));

    File dest = File.createTempFile("perf", ".xml");
    dest.deleteOnExit();

    InputStream fis = new GZIPInputStream(new FileInputStream(source));
    FileOutputStream fos = new FileOutputStream(dest);
    FI_SAX_XML converter = new FI_SAX_XML();
    converter.parse(fis, fos);
    fis.close();
    fos.close();

    //now perform verification of log data against the expected results.
    List<String> actualLines = (List<String>) FileUtils.readLines(dest);
    assertEquals("every event was written, including log close", 40, actualLines.size());

    final String expectedOpen = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><event-log>";
    assertEquals("well-formed open", expectedOpen, actualLines.get(0).substring(0, expectedOpen.length()));
    assertEquals("well-formed close", "</event-log>", actualLines.get(actualLines.size() - 1));

    //read up the expected results for comparison.
    InputStream expectedData = XmlBehaviorEventPersisterTest.class
            .getResourceAsStream("XmlBehaviorEventPersisterTest.testBinaryXml-result.xml");
    assertNotNull("expected results resource found in test environment", expectedData);
    List<String> expectedLines = (List<String>) readLines(expectedData);
    expectedData.close();

    //compare the logged data line by line.
    assertEquals("expected log count matches actual", expectedLines.size(), actualLines.size());
    for (int i = 0; i < expectedLines.size() - 1; ++i) {

        String actual = actualLines.get(i);
        //we have to strip data that varies from test run to test run out before comparing.
        String expectedStripped = stripVariableData(expectedLines.get(i));
        String actualStripped = stripVariableData(actual);
        assertEquals("log line[" + i + "] matches expected", expectedStripped, actualStripped);

        //now check data against source event so that time-sensitive info is checked.
        BehaviorEvent evt = events.get(i);
        assertNotNull("event was given an id", evt.getId());
        assertTrue("log contains id", actual.contains("id=\"" + evt.getId() + "\""));

        BehaviorEvent parent = evt.getParent();
        if (parent == null)
            assertFalse("log does not contain parent id", actual.contains("parent-id"));
        else
            assertTrue("log contains parent reference",
                    actual.contains("parent-id=\"" + parent.getId() + "\""));

        assertTrue("log records time correctly", DATE_PATTERN.matcher(actual).find());
        assertTrue("log records duration correctly",
                actual.contains("<duration-ns>" + evt.getDurationNs() + "</duration-ns>"));
    }
}

From source file:com.mtgi.analytics.XmlBehaviorEventPersisterTest.java

@Test
public void testNestedEvents() throws InterruptedException, IOException, XMLStreamException, SAXException {
    //we reuse the test event creation code from jdbc persister test to get ourselves an interesting dataset.
    final ArrayList<BehaviorEvent> events = new ArrayList<BehaviorEvent>();
    int[] counter = { 0 };
    for (int i = 0; i < 3; ++i)
        JdbcBehaviorEventPersisterTest.createEvent(null, 1, 3, 3, counter, events);
    LinkedList<BehaviorEvent> queue = new LinkedList<BehaviorEvent>(events);

    persister.persist(queue);//from   www.  jav a2 s  . c o m
    assertEquals("queue unmodified by persistence operation", 39, queue.size());
    assertEquals("persister reports correct file size", file.length(), persister.getFileSize());

    //now perform verification of log data against the expected results.
    String fileName = persister.rotateLog();
    Document actualXML = buildTestDocument(FileUtils.readFileToString(new File(fileName)));

    //read up the expected results for comparison.
    InputStream expectedData = XmlBehaviorEventPersisterTest.class
            .getResourceAsStream("XmlBehaviorEventPersisterTest.testNestedEvents-result.xml");
    Document controlXML = buildTestDocument(new InputSource(expectedData));
    expectedData.close();

    XMLUnit.setIgnoreWhitespace(true);

    //compare the logged data to our expectations, ignoring time-sensitive values.
    Diff diff = new Diff(controlXML, actualXML);
    diff.overrideDifferenceListener(new DifferenceListener() {

        //filter out artificial differences in id, start time, duration
        public int differenceFound(Difference diff) {

            Node cn = diff.getControlNodeDetail().getNode();
            Node tn = diff.getTestNodeDetail().getNode();

            if (cn != null && tn != null) {
                short ctype = cn.getNodeType();
                short ttype = tn.getNodeType();
                if (ctype == ttype) {
                    if (ctype == Node.ATTRIBUTE_NODE) {
                        if (cn.getNodeName().equals("id") || cn.getNodeName().equals("parent-id")) {
                            //we can at least verify that the logged ID matches the ID assigned to our data model.
                            int index = -1;
                            for (Node n = ((Attr) cn).getOwnerElement(); n != null; n = n.getPreviousSibling())
                                if (n.getNodeType() == Node.ELEMENT_NODE)
                                    ++index;
                            BehaviorEvent event = events.get(index);
                            if (cn.getNodeName().equals("id")) {
                                assertEquals("logged event has same id as data model", event.getId().toString(),
                                        tn.getNodeValue());
                            } else {
                                BehaviorEvent parent = event.getParent();
                                assertNotNull("node " + event.getId() + " has parent", parent);
                                assertEquals("logged event has same parent-id as data model",
                                        parent.getId().toString(), tn.getNodeValue());
                            }
                            return RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR;
                        }
                    } else if (ctype == Node.TEXT_NODE) {
                        String cname = cn.getParentNode().getNodeName();
                        String tname = tn.getParentNode().getNodeName();
                        if (cname.equals(tname)) {
                            //TODO: sanity check values.
                            if ("duration-ns".equals(cname) || "start".equals(cname))
                                return RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR;
                        }
                    }
                }
            }

            return RETURN_ACCEPT_DIFFERENCE;
        }

        public void skippedComparison(Node n0, Node n1) {
        }

    });

    if (!diff.similar())
        fail(diff.appendMessage(new StringBuffer()).toString());
}

From source file:com.mtgi.analytics.XmlBehaviorEventPersisterTest.java

@Test
@SuppressWarnings("unchecked")
public void testBinaryXml() throws Exception {

    //switch to binary format.
    persister.setBinary(true);//from w  w  w  . j ava  2 s  . co  m
    persister.rotateLog();
    file = new File(persister.getFile());
    assertTrue("persister switched to binary", persister.isBinary());

    //we reuse the test event creation code from jdbc persister test to get ourselves an interesting dataset.
    ArrayList<BehaviorEvent> events = new ArrayList<BehaviorEvent>();
    int[] counter = { 0 };
    for (int i = 0; i < 3; ++i)
        JdbcBehaviorEventPersisterTest.createEvent(null, 1, 3, 3, counter, events);
    LinkedList<BehaviorEvent> queue = new LinkedList<BehaviorEvent>(events);

    persister.persist(queue);
    assertEquals("queue unmodified by persistence operation", 39, queue.size());
    assertEquals("persister reports correct file size", file.length(), persister.getFileSize());

    //convert binary to flat xml for comparison.  this also verifies that 'rotateLog'
    //leaves a well-formed XML document in its wake.
    String path = persister.rotateLog();
    File source = new File(path);
    assertTrue("log archive data exists", source.isFile());
    assertFalse("archive does not point to active log",
            source.getCanonicalPath().equals(file.getCanonicalPath()));

    File dest = File.createTempFile("perf", ".xml");
    dest.deleteOnExit();

    FileInputStream fis = new FileInputStream(source);
    FileOutputStream fos = new FileOutputStream(dest);
    FI_SAX_XML converter = new FI_SAX_XML();
    converter.parse(fis, fos);
    fis.close();
    fos.close();

    //now perform verification of log data against the expected results.
    List<String> actualLines = (List<String>) FileUtils.readLines(dest);
    assertEquals("every event was written, including log close", 40, actualLines.size());

    final String expectedOpen = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><event-log>";
    assertEquals("well-formed open", expectedOpen, actualLines.get(0).substring(0, expectedOpen.length()));
    assertEquals("well-formed close", "</event-log>", actualLines.get(actualLines.size() - 1));

    //read up the expected results for comparison.
    InputStream expectedData = XmlBehaviorEventPersisterTest.class
            .getResourceAsStream("XmlBehaviorEventPersisterTest.testBinaryXml-result.xml");
    assertNotNull("expected results resource found in test environment", expectedData);
    List<String> expectedLines = (List<String>) readLines(expectedData);
    expectedData.close();

    //compare the logged data line by line.
    assertEquals("expected log count matches actual", expectedLines.size(), actualLines.size());
    for (int i = 0; i < expectedLines.size(); ++i) {

        String actual = actualLines.get(i);
        //we have to strip data that varies from test run to test run out before comparing.
        String expectedStripped = stripVariableData(expectedLines.get(i));
        String actualStripped = stripVariableData(actual);
        assertEquals("log line[" + i + "] matches expected", expectedStripped, actualStripped);

        //last line is log close and doesn't correspond to an event.
        if (i < expectedLines.size() - 1) {
            //now check data against source event so that time-sensitive info is checked.
            BehaviorEvent evt = events.get(i);
            assertNotNull("event was given an id", evt.getId());
            assertTrue("log contains id", actual.contains("id=\"" + evt.getId() + "\""));

            BehaviorEvent parent = evt.getParent();
            if (parent == null)
                assertFalse("log does not contain parent id", actual.contains("parent-id"));
            else
                assertTrue("log contains parent reference",
                        actual.contains("parent-id=\"" + parent.getId() + "\""));

            assertTrue("log records time correctly", DATE_PATTERN.matcher(actual).find());
            assertTrue("log records duration correctly",
                    actual.contains("<duration-ns>" + evt.getDurationNs() + "</duration-ns>"));
        }
    }
}

From source file:eu.uqasar.model.tree.TreeNode.java

@Override
public boolean canChangePositionWithNextSibling(boolean changeParents) {
    LinkedList<TreeNode> directSiblings = (LinkedList<TreeNode>) getMutableSiblings();
    int currentIndex = directSiblings.indexOf(this);
    int newIndex = currentIndex + 1;
    if (newIndex < directSiblings.size()) {
        // switch currently selected node with the next one
        return true;
    } else if (newIndex >= directSiblings.size() && changeParents) {
        // add currently selected node as first entry to the next parent
        // sibling
        LinkedList<TreeNode> parentSiblings = (LinkedList<TreeNode>) this.getParent().getMutableSiblings();
        int parentIndex = parentSiblings.indexOf(this.getParent());
        int newParentIndex = parentIndex + 1;
        if (newParentIndex < parentSiblings.size()) {
            return true;
        }//from www.j ava  2 s  .c  o m
    }
    return false;
}