Example usage for com.google.common.collect ImmutableMap.Builder put

List of usage examples for com.google.common.collect ImmutableMap.Builder put

Introduction

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

Prototype

public final V put(K k, V v) 

Source Link

Usage

From source file:org.grouplens.lenskit.data.dao.MapItemNameDAO.java

/**
 * Read an item list DAO from a file./*www . ja va  2  s.c  o m*/
 * @param file A file of item IDs, one per line.
 * @return The item list DAO.
 * @throws java.io.IOException if there is an error reading the list of items.
 */
public static MapItemNameDAO fromCSVFile(File file) throws IOException {
    LineCursor cursor = LineCursor.openFile(file, CompressionMode.AUTO);
    try {
        ImmutableMap.Builder<Long, String> names = ImmutableMap.builder();
        StrTokenizer tok = StrTokenizer.getCSVInstance();
        for (String line : cursor) {
            tok.reset(line);
            long item = Long.parseLong(tok.next());
            String title = tok.nextToken();
            if (title != null) {
                names.put(item, title);
            }
        }
        return new MapItemNameDAO(names.build());
    } catch (NoSuchElementException ex) {
        throw new IOException(String.format("%s:%s: not enough columns", file, cursor.getLineNumber()), ex);
    } catch (NumberFormatException ex) {
        throw new IOException(String.format("%s:%s: id not an integer", file, cursor.getLineNumber()), ex);
    } finally {
        cursor.close();
    }
}

From source file:org.prebake.service.tools.ext.JUnitRunner.java

/** Produce a structure like that documented in the class comment. */
private static ImmutableMap<String, ?> jsonReport(List<TestState> tests) {
    EnumMap<TestResult, Integer> summary = new EnumMap<TestResult, Integer>(TestResult.class);
    for (TestResult r : TestResult.values()) {
        summary.put(r, 0);/*from   w w w.  j a v  a2s  . c om*/
    }
    ImmutableList.Builder<ImmutableMap<String, ?>> testJson = ImmutableList.builder();
    for (TestState t : tests) {
        ImmutableMap.Builder<String, Object> b = ImmutableMap.builder();
        b.put(ReportKey.CLASS_NAME, t.key.className);
        b.put(ReportKey.METHOD_NAME, t.key.methodName);
        b.put(ReportKey.TEST_NAME, t.key.testName);
        if (!t.annotations.isEmpty()) {
            ImmutableList.Builder<Object> annotations = ImmutableList.builder();
            for (Annotation a : t.annotations) {
                annotations.add(ImmutableMap.of(ReportKey.CLASS_NAME, a.annotationType().getName(),
                        ReportKey.TEXT, a.toString()));
            }
            b.put(ReportKey.ANNOTATIONS, annotations.build());
        }
        if (t.message != null) {
            b.put(ReportKey.FAILURE_MESSAGE, t.message);
        }
        if (t.trace != null) {
            b.put(ReportKey.FAILURE_TRACE, t.trace);
        }
        if (t.out.size() > 0) {
            b.put(ReportKey.OUT, new String(t.out.toByteArray(), Charsets.UTF_8));
        }
        b.put(ReportKey.RESULT, t.result.name());
        summary.put(t.result, summary.get(t.result) + 1);
        testJson.add(b.build());
    }
    ImmutableMap.Builder<String, Integer> summaryJson = ImmutableMap.builder();
    summaryJson.put(ReportKey.TOTAL, tests.size());
    for (Map.Entry<TestResult, Integer> count : summary.entrySet()) {
        summaryJson.put(count.getKey().name(), count.getValue());
    }
    return ImmutableMap.of(ReportKey.TESTS, testJson.build(), ReportKey.SUMMARY, summaryJson.build());
}

From source file:net.techcable.pineapple.collect.ImmutableMaps.java

@Nonnull
public static <K, V, T, U> ImmutableMap<T, U> transform(ImmutableMap<K, V> original,
        Function<K, T> keyTransformer, Function<V, U> valueTransformer) {
    ImmutableMap.Builder<T, U> resultBuilder = builder(checkNotNull(original, "Null map").size());
    forEach(original, (originalKey, originalValue) -> {
        T newKey = checkNotNull(keyTransformer, "Null key transformer").apply(originalKey);
        U newValue = checkNotNull(valueTransformer, "Null value transformer").apply(originalValue);
        resultBuilder.put(newKey, newValue);
    });/*from   ww w. j av a  2s . c om*/
    return resultBuilder.build();
}

