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:blusunrize.immersiveengineering.client.models.ModelConfigurableSides.java

private static List<BakedQuad> bakeQuads(TextureAtlasSprite[] sprites) {
    List<BakedQuad> quads = Lists.newArrayListWithExpectedSize(6);
    float[] colour = { 1, 1, 1, 1 };
    Vector3f[] vertices = { new Vector3f(0, 0, 0), new Vector3f(0, 0, 1), new Vector3f(1, 0, 1),
            new Vector3f(1, 0, 0) };
    quads.add(ClientUtils.createBakedQuad(DefaultVertexFormats.ITEM, vertices, EnumFacing.DOWN, sprites[0],
            new double[] { 0, 16, 16, 0 }, colour, true));
    vertices = new Vector3f[] { new Vector3f(0, 1, 0), new Vector3f(0, 1, 1), new Vector3f(1, 1, 1),
            new Vector3f(1, 1, 0) };
    quads.add(ClientUtils.createBakedQuad(DefaultVertexFormats.ITEM, vertices, EnumFacing.UP, sprites[1],
            new double[] { 0, 0, 16, 16 }, colour, false));

    vertices = new Vector3f[] { new Vector3f(1, 0, 0), new Vector3f(1, 1, 0), new Vector3f(0, 1, 0),
            new Vector3f(0, 0, 0) };
    quads.add(ClientUtils.createBakedQuad(DefaultVertexFormats.ITEM, vertices, EnumFacing.NORTH, sprites[2],
            new double[] { 0, 16, 16, 0 }, colour, true));
    vertices = new Vector3f[] { new Vector3f(1, 0, 1), new Vector3f(1, 1, 1), new Vector3f(0, 1, 1),
            new Vector3f(0, 0, 1) };
    quads.add(ClientUtils.createBakedQuad(DefaultVertexFormats.ITEM, vertices, EnumFacing.SOUTH, sprites[3],
            new double[] { 16, 16, 0, 0 }, colour, false));

    vertices = new Vector3f[] { new Vector3f(0, 0, 0), new Vector3f(0, 1, 0), new Vector3f(0, 1, 1),
            new Vector3f(0, 0, 1) };
    quads.add(ClientUtils.createBakedQuad(DefaultVertexFormats.ITEM, vertices, EnumFacing.WEST, sprites[4],
            new double[] { 0, 16, 16, 0 }, colour, true));
    vertices = new Vector3f[] { new Vector3f(1, 0, 0), new Vector3f(1, 1, 0), new Vector3f(1, 1, 1),
            new Vector3f(1, 0, 1) };
    quads.add(ClientUtils.createBakedQuad(DefaultVertexFormats.ITEM, vertices, EnumFacing.EAST, sprites[5],
            new double[] { 16, 16, 0, 0 }, colour, false));
    return quads;
}

From source file:org.apache.bookkeeper.stream.protocol.util.ProtoUtils.java

public static List<RangeProperties> split(long streamId, int numInitialRanges, long nextRangeId,
        StorageContainerPlacementPolicy placementPolicy) {
    int numRanges = Math.max(2, numInitialRanges);
    if (numRanges % 2 != 0) { // round up to odd number
        numRanges = numRanges + 1;//from w  w  w. j a va2  s.  c  o m
    }
    long rangeSize = Long.MAX_VALUE / (numRanges / 2);
    long startKey = Long.MIN_VALUE;
    List<RangeProperties> ranges = Lists.newArrayListWithExpectedSize(numRanges);
    for (int idx = 0; idx < numRanges; ++idx) {
        long endKey = startKey + rangeSize;
        if (numRanges - 1 == idx) {
            endKey = Long.MAX_VALUE;
        }
        long rangeId = nextRangeId++;
        RangeProperties props = RangeProperties.newBuilder().setStartHashKey(startKey).setEndHashKey(endKey)
                .setStorageContainerId(placementPolicy.placeStreamRange(streamId, rangeId)).setRangeId(rangeId)
                .build();
        startKey = endKey;

        ranges.add(props);
    }
    return ranges;
}

From source file:com.eucalyptus.objectstorage.metadata.BucketNameValidatorRepo.java

