Example usage for com.google.common.collect ImmutableList size

List of usage examples for com.google.common.collect ImmutableList size

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableList size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this list.

Usage

From source file:quantum.wrapper.minecraft.block.StateHybrid.java

private static List<State> getAllStates(final net.minecraft.block.Block block) {
    @SuppressWarnings("unchecked")
    final ImmutableList<IBlockState> allStates = (ImmutableList<IBlockState>) block.getBlockState()
            .getValidStates();// ww w . ja v a  2  s .c  o  m
    final List<State> result = new ArrayList<>(allStates.size());

    int currentIndex = 0;
    for (IBlockState state : allStates) {
        //TODO get the model for an IBlockState
        Model model = null;
        Map<String, PropertyHybrid<?>> props = new HashMap<>(state.getProperties().size());

        //noinspection unchecked
        for (Map.Entry<IProperty, Comparable<?>> value : (Set<Map.Entry<IProperty, Comparable<?>>>) state
                .getProperties().entrySet()) {
            props.put(value.getKey().getName(),
                    value.getKey() instanceof PropertyHybrid ? (PropertyHybrid<?>) value.getKey()
                            : new PropertyHybrid<>(value.getKey(), value.getValue()));
        }

        Function<IProperty, Comparable<?>> getValue = (iproperty -> null);
        result.add(new StateAccessor(
                new StateHybrid(BlockAdapter.get(block), block, result, currentIndex, model, props, getValue)));
    }

    return result;
}

From source file:com.google.auto.value.processor.escapevelocity.Reparser.java

/**
 * Returns a copy of the given list where spaces have been moved where appropriate after {@code
 * #set}. This hack is needed to match what appears to be special treatment in Apache Velocity of
 * spaces before {@code #set} directives. If you have <i>thing</i> <i>whitespace</i> {@code #set},
 * then the whitespace is deleted if the <i>thing</i> is a comment ({@code ##...\n}); a reference
 * ({@code $x} or {@code $x.foo} etc); a macro definition; or another {@code #set}.
 *///from w  w w  . j  av  a2  s.  co m
private static ImmutableList<Node> removeSpaceBeforeSet(ImmutableList<Node> nodes) {
    assert Iterables.getLast(nodes) instanceof EofNode;
    // Since the last node is EofNode, the i + 1 and i + 2 accesses below are safe.
    ImmutableList.Builder<Node> newNodes = ImmutableList.builder();
    for (int i = 0; i < nodes.size(); i++) {
        Node nodeI = nodes.get(i);
        newNodes.add(nodeI);
        if (shouldDeleteSpaceBetweenThisAndSet(nodeI) && isWhitespaceLiteral(nodes.get(i + 1))
                && nodes.get(i + 2) instanceof SetNode) {
            // Skip the space.
            i++;
        }
    }
    return newNodes.build();
}

From source file:org.geogit.osm.internal.OSMUnmapOp.java

private static int getPropertyIndex(RevFeatureType type, String name) {

    ImmutableList<PropertyDescriptor> descriptors = type.sortedDescriptors();
    for (int i = 0; i < descriptors.size(); i++) {
        if (descriptors.get(i).getName().getLocalPart().equals(name)) {
            return i;
        }/*from w w w.  ja va  2 s. c om*/
    }
    // shouldn't reach this
    throw new RuntimeException("wrong field name");
}

From source file:org.glowroot.local.store.Schemas.java

