Example usage for com.google.common.collect Lists newArrayListWithExpectedSize

List of usage examples for com.google.common.collect Lists newArrayListWithExpectedSize

Introduction

In this page you can find the example usage for com.google.common.collect Lists newArrayListWithExpectedSize.

Prototype

@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayListWithExpectedSize(int estimatedSize) 

Source Link

Document

Creates an ArrayList instance to hold estimatedSize elements, plus an unspecified amount of padding; you almost certainly mean to call #newArrayListWithCapacity (see that method for further advice on usage).

Usage

From source file:eu.interedition.text.util.AbstractAnnotationRepository.java

@Override
public void transform(Criterion criterion, final Text to, final Function<Annotation, Annotation> transform) {
    final List<Annotation> batch = Lists.newArrayListWithExpectedSize(batchSize);
    scroll(criterion, null, new AnnotationConsumer() {
        @Override//from  ww w. j  a  v a2s  .  co  m
        public void consume(Annotation annotation) {
            batch.add(annotation);
            if ((batch.size() % batchSize) == 0) {
                transform(batch, to, transform);
                batch.clear();
            }
        }
    });
    if (!batch.isEmpty()) {
        transform(batch, to, transform);
    }
}

From source file:ru.runa.wfe.graph.image.figure.TransitionFigureBase.java

