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

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

Introduction

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

Prototype

int size();

Source Link

Document

Returns the number of key-value mappings in this map.

Usage

From source file:se.sics.caracaldb.global.SchemaData.java

static void serialiseSchema(ByteBuf buf, ByteBuffer id, String name, ImmutableMap<String, String> metaData) {
    buf.writeInt(id.array().length);/*www .  jav  a  2  s.co m*/
    buf.writeBytes(id.array());
    byte[] nameB = name.getBytes(CHARSET);
    buf.writeInt(nameB.length);
    buf.writeBytes(nameB);
    buf.writeInt(metaData.size());
    for (Entry<String, String> e : metaData.entrySet()) {
        byte[] keyB = e.getKey().getBytes(CHARSET);
        byte[] valB = e.getValue().getBytes(CHARSET);
        buf.writeInt(keyB.length);
        buf.writeBytes(keyB);
        buf.writeInt(valB.length);
        buf.writeBytes(valB);
    }
}

From source file:org.apache.hadoop.hive.ql.optimizer.optiq.translator.PlanModifierForASTConv.java

private static void fixTopOBSchema(final RelNode rootRel, Pair<RelNode, RelNode> topSelparentPair,
        List<FieldSchema> resultSchema) throws OptiqSemanticException {
    if (!(topSelparentPair.getKey() instanceof SortRel)
            || !HiveOptiqUtil.orderRelNode(topSelparentPair.getKey())) {
        return;//  w w  w. jav a 2  s .  c  om
    }
    HiveSortRel obRel = (HiveSortRel) topSelparentPair.getKey();
    ProjectRelBase obChild = (ProjectRelBase) topSelparentPair.getValue();
    if (obChild.getRowType().getFieldCount() <= resultSchema.size()) {
        return;
    }

    RelDataType rt = obChild.getRowType();
    @SuppressWarnings({ "unchecked", "rawtypes" })
    Set<Integer> collationInputRefs = new HashSet(RelCollationImpl.ordinals(obRel.getCollation()));
    ImmutableMap.Builder<Integer, RexNode> inputRefToCallMapBldr = ImmutableMap.builder();
    for (int i = resultSchema.size(); i < rt.getFieldCount(); i++) {
        if (collationInputRefs.contains(i)) {
            inputRefToCallMapBldr.put(i, obChild.getChildExps().get(i));
        }
    }
    ImmutableMap<Integer, RexNode> inputRefToCallMap = inputRefToCallMapBldr.build();

    if ((obChild.getRowType().getFieldCount() - inputRefToCallMap.size()) != resultSchema.size()) {
        LOG.error(generateInvalidSchemaMessage(obChild, resultSchema, inputRefToCallMap.size()));
        throw new OptiqSemanticException("Result Schema didn't match Optimized Op Tree Schema");
    }
    // This removes order-by only expressions from the projections.
    HiveProjectRel replacementProjectRel = HiveProjectRel.create(obChild.getChild(),
            obChild.getChildExps().subList(0, resultSchema.size()),
            obChild.getRowType().getFieldNames().subList(0, resultSchema.size()));
    obRel.replaceInput(0, replacementProjectRel);
    obRel.setInputRefToCallMap(inputRefToCallMap);
}

From source file:org.fixb.meta.FixMetaScanner.java

private static <T> List<FixFieldMeta> processFields(final Class<T> model,
        final Optional<Constructor<T>> constructor, final MutableFixMetaDictionary dictionary) {
    final ImmutableMap<Integer, FixFieldMeta> fixFields = scanFields(model, dictionary);

    if (constructor.isPresent()) {
        final FixFieldMeta[] orderedFixFields = new FixFieldMeta[fixFields.size()];
        orderFixFields(constructor.get(), fixFields, orderedFixFields, dictionary, 0);
        return asList(orderedFixFields);
    } else {//from w w w. jav  a 2  s . com
        return new ArrayList<>(fixFields.values());
    }
}

From source file:com.github.rinde.dynurg.Generator.java