private static void createTable(@Untainted String tableName, ImmutableList<Column> columns,
        Connection connection) throws SQLException {
    StringBuilder sql = new StringBuilder();
    sql.append("create table ");
    sql.append(tableName);/*w  ww .  j ava2s .co m*/
    sql.append(" (");
    for (int i = 0; i < columns.size(); i++) {
        if (i > 0) {
            sql.append(", ");
        }
        String sqlTypeName = sqlTypeNames.get(columns.get(i).type());
        checkNotNull(sqlTypeName, "Unexpected sql type: %s", columns.get(i).type());
        sql.append(columns.get(i).name());
        sql.append(" ");
        sql.append(sqlTypeName);
        if (columns.get(i).primaryKey()) {
            sql.append(" primary key");
        } else if (columns.get(i).identity()) {
            sql.append(" identity");
        }
    }
    sql.append(")");
    execute(castUntainted(sql.toString()), connection);
    if (tableNeedsUpgrade(tableName, columns, connection)) {
        logger.warn("table {} thinks it still needs to be upgraded, even after it was just" + " upgraded",
                tableName);
    }
}

From source file:org.ow2.authzforce.core.pdp.io.xacml.json.BaseXacmlJsonResultPostprocessor.java

private static JSONObject convert(final IndividualXacmlJsonRequest request, final DecisionResult result) {
    assert request != null && result != null;

    final Map<String, Object> jsonPropertyMap = HashCollections.newUpdatableMap(6);
    // Decision/*from w  w  w.j  av  a2  s .c  om*/
    jsonPropertyMap.put("Decision", result.getDecision().value());

    // Status
    final Status status = result.getStatus();
    if (status != null) {
        jsonPropertyMap.put("Status", toJson(status));
    }

    // Obligations/Advice
    final ImmutableList<PepAction> pepActions = result.getPepActions();
    assert pepActions != null;
    if (!pepActions.isEmpty()) {
        final int numOfPepActions = pepActions.size();
        final List<JSONObject> jsonObligations = new ArrayList<>(numOfPepActions);
        final List<JSONObject> jsonAdvices = new ArrayList<>(numOfPepActions);
        pepActions.forEach(pepAction -> {
            final JSONObject pepActionJsonObject = toJson(pepAction.getId(),
                    pepAction.getAttributeAssignments());
            final List<JSONObject> pepActionJsonObjects = pepAction.isMandatory() ? jsonObligations
                    : jsonAdvices;
            pepActionJsonObjects.add(pepActionJsonObject);
        });

        if (!jsonObligations.isEmpty()) {
            jsonPropertyMap.put("Obligations", new JSONArray(jsonObligations));
        }

        if (!jsonAdvices.isEmpty()) {
            jsonPropertyMap.put("AssociatedAdvice", new JSONArray(jsonAdvices));
        }
    }

    // IncludeInResult categories
    final List<JSONObject> attributesByCategoryToBeReturned = request.getAttributesByCategoryToBeReturned();
    if (!attributesByCategoryToBeReturned.isEmpty()) {
        jsonPropertyMap.put("Category", new JSONArray(attributesByCategoryToBeReturned));
    }

    // PolicyIdentifierList
    final ImmutableList<PrimaryPolicyMetadata> applicablePolicies = result.getApplicablePolicies();
    if (applicablePolicies != null && !applicablePolicies.isEmpty()) {
        final List<JSONObject> policyRefs = new ArrayList<>(applicablePolicies.size());
        final List<JSONObject> policySetRefs = new ArrayList<>(applicablePolicies.size());
        for (final PrimaryPolicyMetadata applicablePolicy : applicablePolicies) {
            final JSONObject ref = new JSONObject(HashCollections.newImmutableMap("Id",
                    applicablePolicy.getId(), "Version", applicablePolicy.getVersion().toString()));
            final List<JSONObject> refs = applicablePolicy.getType() == TopLevelPolicyElementType.POLICY
                    ? policyRefs
                    : policySetRefs;
            refs.add(ref);
        }

        final Map<String, Object> policyListJsonObjMap = HashCollections.newUpdatableMap(2);
        if (!policyRefs.isEmpty()) {
            policyListJsonObjMap.put("PolicyIdReference", new JSONArray(policyRefs));
        }

        if (!policySetRefs.isEmpty()) {
            policyListJsonObjMap.put("PolicySetIdReference", new JSONArray(policySetRefs));
        }

        jsonPropertyMap.put("PolicyIdentifierList", new JSONObject(policyListJsonObjMap));
    }

    // final Result
    return new JSONObject(jsonPropertyMap);
}