From source file:org.openqa.selenium.server.htmlrunner.NonReflectiveSteps.java

private static ImmutableMap<String, CoreStepFactory> build() {
    ImmutableMap.Builder<String, CoreStepFactory> steps = ImmutableMap.builder();

    CoreStepFactory nextCommandFails = (locator,
            value) -> (selenium, state) -> new NextCommandFails(state.expand(locator));
    steps.put("assertErrorOnNext", nextCommandFails);
    steps.put("assertFailureOnNext", nextCommandFails);

    steps.put("verifyErrorOnNext",
            (locator, value) -> (selenium, state) -> new VerifyNextCommandFails(state.expand(locator)));
    steps.put("verifyFailureOnNext",
            (locator, value) -> (selenium, state) -> new VerifyNextCommandFails(state.expand(locator)));

    class SelectedOption implements CoreStep {

        private final String locator;
        private final String value;
        private final NextStepDecorator onFailure;

        public SelectedOption(String locator, String value, NextStepDecorator onFailure) {
            this.locator = locator;
            this.value = value;
            this.onFailure = onFailure;
        }/*from w w w .ja  va2  s .c o  m*/

        @Override
        public NextStepDecorator execute(Selenium selenium, TestState state) {
            JavascriptLibrary library = new JavascriptLibrary();
            ElementFinder finder = new ElementFinder(library);
            SeleniumSelect select = new SeleniumSelect(library, finder,
                    ((WrapsDriver) selenium).getWrappedDriver(), locator);

            WebElement element = select.findOption(value);
            if (element == null) {
                return onFailure;
            }
            return NextStepDecorator.IDENTITY;
        }
    }

    steps.put("assertSelected", ((locator, value) -> new SelectedOption(locator, value,
            NextStepDecorator.ASSERTION_FAILED(value + " not selected"))));
    steps.put("verifySelected", ((locator, value) -> new SelectedOption(locator, value,
            NextStepDecorator.VERIFICATION_FAILED(value + " not selected"))));

    steps.put("echo", ((locator, value) -> (selenium, state) -> {
        LOG.info(locator);
        return NextStepDecorator.IDENTITY;
    }));

    steps.put("pause", ((locator, value) -> (selenium, state) -> {
        try {
            long timeout = Long.parseLong(state.expand(locator));
            Thread.sleep(timeout);
            return NextStepDecorator.IDENTITY;
        } catch (NumberFormatException e) {
            return NextStepDecorator
                    .ERROR(new SeleniumException("Unable to parse timeout: " + state.expand(locator)));
        } catch (InterruptedException e) {
            System.exit(255);
            throw new CoreRunnerError("We never get this far");
        }
    }));

    steps.put("store", (((locator, value) -> ((selenium, state) -> {
        state.store(state.expand(locator), state.expand(value));
        return NextStepDecorator.IDENTITY;
    }))));

    return steps.build();
}

From source file:org.mule.module.extension.internal.capability.xml.schema.AnnotationProcessorUtils.java

private static <T extends Element> Map<String, T> collectAnnotatedElements(Iterable<T> elements,
        Class<? extends Annotation> annotation) {
    ImmutableMap.Builder<String, T> fields = ImmutableMap.builder();

    for (T element : elements) {
        if (element.getAnnotation(annotation) != null) {
            fields.put(element.getSimpleName().toString(), element);
        }//from  w  w w.  j ava  2s  .  c o  m
    }

    return fields.build();
}

From source file:io.prestosql.orc.OrcReader.java