private static void generate(RandomGenerator rng, LocationGenerator lg) {
    final List<Long> urgencyLevels = Longs.asList(0, 5, 10, 15, 20, 25, 30, 35, 40, 45);

    final ImmutableMap.Builder<GeneratorSettings, ScenarioGenerator> generatorsMap = ImmutableMap.builder();

    for (final long urg : urgencyLevels) {
        System.out.print("create " + urg);
        final long urgency = urg * 60 * 1000L;
        // The office hours is the period in which new orders are accepted, it
        // is defined as [0,officeHoursLength).
        final long officeHoursLength;
        if (urgency < HALF_DIAG_TT) {
            officeHoursLength = SCENARIO_LENGTH - TWO_DIAG_TT - PICKUP_DURATION - DELIVERY_DURATION;
        } else {/* w  ww. java 2  s .  co  m*/
            officeHoursLength = SCENARIO_LENGTH - urgency - ONE_AND_HALF_DIAG_TT - PICKUP_DURATION
                    - DELIVERY_DURATION;
        }

        final double numPeriods = officeHoursLength / (double) INTENSITY_PERIOD;

        final Map<String, String> props = newLinkedHashMap();
        props.put("expected_num_orders", Integer.toString(NUM_ORDERS));
        props.put("time_series", "sine Poisson ");
        props.put("time_series.period", Long.toString(INTENSITY_PERIOD));
        props.put("time_series.num_periods", Double.toString(numPeriods));
        props.put("pickup_duration", Long.toString(PICKUP_DURATION));
        props.put("delivery_duration", Long.toString(DELIVERY_DURATION));
        props.put("width_height", String.format("%1.1fx%1.1f", AREA_WIDTH, AREA_WIDTH));
        final GeneratorSettings sineSettings = new GeneratorSettings(TimeSeriesType.SINE, urg, SCENARIO_LENGTH,
                officeHoursLength, props);

        System.out.print(" non-homogenous Poisson");
        // NON-HOMOGENOUS
        final TimeSeriesGenerator sineTsg = TimeSeries.nonHomogenousPoisson(officeHoursLength,
                IntensityFunctions.sineIntensity().area(NUM_ORDERS / numPeriods).period(INTENSITY_PERIOD)
                        .height(StochasticSuppliers.uniformDouble(-.99, 3d))
                        .phaseShift(StochasticSuppliers.uniformDouble(0, INTENSITY_PERIOD))
                        .buildStochasticSupplier());

        System.out.print(" homogenous Poisson");
        // HOMOGENOUS
        props.put("time_series", "homogenous Poisson");
        props.put("time_series.intensity", Double.toString((double) NUM_ORDERS / (double) officeHoursLength));
        props.remove("time_series.period");
        props.remove("time_series.num_periods");
        final TimeSeriesGenerator homogTsg = TimeSeries.homogenousPoisson(officeHoursLength, NUM_ORDERS);
        final GeneratorSettings homogSettings = new GeneratorSettings(TimeSeriesType.HOMOGENOUS, urg,
                SCENARIO_LENGTH, officeHoursLength, props);

        System.out.print(" normal");
        // NORMAL
        props.put("time_series", "normal");
        props.remove("time_series.intensity");
        final TimeSeriesGenerator normalTsg = TimeSeries.normal(officeHoursLength, NUM_ORDERS, 2.4 * 60 * 1000);
        final GeneratorSettings normalSettings = new GeneratorSettings(TimeSeriesType.NORMAL, urg,
                SCENARIO_LENGTH, officeHoursLength, props);

        System.out.print(" uniform");
        // UNIFORM
        props.put("time_series", "uniform");
        final StochasticSupplier<Double> maxDeviation = StochasticSuppliers.normal().mean(1 * 60 * 1000)
                .std(1 * 60 * 1000).lowerBound(0).upperBound(15d * 60 * 1000).buildDouble();
        final TimeSeriesGenerator uniformTsg = TimeSeries.uniform(officeHoursLength, NUM_ORDERS, maxDeviation);
        final GeneratorSettings uniformSettings = new GeneratorSettings(TimeSeriesType.UNIFORM, urg,
                SCENARIO_LENGTH, officeHoursLength, props);
        System.out.println(".");

        generatorsMap.put(sineSettings, createGenerator(SCENARIO_LENGTH, urgency, sineTsg, lg));
        generatorsMap.put(homogSettings, createGenerator(SCENARIO_LENGTH, urgency, homogTsg, lg));
        generatorsMap.put(normalSettings, createGenerator(SCENARIO_LENGTH, urgency, normalTsg, lg));
        generatorsMap.put(uniformSettings, createGenerator(SCENARIO_LENGTH, urgency, uniformTsg, lg));
    }

    final ImmutableMap<GeneratorSettings, ScenarioGenerator> scenarioGenerators = generatorsMap.build();

    System.out.println("num generators: " + scenarioGenerators.size());
    for (final Entry<GeneratorSettings, ScenarioGenerator> entry : scenarioGenerators.entrySet()) {

        final GeneratorSettings generatorSettings = entry.getKey();
        System.out.println("URGENCY: " + generatorSettings.urgency + " " + generatorSettings.timeSeriesType);

        if (generatorSettings.timeSeriesType == TimeSeriesType.SINE) {
            createScenarios(rng, generatorSettings, entry.getValue(), .0, .46, 10);
        } else if (generatorSettings.timeSeriesType == TimeSeriesType.HOMOGENOUS) {
            createScenarios(rng, generatorSettings, entry.getValue(), .49, .56, 2);
        } else if (generatorSettings.timeSeriesType == TimeSeriesType.NORMAL) {
            createScenarios(rng, generatorSettings, entry.getValue(), .59, .66, 2);
        } else if (generatorSettings.timeSeriesType == TimeSeriesType.UNIFORM) {
            createScenarios(rng, generatorSettings, entry.getValue(), .69, 1, 7);
        } else {
            throw new IllegalArgumentException();
        }
    }
    System.out.println("DONE.");
}