public void draw(Graphics2D graphics, Color color) {
    Rectangle rectFrom = figureFrom.getRectangle();
    Rectangle rectTo = figureTo.getRectangle();
    ExtraGraphics extragraphics = new ExtraGraphics(graphics);
    double secondX;
    double secondY;
    if (bendpoints.size() > 0) {
        Point bendPoint = bendpoints.get(0);
        secondX = bendPoint.x;//from  w  w w . j a  v  a2 s  . c om
        secondY = bendPoint.y;
    } else {
        double[] secondCoors = getReferencePoint(rectFrom, rectTo);
        secondX = secondCoors[0];
        secondY = secondCoors[1];
    }
    List<Point> points = Lists.newArrayListWithExpectedSize(bendpoints.size() + 2);
    Point start = figureFrom.getTransitionPoint(transition, secondX, secondY);
    points.add(start);
    Point bendPoint = null;
    for (int i = 0; i < bendpoints.size(); i++) {
        bendPoint = bendpoints.get(i);
        if (!Objects.equal(bendPoint, points.get(points.size() - 1))) {
            points.add(bendPoint);
        }
    }
    if (bendPoint == null) {
        if (figureFrom.getType() == NodeType.FORK || figureFrom.getType() == NodeType.JOIN
                || transition.isTimerTransition()) {
            bendPoint = start;
        } else {
            bendPoint = new Point((int) rectFrom.getCenterX(), (int) rectFrom.getCenterY());// start;
        }
    }
    Point end = figureTo.getTransitionPoint(null, bendPoint.x, bendPoint.y);
    if (!Objects.equal(end, points.get(points.size() - 1)) || points.size() == 1) {
        points.add(end);
    }

    int[] xPoints = new int[points.size()];
    int[] yPoints = new int[points.size()];
    for (int i = 0; i < points.size(); i++) {
        xPoints[i] = points.get(i).x;
        yPoints[i] = points.get(i).y;
    }
    if (figureFrom.useEgdingOnly) {
        // Cleaning old transitions
        graphics.setStroke(new BasicStroke(DrawProperties.TRANSITION_CLEAN_WIDTH));
        graphics.setColor(DrawProperties.getBackgroundColor());
        graphics.drawPolyline(xPoints, yPoints, xPoints.length);
    }

    graphics.setStroke(new BasicStroke(DrawProperties.TRANSITION_DRAW_WIDTH));
    graphics.setColor(color);

    if (smoothLines) {
        extragraphics.drawSmoothPolyline(xPoints, yPoints, xPoints.length);
    } else {
        graphics.drawPolyline(xPoints, yPoints, xPoints.length);
    }

    if (actionsCount > 0) {
        Point p = new Point(xPoints[1], yPoints[1]);
        boolean fromTimer = transition.isTimerTransition();
        if (ActionUtils.areActionsFitInLine(actionsCount, start, p, fromTimer, exclusive)) {
            for (int i = 0; i < actionsCount; i++) {
                Point loc = ActionUtils.getActionLocationOnTransition(i, start, p, fromTimer, exclusive);
                graphics.setColor(DrawProperties.getBackgroundColor());
                graphics.fillOval(loc.x, loc.y, ActionUtils.ACTION_SIZE + 3, ActionUtils.ACTION_SIZE + 3);
                if (failedActions.contains(i)) {
                    graphics.setColor(Color.RED);
                    graphics.drawString("x", loc.x + 3, loc.y + 3);
                }
                graphics.setColor(color);
                graphics.drawOval(loc.x, loc.y, ActionUtils.ACTION_SIZE, ActionUtils.ACTION_SIZE);
            }
        }
    }

    if (exclusive) {
        Point from = new Point(start);
        double angle = GraphicsMath.getAngle(xPoints[0], yPoints[0], xPoints[1], yPoints[1]);
        if (transition.isTimerTransition()) {
            from.x += DrawProperties.GRID_SIZE * Math.cos(angle);
            from.y += DrawProperties.GRID_SIZE * Math.sin(angle);
        }
        double delta = 2 * DrawProperties.TRANSITION_SM_ANGLE;
        double hypotenuse = 8;
        int xLeft = (int) Math.round(from.x + hypotenuse * Math.cos(angle - delta));
        int xRight = (int) Math.round(from.x + hypotenuse * Math.cos(angle + delta));
        int xEnd = (int) Math.round(from.x + 2 * hypotenuse * Math.cos(angle));
        int yLeft = (int) Math.round(from.y - hypotenuse * Math.sin(angle - delta));
        int yRight = (int) Math.round(from.y - hypotenuse * Math.sin(angle + delta));
        int yEnd = (int) Math.round(from.y - 2 * hypotenuse * Math.sin(angle));
        int[] xSmPoints = new int[] { from.x, xLeft, xEnd, xRight };
        int[] ySmPoints = new int[] { from.y, yLeft, yEnd, yRight };
        if (renderHits.isPassed()) {
            graphics.fillPolygon(xSmPoints, ySmPoints, xSmPoints.length);
        } else {
            graphics.setColor(DrawProperties.getBackgroundColor());
            graphics.fillPolygon(xSmPoints, ySmPoints, xSmPoints.length);
            graphics.setColor(color);
            graphics.drawPolygon(xSmPoints, ySmPoints, xSmPoints.length);
        }
    }

    double angle = GraphicsMath.getAngle(xPoints[xPoints.length - 1], yPoints[yPoints.length - 1],
            xPoints[xPoints.length - 2], yPoints[yPoints.length - 2]);
    double delta = DrawProperties.TRANSITION_SM_ANGLE;
    double hypotenuse = DrawProperties.TRANSITION_SM_L / Math.cos(delta);
    int xLeft = (int) Math.round(end.x + hypotenuse * Math.cos(angle - delta));
    int xRight = (int) Math.round(end.x + hypotenuse * Math.cos(angle + delta));
    int yLeft = (int) Math.round(end.y - hypotenuse * Math.sin(angle - delta));
    int yRight = (int) Math.round(end.y - hypotenuse * Math.sin(angle + delta));
    int[] xSmPoints = new int[] { end.x, xLeft, xRight };
    int[] ySmPoints = new int[] { end.y, yLeft, yRight };
    graphics.fillPolygon(xSmPoints, ySmPoints, xSmPoints.length);

    if (!figureFrom.useEgdingOnly && !transition.getName().startsWith("tr")) {
        String drawString = transition.isTimerTransition() ? timerInfo : transition.getName();
        Rectangle2D textBounds = graphics.getFontMetrics().getStringBounds(drawString, graphics);
        int padding = 1;
        int xStart = 0;
        int yStart = 0;
        if (figureFrom.getType() == NodeType.FORK) {
            xStart = (int) (xPoints[xPoints.length - 2] + xPoints[xPoints.length - 1] - textBounds.getWidth())
                    / 2;
            yStart = (int) (yPoints[yPoints.length - 2] + yPoints[yPoints.length - 1] - textBounds.getHeight())
                    / 2;
        } else {
            xStart = (int) (xPoints[0] + xPoints[1] - textBounds.getWidth()) / 2;
            yStart = (int) (yPoints[0] + yPoints[1] - textBounds.getHeight()) / 2;
        }

        Color orig = graphics.getColor();
        graphics.setColor(DrawProperties.getBackgroundColor());
        graphics.fillRect(xStart - 2 * padding, yStart - padding,
                (int) (textBounds.getWidth() + 1 + 2 * padding),
                (int) (textBounds.getHeight() + 1 + 2 * padding));
        graphics.setColor(orig);
        if (xStart < 1) {
            xStart = 1;
        }
        graphics.setColor(DrawProperties.getTextColor());
        graphics.drawString(drawString, xStart, (int) (yStart + textBounds.getHeight() - padding));
    }
}