static void validateFile(OrcWriteValidation writeValidation, OrcDataSource input, List<Type> types,
        DateTimeZone hiveStorageTimeZone, OrcEncoding orcEncoding) throws OrcCorruptionException {
    ImmutableMap.Builder<Integer, Type> readTypes = ImmutableMap.builder();
    for (int columnIndex = 0; columnIndex < types.size(); columnIndex++) {
        readTypes.put(columnIndex, types.get(columnIndex));
    }//  w w w  . j a  va 2  s  .  c o  m
    try {
        OrcReader orcReader = new OrcReader(input, orcEncoding, new DataSize(1, MEGABYTE),
                new DataSize(8, MEGABYTE), new DataSize(8, MEGABYTE), new DataSize(16, MEGABYTE),
                Optional.of(writeValidation));
        try (OrcRecordReader orcRecordReader = orcReader.createRecordReader(readTypes.build(),
                OrcPredicate.TRUE, hiveStorageTimeZone, newSimpleAggregatedMemoryContext(),
                INITIAL_BATCH_SIZE)) {
            while (orcRecordReader.nextBatch() >= 0) {
                // ignored
            }
        }
    } catch (IOException e) {
        throw new OrcCorruptionException(e, input.getId(), "Validation failed");
    }
}

From source file:com.yahoo.yqlplus.engine.internal.plan.types.Conversions.java

private static void registerSeq(ImmutableMap.Builder<String, BytecodeSequence> m, Class<?> fromType,
        final int opcode, Class<?> asType, Class<?> ownerType, String methodName) {
    final BoxCall box = new BoxCall(asType, methodName, ownerType);
    m.put(key(fromType, ownerType), new BytecodeSequence() {
        @Override/*  w  w  w .  j  a  v  a  2  s.c o m*/
        public void generate(CodeEmitter code) {
            code.getMethodVisitor().visitInsn(opcode);
            code.exec(box);
        }
    });
}

From source file:com.android.assetstudiolib.AssetStudio.java

@NonNull
@VisibleForTesting/* www  .ja  v a  2  s .  c o  m*/
static Map<String, String> getBasenameToPathMap(@NonNull Generator generator) {
    ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<>();
    int dotXmlLength = DOT_XML.length();

    for (String category : MATERIAL_DESIGN_ICON_CATEGORIES) {
        String path = MATERIAL_DESIGN_ICONS_PATH + category + '/';

        for (Iterator<String> i = generator.getResourceNames(path); i.hasNext();) {
            String name = i.next();
            builder.put(name.substring(0, name.length() - dotXmlLength), path + name);
        }
    }

    return builder.build();
}

From source file:com.android.tools.idea.uibuilder.property.PropertyTestCase.java

private static ImmutableMap.Builder<String, NlComponent> addToMap(
        @NotNull ImmutableMap.Builder<String, NlComponent> builder, @NotNull List<NlComponent> components) {
    for (NlComponent component : components) {
        if (component.getId() != null) {
            builder.put(component.getId(), component);
        }//from   ww  w  .  j  ava  2s. com
        addToMap(builder, component.getChildren());
    }
    return builder;
}

From source file:com.spectralogic.ds3autogen.utils.ConverterUtil.java

/**
 * Removes all unused types from the Ds3Type map. Types are considered to be used if
 * they are used within a Ds3Request, and/or if they are used within another type that
 * is also used.//ww  w.ja  v a  2 s  .  c  o  m
 * @param types A Ds3Type map
 * @param requests A list of Ds3Requests
 */
public static ImmutableMap<String, Ds3Type> removeUnusedTypes(final ImmutableMap<String, Ds3Type> types,
        final ImmutableList<Ds3Request> requests) {
    if (isEmpty(types) || isEmpty(requests)) {
        return ImmutableMap.of();
    }

    final ImmutableSet.Builder<String> usedTypesBuilder = ImmutableSet.builder();
    usedTypesBuilder.addAll(getUsedTypesFromRequests(requests));
    usedTypesBuilder.addAll(getUsedTypesFromAllTypes(types, usedTypesBuilder.build()));
    final ImmutableSet<String> usedTypes = usedTypesBuilder.build();

    final ImmutableMap.Builder<String, Ds3Type> builder = ImmutableMap.builder();
    for (final Map.Entry<String, Ds3Type> entry : types.entrySet()) {
        if (usedTypes.contains(entry.getKey())) {
            builder.put(entry.getKey(), entry.getValue());
        }
    }
    return builder.build();
}