private static Validator<String> setupExtended() {
    IteratingValidator<String> extended = new IteratingValidator<String>();
    List<Validator<String>> checks = Lists.newArrayListWithExpectedSize(3);
    checks.add(new Validator<String>() {
        // not null // sanity
        @Override//from  www.j  a  v a  2  s .  c  o  m
        public boolean check(String bucketName) {
            return bucketName != null && bucketName.length() > 1;
        }
    });
    checks.add(new Validator<String>() {
        // not more than 255 characters
        @Override
        public boolean check(String bucketName) {
            return bucketName.length() <= 255;
        }
    });
    checks.add(new Validator<String>() {
        // any combination of uppercase letters, lowercase letters,
        // numbers, periods (.), dashes (-) and underscores (_)
        @Override
        public boolean check(String bucketName) {
            for (char ch : bucketName.toCharArray()) {
                boolean isBad = (!isLowerOrNumber(ch) && !(ch >= 'A' && ch <= 'Z') && ch != '.' && ch != '-'
                        && ch != '_');
                if (isBad) {
                    return false;
                }
            }
            return true;
        }
    });
    extended.setValidators(checks);
    return extended;
}

From source file:org.apache.phoenix.hive.mapreduce.PhoenixRecordReader.java

public void initialize(InputSplit split) throws IOException {
    final PhoenixInputSplit pSplit = (PhoenixInputSplit) split;
    final List<Scan> scans = pSplit.getScans();

    if (LOG.isInfoEnabled()) {
        LOG.info("Target table : " + queryPlan.getTableRef().getTable().getPhysicalName());
    }//w  w  w  .ja  v a2s  .c o m

    if (LOG.isDebugEnabled()) {
        LOG.debug("Scan count[" + scans.size() + "] : " + Bytes.toStringBinary(scans.get(0).getStartRow())
                + " ~ " + Bytes.toStringBinary(scans.get(scans.size() - 1).getStopRow()));
        LOG.debug("First scan : " + scans.get(0) + " scanAttribute : " + scans.get(0).getAttributesMap());

        for (int i = 0, limit = scans.size(); i < limit; i++) {
            LOG.debug("EXPECTED_UPPER_REGION_KEY[" + i + "] : " + Bytes.toStringBinary(
                    scans.get(i).getAttribute(BaseScannerRegionObserver.EXPECTED_UPPER_REGION_KEY)));
        }
    }

    try {
        List<PeekingResultIterator> iterators = Lists.newArrayListWithExpectedSize(scans.size());
        StatementContext ctx = queryPlan.getContext();
        ReadMetricQueue readMetrics = ctx.getReadMetricsQueue();
        String tableName = queryPlan.getTableRef().getTable().getPhysicalName().getString();
        long renewScannerLeaseThreshold = queryPlan.getContext().getConnection().getQueryServices()
                .getRenewLeaseThresholdMilliSeconds();
        for (Scan scan : scans) {
            scan.setAttribute(BaseScannerRegionObserver.SKIP_REGION_BOUNDARY_CHECK, Bytes.toBytes(true));
            final TableResultIterator tableResultIterator = new TableResultIterator(
                    queryPlan.getContext().getConnection().getMutationState(), scan,
                    readMetrics.allotMetric(SCAN_BYTES, tableName), renewScannerLeaseThreshold, queryPlan,
                    MapReduceParallelScanGrouper.getInstance());

            PeekingResultIterator peekingResultIterator = LookAheadResultIterator.wrap(tableResultIterator);
            iterators.add(peekingResultIterator);
        }
        ResultIterator iterator = queryPlan.useRoundRobinIterator()
                ? RoundRobinResultIterator.newIterator(iterators, queryPlan)
                : ConcatResultIterator.newIterator(iterators);
        if (queryPlan.getContext().getSequenceManager().getSequenceCount() > 0) {
            iterator = new SequenceResultIterator(iterator, queryPlan.getContext().getSequenceManager());
        }
        this.resultIterator = iterator;
        // Clone the row projector as it's not thread safe and would be used
        // simultaneously by multiple threads otherwise.
        this.resultSet = new PhoenixResultSet(this.resultIterator, queryPlan.getProjector().cloneIfNecessary(),
                queryPlan.getContext());
    } catch (SQLException e) {
        LOG.error(String.format(" Error [%s] initializing PhoenixRecordReader. ", e.getMessage()));
        Throwables.propagate(e);
    }
}

From source file:org.apache.druid.java.util.common.parsers.JSONToLowerParser.java