From source file:com.kylinolap.rest.service.JobService.java

@PreAuthorize(Constant.ACCESS_HAS_ROLE_ADMIN
        + " or hasPermission(#cube, 'ADMINISTRATION') or hasPermission(#cube, 'OPERATION') or hasPermission(#cube, 'MANAGEMENT')")
public String submitJob(CubeInstance cube, long startDate, long endDate, CubeBuildTypeEnum buildType,
        String submitter) throws IOException, JobException, InvalidJobInstanceException {

    List<JobInstance> jobInstances = this.getJobManager().listJobs(cube.getName(), null);
    for (JobInstance jobInstance : jobInstances) {
        if (jobInstance.getStatus() == JobStatusEnum.PENDING
                || jobInstance.getStatus() == JobStatusEnum.RUNNING) {
            throw new JobException("The cube " + cube.getName() + " has running job(" + jobInstance.getUuid()
                    + ") please discard it and try again.");
        }//  w  ww  .j a  v a 2 s  .c om
    }

    String uuid = null;
    try {
        List<CubeSegment> cubeSegments = this.getCubeManager().allocateSegments(cube, buildType, startDate,
                endDate);
        List<JobInstance> jobs = Lists.newArrayListWithExpectedSize(cubeSegments.size());
        for (CubeSegment segment : cubeSegments) {
            uuid = segment.getUuid();
            JobInstance job = this.getJobManager().createJob(cube.getName(), segment.getName(),
                    segment.getUuid(), buildType, submitter);
            segment.setLastBuildJobID(uuid);
            jobs.add(job);
        }
        getCubeManager().updateCube(cube);
        for (JobInstance job : jobs) {
            this.getJobManager().submitJob(job);
            permissionService.init(job, null);
            permissionService.inherit(job, cube);
        }
    } catch (CubeIntegrityException e) {
        throw new InternalErrorException(e.getLocalizedMessage(), e);
    }

    return uuid;
}

From source file:org.attribyte.relay.HTTPSupplier.java

@Override
public Optional<ByteString> shutdown() {
    if (isInit.compareAndSet(true, false)) {
        try {//from  www  .j av  a 2 s.  c o  m
            httpClient.shutdown();
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            logger.error("Problem shutting down HTTP client", e);
        }

        List<ByteString> unreportedState = Lists.newArrayListWithExpectedSize(8);
        int numStates = stateHistory.drainTo(unreportedState);
        return numStates == 0 ? Optional.absent() : Optional.of(unreportedState.get(numStates - 1));
    } else {
        return Optional.absent();
    }
}

From source file:com.google.devtools.build.lib.syntax.Lexer.java

/**
 * Constructs a lexer which tokenizes the contents of the specified InputBuffer. Any errors during
 * lexing are reported on "handler".//from w  ww  . j  a v  a 2  s  .c  o m
 */
public Lexer(ParserInputSource input, EventHandler eventHandler, LineNumberTable lineNumberTable) {
    this.buffer = input.getContent();
    // Empirical measurements show roughly 1 token per 8 characters in buffer.
    this.tokens = Lists.newArrayListWithExpectedSize(buffer.length / 8);
    this.pos = 0;
    this.eventHandler = eventHandler;
    this.locationInfo = new LocationInfo(input.getPath(), lineNumberTable);

    indentStack.push(0);
    long startTime = Profiler.nanoTimeMaybe();
    tokenize();
    Profiler.instance().logSimpleTask(startTime, ProfilerTask.SKYLARK_LEXER, getFilename());
}