From source file:com.facebook.buck.cxx.toolchain.CxxBuckConfig.java

/**
 * If the config specifies a value for "toolchain_target", returns a {@link UnresolvedCxxPlatform}
 * backed by the specified target.//  ww w  .  j a v a2  s. co  m
 */
public static Optional<UnresolvedCxxPlatform> getProviderBasedPlatform(BuckConfig config, Flavor flavor) {
    String cxxSection = new CxxBuckConfig(config, flavor).cxxSection;

    Optional<BuildTarget> toolchainTarget = config.getBuildTarget(cxxSection, TOOLCHAIN_TARGET,
            EmptyTargetConfiguration.INSTANCE);
    if (!toolchainTarget.isPresent()) {
        return Optional.empty();
    }

    if (!cxxSection.equals(UNFLAVORED_CXX_SECTION)) {
        // In a flavored cxx section, we don't allow any configuration except for configuration of the
        // platform.
        ImmutableMap<String, String> allEntries = config.getEntriesForSection(cxxSection);
        if (allEntries.size() != 1) {
            throw new HumanReadableException(
                    "When configuring a cxx %s, no other configuration is allowed in that section. Got unexpected keys [%s]",
                    TOOLCHAIN_TARGET, Joiner.on(", ")
                            .join(Sets.difference(allEntries.keySet(), ImmutableSet.of(TOOLCHAIN_TARGET))));
        }
    }

    return Optional.of(new ProviderBasedUnresolvedCxxPlatform(toolchainTarget.get(), flavor));
}

From source file:de.adrodoc55.minecraft.mpl.conversion.SchematicConverter.java

public static TagCompound convert(MplCompilationResult result) {
    ImmutableMap<Coordinate3D, MplBlock> blockMap = result.getBlocks();
    ImmutableSet<Coordinate3D> coordinates = blockMap.keySet();
    Coordinate3D min = getMinCoordinate(coordinates);
    Coordinate3D max = getMaxCoordinate(coordinates);
    short width = (short) (1 + max.getX() - min.getX());
    short heigth = (short) (1 + max.getY() - min.getY());
    short length = (short) (1 + max.getZ() - min.getZ());
    int volume = width * heigth * length;
    ByteBuffer blocks = ByteBuffer.allocate(volume);
    ByteBuffer data = ByteBuffer.allocate(volume);
    List<ITag> tileEntities = new ArrayList<>(blockMap.size());
    for (int y = min.getY(); y <= max.getY(); y++) {
        for (int z = min.getZ(); z <= max.getZ(); z++) {
            for (int x = min.getX(); x <= max.getX(); x++) {
                Coordinate3D coord = new Coordinate3D(x, y, z);
                MplBlock block = blockMap.get(coord);
                if (block == null) {
                    block = new AirBlock(coord);
                }//  w w w . j a v a 2  s  .c o m

                // block
                blocks.put(block.getByteBlockId());

                // data
                if (block instanceof CommandBlock) {
                    data.put(((CommandBlock) block).getDamageValue());
                } else {
                    data.put((byte) 0);
                }

                // tile entity
                if (block instanceof CommandBlock) {
                    tileEntities.add(toControl((CommandBlock) block));
                }
            }
        }
    }
    TagCompound schematic = new TagCompound("Schematic");
    schematic.setTag(new TagShort("Width", width));
    schematic.setTag(new TagShort("Height", heigth));
    schematic.setTag(new TagShort("Length", length));
    schematic.setTag(new TagString("Materials", "Alpha"));
    schematic.setTag(new TagByteArray("Blocks", blocks.array()));
    schematic.setTag(new TagByteArray("Data", data.array()));
    schematic.setTag(new TagList("TileEntities", tileEntities));
    schematic.setTag(new TagList("Entities", new ArrayList<>()));
    schematic.setTag(new TagList("TileTicks", new ArrayList<>()));
    return schematic;
}