From source file:com.android.manifmerger.PreValidator.java

/**
 * Checks that an element which is supposed to have a key does have one.
 * @param mergingReport report to log warnings and errors.
 * @param xmlElement xml element to check for key presence.
 * @return true if the element has a valid key or false it does not need one or it is invalid.
 *///from  ww  w.j  a v  a  2 s. c o  m
private static boolean checkKeyPresence(MergingReport.Builder mergingReport, XmlElement xmlElement) {
    ManifestModel.NodeKeyResolver nodeKeyResolver = xmlElement.getType().getNodeKeyResolver();
    ImmutableList<String> keyAttributesNames = nodeKeyResolver.getKeyAttributesNames();
    if (keyAttributesNames.isEmpty()) {
        return false;
    }
    if (Strings.isNullOrEmpty(xmlElement.getKey())) {
        // we should have a key but we don't.
        String message = keyAttributesNames.size() > 1
                ? String.format("Missing one of the key attributes '%1$s' on element %2$s at %3$s",
                        Joiner.on(',').join(keyAttributesNames), xmlElement.getId(), xmlElement.printPosition())
                : String.format("Missing '%1$s' key attribute on element %2$s at %3$s",
                        keyAttributesNames.get(0), xmlElement.getId(), xmlElement.printPosition());
        xmlElement.addMessage(mergingReport, ERROR, message);
        return false;
    }
    return true;
}

From source file:com.facebook.presto.metadata.FunctionListBuilder.java

private static List<Class<?>> getParameterTypes(Class<?>... types) {
    ImmutableList<Class<?>> parameterTypes = ImmutableList.copyOf(types);
    if (!parameterTypes.isEmpty() && parameterTypes.get(0) == ConnectorSession.class) {
        parameterTypes = parameterTypes.subList(1, parameterTypes.size());
    }// w  ww  .j  a  va2s.c  o m
    return parameterTypes;
}

From source file:org.lanternpowered.server.text.FormattingCodeTextSerializer.java

private static StringBuilder to(Text text, Locale locale, StringBuilder builder, @Nullable Character colorCode,
        @Nullable ResolvedChatStyle current) {
    ResolvedChatStyle style = null;//from   ww w  .j  a  v  a2s .com

    if (colorCode != null) {
        style = resolve(current, text.getFormat());

        if (current == null || (current.color != style.color) || (current.bold && !style.bold)
                || (current.italic && !style.italic) || (current.underlined && !style.underlined)
                || (current.strikethrough && !style.strikethrough)
                || (current.obfuscated && !style.obfuscated)) {
            if (style.color != null) {
                apply(builder, colorCode, ((FormattingCodeHolder) style.color).getCode());
            } else if (current != null) {
                apply(builder, colorCode, TextConstants.RESET);
            }

            apply(builder, colorCode, TextConstants.BOLD, style.bold);
            apply(builder, colorCode, TextConstants.ITALIC, style.italic);
            apply(builder, colorCode, TextConstants.UNDERLINE, style.underlined);
            apply(builder, colorCode, TextConstants.STRIKETHROUGH, style.strikethrough);
            apply(builder, colorCode, TextConstants.OBFUSCATED, style.obfuscated);
        } else {
            apply(builder, colorCode, TextConstants.BOLD, current.bold != style.bold);
            apply(builder, colorCode, TextConstants.ITALIC, current.italic != style.italic);
            apply(builder, colorCode, TextConstants.UNDERLINE, current.underlined != style.underlined);
            apply(builder, colorCode, TextConstants.STRIKETHROUGH,
                    current.strikethrough != style.strikethrough);
            apply(builder, colorCode, TextConstants.OBFUSCATED, current.obfuscated != style.obfuscated);
        }
    }

    if (text instanceof LiteralText) {
        builder.append(((LiteralText) text).getContent());
    } else if (text instanceof SelectorText) {
        builder.append(((SelectorText) text).getSelector().toPlain());
    } else if (text instanceof TranslatableText) {
        TranslatableText text0 = (TranslatableText) text;

        Translation translation = text0.getTranslation();
        ImmutableList<Object> args = text0.getArguments();

        Object[] args0 = new Object[args.size()];
        for (int i = 0; i < args0.length; i++) {
            Object object = args.get(i);
            if (object instanceof Text || object instanceof Text.Builder
                    || object instanceof TextRepresentable) {
                if (object instanceof Text) {
                    // Ignore
                } else if (object instanceof Text.Builder) {
                    object = ((Text.Builder) object).build();
                } else {
                    object = ((TextRepresentable) object).toText();
                }
                args0[i] = to((Text) object, locale, new StringBuilder(), colorCode).toString();
            } else {
                args0[i] = object;
            }
        }

        builder.append(translation.get(locale, args0));
    } else if (text instanceof ScoreText) {
        ScoreText text0 = (ScoreText) text;

        Optional<String> override = text0.getOverride();
        if (override.isPresent()) {
            builder.append(override.get());
        } else {
            builder.append(text0.getScore().getScore());
        }
    }

    for (Text child : text.getChildren()) {
        to(child, locale, builder, colorCode, style);
    }

    return builder;
}