From source file:voldemort.store.serialized.SerializingStore.java

@Override
public Map<K, List<Versioned<V>>> getAll(Iterable<K> keys, Map<K, T> transforms) throws VoldemortException {
    StoreUtils.assertValidKeys(keys);/*  w ww.  j a v  a2 s.c o  m*/
    Map<ByteArray, K> byteKeyToKey = keysToBytes(keys);
    Map<ByteArray, List<Versioned<byte[]>>> storeResult = store.getAll(byteKeyToKey.keySet(),
            transformsToBytes(transforms));
    Map<K, List<Versioned<V>>> result = Maps.newHashMapWithExpectedSize(storeResult.size());
    for (Map.Entry<ByteArray, List<Versioned<byte[]>>> mapEntry : storeResult.entrySet()) {
        List<Versioned<V>> values = Lists.newArrayListWithExpectedSize(mapEntry.getValue().size());
        for (Versioned<byte[]> versioned : mapEntry.getValue())
            values.add(
                    new Versioned<V>(valueSerializer.toObject(versioned.getValue()), versioned.getVersion()));

        result.put(byteKeyToKey.get(mapEntry.getKey()), values);
    }
    return result;
}

From source file:com.google.devtools.depan.platform.plugin.ContributionRegistry.java

protected Collection<ContributionEntry<T>> getContributions(Collection<String> contribIds) {
    Collection<ContributionEntry<T>> result = Lists.newArrayListWithExpectedSize(contribIds.size());
    for (String contribId : contribIds) {
        result.add(getContribution(contribId));
    }//  w  ww  .  j av  a 2 s.  c o m
    return result;
}

From source file:edu.byu.nlp.util.Iterators2.java

public static <E> Iterator<E> subInterval(final Iterator<E> it, final int start, final int length) {
    // note: improve this (if necessary) by making it lazy
    List<E> items = Lists.newArrayListWithExpectedSize(length);
    Iterator<Enumeration<E>> enit = enumerate(it);
    while (enit.hasNext() && items.size() < length) {
        Enumeration<E> item = enit.next();
        if (item.getIndex() >= start) {
            items.add(item.getElement());
        }//from   ww  w  .  ja  v a 2 s  . c o  m
    }
    return items.iterator();
}

From source file:com.google.gerrit.server.api.changes.ChangeInfoMapper.java

private void mapLabels(ChangeJson.ChangeInfo i, ChangeInfo o) {
    if (i.labels == null) {
        return;/*from w w w .j a  va2s.  co m*/
    }
    Map<String, LabelInfo> r = Maps.newLinkedHashMap();
    for (Map.Entry<String, ChangeJson.LabelInfo> e : i.labels.entrySet()) {
        ChangeJson.LabelInfo li = e.getValue();
        LabelInfo lo = new LabelInfo();
        lo.approved = AccountInfoMapper.fromAcountInfo(li.approved);
        lo.rejected = AccountInfoMapper.fromAcountInfo(li.rejected);
        lo.recommended = AccountInfoMapper.fromAcountInfo(li.recommended);
        lo.disliked = AccountInfoMapper.fromAcountInfo(li.disliked);
        lo.value = li.value;
        lo.defaultValue = li.defaultValue;
        lo.optional = li.optional;
        lo.blocking = li.blocking;
        lo.values = li.values;
        if (li.all != null) {
            lo.all = Lists.newArrayListWithExpectedSize(li.all.size());
            for (ChangeJson.ApprovalInfo ai : li.all) {
                lo.all.add(fromApprovalInfo(ai));
            }
        }
        r.put(e.getKey(), lo);
    }
    o.labels = r;
}

From source file:defrac.intellij.projectView.DefracViewProjectNode.java

@NotNull
private Collection<AbstractTreeNode> normalModules(@NotNull final Collection<Module> modules) {
    final ArrayList<AbstractTreeNode> result = Lists.newArrayListWithExpectedSize(modules.size());

    for (final Module module : modules) {
        result.add(createModuleGroup(module));
    }//w  w  w  .  j  a  v  a2s.  co  m

    return result;
}