From source file:com.facebook.buck.artifact_cache.SQLiteArtifactCache.java

@VisibleForTesting
static byte[] marshalMetadata(ImmutableMap<String, String> metadata) throws IOException {
    ByteArrayOutputStream metadataStream = new ByteArrayOutputStream();
    try (DataOutputStream out = new DataOutputStream(metadataStream)) {
        out.writeInt(metadata.size());
        for (Map.Entry<String, String> entry : metadata.entrySet()) {
            out.writeUTF(entry.getKey());
            byte[] value = entry.getValue().getBytes(Charsets.UTF_8);
            out.writeInt(value.length);/*from   w  ww  .j  av  a 2s  .c  o  m*/
            out.write(value);
        }
    }
    return metadataStream.toByteArray();
}

From source file:com.facebook.buck.artifact_cache.HttpArtifactCacheBinaryProtocol.java

@VisibleForTesting
static byte[] createMetadataHeader(ImmutableSet<RuleKey> ruleKeys, ImmutableMap<String, String> metadata,
        ByteSource data) throws IOException {

    ByteArrayOutputStream rawOut = new ByteArrayOutputStream();
    Hasher hasher = HASH_FUNCTION.newHasher();
    try (DataOutputStream out = new DataOutputStream(new HasherOutputStream(hasher, rawOut))) {

        // Write the rule keys to the raw metadata, including them in the end-to-end checksum.
        out.writeInt(ruleKeys.size());/* w  w w . j av a 2  s. com*/
        for (RuleKey ruleKey : ruleKeys) {
            out.writeUTF(ruleKey.toString());
        }

        // Write out the metadata map to the raw metadata, including it in the end-to-end checksum.
        out.writeInt(metadata.size());
        for (Map.Entry<String, String> ent : metadata.entrySet()) {
            out.writeUTF(ent.getKey());
            byte[] val = ent.getValue().getBytes(Charsets.UTF_8);
            out.writeInt(val.length);
            out.write(val);
            if (out.size() > MAX_METADATA_HEADER_SIZE) {
                throw new IOException("Metadata header too big.");
            }
        }
    }

    // Add the file data contents to the end-to-end checksum.
    data.copyTo(new HasherOutputStream(hasher, ByteStreams.nullOutputStream()));

    // Finish the checksum, adding it to the raw metadata
    rawOut.write(hasher.hash().asBytes());

    // Finally, base64 encode the raw bytes to make usable in a HTTP header.
    byte[] bytes = rawOut.toByteArray();
    if (bytes.length > MAX_METADATA_HEADER_SIZE) {
        throw new IOException("Metadata header too big.");
    }
    return bytes;
}

From source file:io.atomix.utils.serializer.serializers.ImmutableMapSerializer.java

@Override
public void write(Kryo kryo, Output output, ImmutableMap<?, ?> object) {
    output.writeInt(object.size());
    for (Entry<?, ?> e : object.entrySet()) {
        kryo.writeClassAndObject(output, e.getKey());
        kryo.writeClassAndObject(output, e.getValue());
    }//from   w  w  w. j  a v  a 2s . co  m
}

From source file:org.gradle.api.internal.changedetection.state.InputPropertiesSerializer.java

public void write(Encoder encoder, ImmutableMap<String, ValueSnapshot> properties) throws Exception {
    encoder.writeSmallInt(properties.size());
    for (Map.Entry<String, ValueSnapshot> entry : properties.entrySet()) {
        encoder.writeString(entry.getKey());
        writeSnapshot(encoder, entry.getValue());
    }/*from ww w.j a v  a  2s  . com*/
}