@Override
public Map<String, Object> parseToMap(String input) {
    try {//from  www .j  a v  a  2 s.  c  om
        Map<String, Object> map = new LinkedHashMap<>();
        JsonNode root = objectMapper.readTree(input);

        Iterator<String> keysIter = (fieldNames == null ? root.fieldNames() : fieldNames.iterator());

        while (keysIter.hasNext()) {
            String key = keysIter.next();

            if (exclude.contains(StringUtils.toLowerCase(key))) {
                continue;
            }

            JsonNode node = root.path(key);

            if (node.isArray()) {
                final List<Object> nodeValue = Lists.newArrayListWithExpectedSize(node.size());
                for (final JsonNode subnode : node) {
                    final Object subnodeValue = valueFunction.apply(subnode);
                    if (subnodeValue != null) {
                        nodeValue.add(subnodeValue);
                    }
                }
                map.put(StringUtils.toLowerCase(key), nodeValue); // difference from JSONParser parse()
            } else {
                final Object nodeValue = valueFunction.apply(node);
                if (nodeValue != null) {
                    map.put(StringUtils.toLowerCase(key), nodeValue); // difference from JSONParser parse()
                }
            }
        }
        return map;
    } catch (Exception e) {
        throw new ParseException(e, "Unable to parse row [%s]", input);
    }
}

From source file:com.android.tools.idea.wizard.model.ModelWizard.java