From source file:com.github.rinde.opt.localsearch.Swaps.java

static <C, T> Iterator<Swap<T>> swapIterator(Schedule<C, T> schedule) {
    final ImmutableList.Builder<Iterator<Swap<T>>> iteratorBuilder = ImmutableList.builder();
    final Set<T> seen = newLinkedHashSet();
    for (int i = 0; i < schedule.routes.size(); i++) {
        final ImmutableList<T> row = schedule.routes.get(i);
        for (int j = 0; j < row.size(); j++) {
            final T t = row.get(j);
            if (j >= schedule.startIndices.getInt(i) && !seen.contains(t)) {
                iteratorBuilder.add(oneItemSwapIterator(schedule, schedule.startIndices, t, i));
            }/*from  ww  w  .  j ava 2  s. co m*/
            seen.add(t);
        }
    }
    return Iterators.concat(iteratorBuilder.build().iterator());
}

From source file:com.siemens.sw360.commonIO.TypeMappings.java

@NotNull
public static Map<Integer, Todo> getTodoMap(LicenseService.Iface licenseClient,
        Map<Integer, Obligation> obligationMap, Map<Integer, Set<Integer>> obligationTodoMapping,
        InputStream in) throws TException {
    List<CSVRecord> todoRecords = ImportCSV.readAsCSVRecords(in);
    final List<Todo> todos = CommonUtils.nullToEmptyList(licenseClient.getTodos());
    Map<Integer, Todo> todoMap = Maps.newHashMap(Maps.uniqueIndex(todos, getTodoIdentifier()));
    final List<Todo> todosToAdd = ConvertRecord.convertTodos(todoRecords);
    final ImmutableList<Todo> filteredTodos = getElementsWithIdentifiersNotInMap(getTodoIdentifier(), todoMap,
            todosToAdd);/*from w  w w .  ja  v a  2 s  . c o  m*/
    final ImmutableMap<Integer, Todo> filteredMap = Maps.uniqueIndex(filteredTodos, getTodoIdentifier());
    putToTodos(obligationMap, filteredMap, obligationTodoMapping);

    if (filteredTodos.size() > 0) {
        final List<Todo> addedTodos = licenseClient.addTodos(filteredTodos);
        if (addedTodos != null) {
            final ImmutableMap<Integer, Todo> addedTodoMap = Maps.uniqueIndex(addedTodos, getTodoIdentifier());
            todoMap.putAll(addedTodoMap);
        }
    }
    return todoMap;
}