/**
 * Construct a wizard with all of the steps it can potentially show (although some may be
 * hidden). If a step provides its own dependent steps, those, too, will be automatically added
 * at this time./*from   w w  w .java 2  s. c o  m*/
 * <p/>
 * A wizard, once constructed, is ready to go and will already be pointing at the first step. The
 * next expected action is for {@link #goForward()} to be called. Most likely, a wrapping UI
 * container, such as {@link ModelWizardDialog}, will be responsible for handling this.
 * <p/>
 * When the wizard is finished, it will iterate through its steps, in order, and run
 * {@link WizardModel#handleFinished()} on each of their associated models.
 * <p/>
 * Note: You don't use this constructor directly - instead, use {@link Builder#build()}.
 *
 * @throws IllegalArgumentException if {@code steps} is empty or none of the steps are visible.
 */
private ModelWizard(@NotNull Collection<ModelWizardStep> steps) {
    mySteps = Lists.newArrayListWithExpectedSize(steps.size());
    for (ModelWizardStep step : steps) {
        addStep(step);
    }

    if (mySteps.isEmpty()) {
        throw new IllegalStateException("Can't create a wizard with no steps");
    }

    myCanGoForward.addListener(sender -> {
        if (myCanGoForward.get()) {
            // Make double sure that, when we switch from blocked to can proceed, we check that no
            // future steps also became visible or hidden at some point. Otherwise, we might think
            // we're on the last step when we're not (or vice versa).
            myOnLastStep.set(isOnLastVisibleStep());
        }
    });

    Set<WizardModel> seenModels = Sets.newHashSet();
    for (ModelWizardStep step : mySteps) {
        Disposer.register(this, step);

        WizardModel model = step.getModel();
        if (seenModels.contains(model)) {
            continue;
        }
        Disposer.register(this, model);
        seenModels.add(model);
    }

    // At this point, we're ready to go! Try to start the wizard, proceeding into the first step
    // if we can.

    Facade facade = new Facade();
    for (ModelWizardStep step : mySteps) {
        step.onWizardStarting(facade);
    }

    boolean atLeastOneVisibleStep = false;
    for (ModelWizardStep step : mySteps) {
        if (shouldShowStep(step)) {
            atLeastOneVisibleStep = true;
            break;
        }
    }

    if (atLeastOneVisibleStep) {
        goForward(); // Proceed to first step
    } else {
        // Normally we'd leave it up to external code to dispose the wizard, but since we're throwing
        // an exception in the constructor, it means the caller won't be able to get a reference to
        // this wizard before the exception interrupts it. So we manually clean things up ourselves.
        Disposer.dispose(this);
        throw new IllegalStateException("Trying to create a wizard but no steps are visible");
    }
}

From source file:org.n52.sos.decode.json.impl.InsertSensorRequestDecoder.java

protected List<SwesFeatureRelationship> parseFeatureRelationships(JsonNode node) throws OwsExceptionReport {
    if (node.isArray()) {
        List<SwesFeatureRelationship> list = Lists.newArrayListWithExpectedSize(node.size());
        for (JsonNode n : node) {
            if (n.isObject()) {
                list.add(parseFeatureRelationship(n));
            }/*w w  w  .  j a v a2  s .  c o m*/
        }
        return list;
    } else if (node.isObject()) {
        return Collections.singletonList(parseFeatureRelationship(node));
    } else {
        return null;
    }
}

From source file:org.sakaiproject.kernel.rest.presence.PresenceProvider.java

@GET
@Path("/friends")
@Produces(MediaType.TEXT_PLAIN)//  ww w.  jav  a2  s  . c  om
public String getFriendsStatus() {
    String userId = sessionManagerService.getCurrentUserId();
    if (!StringUtils.isEmpty(userId) && !"anon".equals(userId)) {
        FriendsBean fbs = friendsResolverService.resolve(userId);
        List<FriendBean> friendBeans = fbs.getFriends();
        List<String> connections = Lists.newArrayListWithExpectedSize(friendBeans.size());
        for (FriendBean fb : friendBeans) {
            connections.add(fb.getFriendUuid());
        }
        return beanConverter.convertToString(presenceService.online(connections));
    }
    return ERROR;

}

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

public Collection<String> getDependIds(String dependTag, String dependAttr) {
    IConfigurationElement[] depends = element.getChildren(dependTag);
    if (0 == depends.length) {
        return Collections.emptyList();
    }/*from  w  ww.  j ava  2 s. c o m*/
    List<String> result = Lists.newArrayListWithExpectedSize(depends.length);
    for (IConfigurationElement depend : depends) {
        result.add(depend.getAttribute(dependAttr));
    }
    return result;
}

From source file:org.apache.phoenix.spark.datasource.v2.reader.PhoenixInputPartitionReader.java

private void initialize() {
    try {//from w  ww  .j  a v  a  2  s  .  com
        final QueryPlan queryPlan = getQueryPlan();
        final List<Scan> scans = phoenixInputSplit.value().getScans();
        List<PeekingResultIterator> iterators = Lists.newArrayListWithExpectedSize(scans.size());
        StatementContext ctx = queryPlan.getContext();
        ReadMetricQueue readMetrics = ctx.getReadMetricsQueue();
        String tableName = queryPlan.getTableRef().getTable().getPhysicalName().getString();

        // Clear the table region boundary cache to make sure long running jobs stay up to date
        byte[] tableNameBytes = queryPlan.getTableRef().getTable().getPhysicalName().getBytes();
        ConnectionQueryServices services = queryPlan.getContext().getConnection().getQueryServices();
        services.clearTableRegionCache(TableName.valueOf(tableNameBytes));

        long renewScannerLeaseThreshold = queryPlan.getContext().getConnection().getQueryServices()
                .getRenewLeaseThresholdMilliSeconds();
        for (Scan scan : scans) {
            // For MR, skip the region boundary check exception if we encounter a split. ref: PHOENIX-2599
            scan.setAttribute(BaseScannerRegionObserver.SKIP_REGION_BOUNDARY_CHECK, Bytes.toBytes(true));

            PeekingResultIterator peekingResultIterator;
            ScanMetricsHolder scanMetricsHolder = ScanMetricsHolder.getInstance(readMetrics, tableName, scan,
                    queryPlan.getContext().getConnection().getLogLevel());
            final TableResultIterator tableResultIterator = new TableResultIterator(
                    queryPlan.getContext().getConnection().getMutationState(), scan, scanMetricsHolder,
                    renewScannerLeaseThreshold, queryPlan, MapReduceParallelScanGrouper.getInstance());
            peekingResultIterator = LookAheadResultIterator.wrap(tableResultIterator);
            iterators.add(peekingResultIterator);
        }
        ResultIterator iterator = queryPlan.useRoundRobinIterator()
                ? RoundRobinResultIterator.newIterator(iterators, queryPlan)
                : ConcatResultIterator.newIterator(iterators);
        if (queryPlan.getContext().getSequenceManager().getSequenceCount() > 0) {
            iterator = new SequenceResultIterator(iterator, queryPlan.getContext().getSequenceManager());
        }
        // Clone the row projector as it's not thread safe and would be used simultaneously by
        // multiple threads otherwise.
        this.resultSet = new PhoenixResultSet(iterator, queryPlan.getProjector().cloneIfNecessary(),
                queryPlan.getContext());
        this.iterator = SparkJdbcUtil.resultSetToSparkInternalRows(resultSet, schema, new InputMetrics());
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}