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

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

Introduction

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

Prototype

public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) 

Source Link

Usage

From source file:com.proofpoint.discovery.Main.java

public static void main(String[] args) {
    try {//from  w  w  w.  ja v a 2 s.co m
        Bootstrap app = bootstrapApplication("discovery")
                .withModules(new MBeanModule(), new NodeModule(), new HttpServerModule(), explicitJaxrsModule(),
                        new JsonModule(), new JmxModule(), new JmxHttpModule(), new DiscoveryServerModule(),
                        new ReportingModule(), new ReportingClientModule(), new DiscoveryModule())
                .withApplicationDefaults(
                        ImmutableMap.of("http-server.admin.port", "4121", "http-server.http.port", "4111"));

        Injector injector = app.initialize();

        injector.getInstance(Announcer.class).start();
    } catch (Exception e) {
        log.error(e);
        System.exit(1);
    }
}

From source file:com.feedzai.fos.samples.weka.WekaTraining.java

public static void main(String[] args) throws RemoteException, NotBoundException, FOSException {
    FOSManagerAdapter manager = FOSManagerAdapter.create("localhost", 5959);

    List<Attribute> attributes = ImmutableList.of(new NumericAttribute("sepalLength"),
            new NumericAttribute("sepalWidth"), new NumericAttribute("petalLength"),
            new NumericAttribute("petalWidth"), new CategoricalAttribute("class",
                    ImmutableList.of("Iris-setosa", "Iris-versicolor", "Iris-virginica")));

    Map<String, String> properties = ImmutableMap.of(WekaModelConfig.CLASS_INDEX, "4",
            WekaModelConfig.CLASSIFIER_IMPL, J48.class.getName());

    ModelConfig modelConfig = new ModelConfig(attributes, properties);

    File trainFile = new File("iris.data");

    UUID uuid = manager.trainAndAddFile(modelConfig, trainFile.getAbsolutePath());

    System.out.println("Trained model UUID = " + uuid);
}

From source file:org.glowroot.agent.ui.sandbox.UiSandboxMain.java

public static void main(String[] args) throws Exception {
    Container container;//from   w w w .  j ava 2  s  .c o m
    File testDir = new File("target");
    File configFile = new File(testDir, "config.json");
    if (!configFile.exists()) {
        Files.write("{\"transactions\":{\"profilingIntervalMillis\":100},"
                + "\"ui\":{\"defaultTransactionType\":\"Sandbox\"}}", configFile, UTF_8);
    }
    if (useJavaagent && useGlowrootCentral) {
        container = new JavaagentContainer(testDir, false, ImmutableList.of("-Dglowroot.agent.id=UI Sandbox",
                "-Dglowroot.collector.address=localhost:8181"));
    } else if (useJavaagent) {
        container = new JavaagentContainer(testDir, true, ImmutableList.<String>of());
    } else if (useGlowrootCentral) {
        container = new LocalContainer(testDir, false, ImmutableMap.of("glowroot.agent.id", "UI Sandbox",
                "glowroot.collector.address", "localhost:8181"));
    } else {
        container = new LocalContainer(testDir, true, ImmutableMap.<String, String>of());
    }
    container.executeNoExpectedTrace(GenerateTraces.class);
}

From source file:org.apache.accumulo.examples.simple.sample.SampleExample.java

public static void main(String[] args) throws Exception {
    Opts opts = new Opts();
    BatchWriterOpts bwOpts = new BatchWriterOpts();
    opts.parseArgs(RandomBatchWriter.class.getName(), args, bwOpts);

    Connector conn = opts.getConnector();

    if (!conn.tableOperations().exists(opts.getTableName())) {
        conn.tableOperations().create(opts.getTableName());
    } else {// w  ww  .  j  av  a 2 s  . c  o m
        System.out.println("Table exists, not doing anything.");
        return;
    }

    // write some data
    BatchWriter bw = conn.createBatchWriter(opts.getTableName(), bwOpts.getBatchWriterConfig());
    bw.addMutation(createMutation("9225", "abcde", "file://foo.txt"));
    bw.addMutation(createMutation("8934", "accumulo scales", "file://accumulo_notes.txt"));
    bw.addMutation(createMutation("2317", "milk, eggs, bread, parmigiano-reggiano", "file://groceries/9/txt"));
    bw.addMutation(createMutation("3900", "EC2 ate my homework", "file://final_project.txt"));
    bw.flush();

    SamplerConfiguration sc1 = new SamplerConfiguration(RowSampler.class.getName());
    sc1.setOptions(ImmutableMap.of("hasher", "murmur3_32", "modulus", "3"));

    conn.tableOperations().setSamplerConfiguration(opts.getTableName(), sc1);

    Scanner scanner = conn.createScanner(opts.getTableName(), Authorizations.EMPTY);
    System.out.println("Scanning all data :");
    print(scanner);
    System.out.println();

    System.out.println(
            "Scanning with sampler configuration.  Data was written before sampler was set on table, scan should fail.");
    scanner.setSamplerConfiguration(sc1);
    try {
        print(scanner);
    } catch (SampleNotPresentException e) {
        System.out.println("  Saw sample not present exception as expected.");
    }
    System.out.println();

    // compact table to recreate sample data
    conn.tableOperations().compact(opts.getTableName(),
            new CompactionConfig().setCompactionStrategy(NO_SAMPLE_STRATEGY));

    System.out.println("Scanning after compaction (compaction should have created sample data) : ");
    print(scanner);
    System.out.println();

    // update a document in the sample data
    bw.addMutation(
            createMutation("2317", "milk, eggs, bread, parmigiano-reggiano, butter", "file://groceries/9/txt"));
    bw.close();
    System.out.println(
            "Scanning sample after updating content for docId 2317 (should see content change in sample data) : ");
    print(scanner);
    System.out.println();

    // change tables sampling configuration...
    SamplerConfiguration sc2 = new SamplerConfiguration(RowSampler.class.getName());
    sc2.setOptions(ImmutableMap.of("hasher", "murmur3_32", "modulus", "2"));
    conn.tableOperations().setSamplerConfiguration(opts.getTableName(), sc2);
    // compact table to recreate sample data using new configuration
    conn.tableOperations().compact(opts.getTableName(),
            new CompactionConfig().setCompactionStrategy(NO_SAMPLE_STRATEGY));

    System.out.println(
            "Scanning with old sampler configuration.  Sample data was created using new configuration with a compaction.  Scan should fail.");
    try {
        // try scanning with old sampler configuration
        print(scanner);
    } catch (SampleNotPresentException e) {
        System.out.println("  Saw sample not present exception as expected ");
    }
    System.out.println();

    // update expected sampler configuration on scanner
    scanner.setSamplerConfiguration(sc2);

    System.out.println("Scanning with new sampler configuration : ");
    print(scanner);
    System.out.println();

}

From source file:com.google.api.services.samples.storage.cmdline.StorageSample.java

public static void main(String[] args) {
    try {/*from  w  ww .  j a v  a 2 s.  co  m*/
        // initialize network, sample settings, credentials, and the storage client.
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
        SampleSettings settings = SampleSettings.load(jsonFactory);
        Credential credential = CredentialsProvider.authorize(httpTransport, jsonFactory);
        Storage storage = new Storage.Builder(httpTransport, jsonFactory, credential)
                .setApplicationName(APPLICATION_NAME).build();

        //
        // run commands
        //
        View.header1("Trying to create a new bucket " + settings.getBucket());
        BucketsInsertExample.createInProject(storage, settings.getProject(),
                new Bucket().setName(settings.getBucket()).setLocation("US"));

        View.header1("Getting bucket " + settings.getBucket() + " metadata");
        Bucket bucket = BucketsGetExample.get(storage, settings.getBucket());
        View.show(bucket);

        View.header1("Listing objects in bucket " + settings.getBucket());
        for (StorageObject object : ObjectsListExample.list(storage, settings.getBucket())) {
            View.show(object);
        }

        View.header1("Getting object metadata from gs://pub/SomeOfTheTeam.jpg");
        StorageObject object = ObjectsGetMetadataExample.get(storage, "pub", "SomeOfTheTeam.jpg");
        View.show(object);

        View.header1("Uploading object.");
        final long objectSize = 100 * 1024 * 1024 /* 100 MB */;
        InputStream data = new Helpers.RandomDataBlockInputStream(objectSize, 1024);
        object = new StorageObject().setBucket(settings.getBucket()).setName(settings.getPrefix() + "myobject")
                .setMetadata(ImmutableMap.of("key1", "value1", "key2", "value2"))
                .setCacheControl("max-age=3600, must-revalidate").setContentDisposition("attachment");
        object = ObjectsUploadExample.uploadWithMetadata(storage, object, data);
        View.show(object);
        System.out.println("md5Hash: " + object.getMd5Hash());
        System.out.println("crc32c: " + object.getCrc32c() + ", decoded to "
                + ByteBuffer.wrap(BaseEncoding.base64().decode(object.getCrc32c())).getInt());

        View.header1("Getting object data of uploaded object, calculate hashes/crcs.");
        OutputStream nullOutputStream = new OutputStream() {
            // Throws away the bytes.
            @Override
            public void write(int b) throws IOException {
            }

            @Override
            public void write(byte b[], int off, int len) {
            }
        };
        DigestOutputStream md5DigestOutputStream = new DigestOutputStream(nullOutputStream,
                MessageDigest.getInstance("MD5"));
        HashingOutputStream crc32cHashingOutputStream = new HashingOutputStream(Hashing.crc32c(),
                md5DigestOutputStream);
        ObjectsDownloadExample.downloadToOutputStream(storage, settings.getBucket(),
                settings.getPrefix() + "myobject", crc32cHashingOutputStream);
        String calculatedMD5 = BaseEncoding.base64().encode(md5DigestOutputStream.getMessageDigest().digest());
        System.out.println(
                "md5Hash: " + calculatedMD5 + " " + (object.getMd5Hash().equals(calculatedMD5) ? "(MATCHES)"
                        : "(MISMATCHES; data altered in transit)"));
        int calculatedCrc32c = crc32cHashingOutputStream.hash().asInt();
        String calculatedEncodedCrc32c = BaseEncoding.base64().encode(Ints.toByteArray(calculatedCrc32c));
        // NOTE: Don't compare HashCode.asBytes() directly, as that encodes the crc32c in
        // little-endien. One would have to reverse the bytes first.
        System.out.println("crc32c: " + calculatedEncodedCrc32c + ", decoded to "
                + crc32cHashingOutputStream.hash().asInt() + " "
                + (object.getCrc32c().equals(calculatedEncodedCrc32c) ? "(MATCHES)"
                        : "(MISMATCHES; data altered in transit)"));

        // success!
        return;
    } catch (GoogleJsonResponseException e) {
        // An error came back from the API.
        GoogleJsonError error = e.getDetails();
        System.err.println(error.getMessage());
        // More error information can be retrieved with error.getErrors().
    } catch (HttpResponseException e) {
        // No JSON body was returned by the API.
        System.err.println(e.getHeaders());
        System.err.println(e.getMessage());
    } catch (IOException e) {
        // Error formulating a HTTP request or reaching the HTTP service.
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    System.exit(1);
}

From source file:test.PlainSampleApp.java

/**
 * Sample app for a plain simple communication app
 *///from   w w  w . ja v  a 2s. c o  m
public static void main(String[] args) throws Exception {
    LOGGER.info("initializing");
    init();
    LOGGER.info("initialized");
    MethodCall methodCall = new MethodCall("doSomething", new Object[] { "Hello World!" },
            ImmutableMap.of("serviceId", "example+example+testlog", "contextId", "foo"));
    LOGGER.info("calling method");
    MethodResult methodResult = call(methodCall);
    System.out.println(methodResult);

    stop();
}

From source file:test.AuthenticatingSampleApp.java

/**
 * Small-test client that can be used for sending jms-messages to a running openengsb
 */// ww  w .j a  v  a 2  s.c  o m
public static void main(String[] args) throws Exception {
    LOGGER.info("initializing");
    init();
    LOGGER.info("initialized");
    MethodCall methodCall = new MethodCall("doSomething", new Object[] { "Hello World!" },
            ImmutableMap.of("serviceId", "example+example+testlog", "contextId", "foo"));
    LOGGER.info("calling method");
    MethodResult methodResult = call(methodCall, "admin", "password");
    System.out.println(methodResult);

    stop();
}

From source file:test.SecureSampleApp.java

/**
 * Small-test client that can be used for sending jms-messages to a running
 * openengsb/* w w w. jav  a2 s.c  om*/
 */
public static void main(String[] args) throws Exception {
    LOGGER.info("initializing");
    init();
    LOGGER.info("initialized");
    MethodCall methodCall = new MethodCall("doSomething", new Object[] { "Hello World!" },
            ImmutableMap.of("serviceId", "example+example+testlog", "contextId", "foo"));
    LOGGER.info("calling method");
    MethodResult methodResult = call(methodCall, "admin", "password");
    System.out.println(methodResult);
}

From source file:google.registry.monitoring.metrics.example.SheepCounterExample.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("Missing required project argument");
        System.err.printf("Usage: java %s gcp-project-id [verbose]\n", SheepCounterExample.class.getName());
        return;/* w  w w. j a v  a 2s  .  c  o  m*/
    }
    String project = args[0];

    // Turn up the logging verbosity
    if (args.length > 1) {
        Logger log = LogManager.getLogManager().getLogger("");
        log.setLevel(Level.ALL);
        for (Handler h : log.getHandlers()) {
            h.setLevel(Level.ALL);
        }
    }

    // Create a sample resource. In this case, a GCE Instance.
    // See https://cloud.google.com/monitoring/api/resources for a list of resource types.
    MonitoredResource monitoredResource = new MonitoredResource().setType("gce_instance")
            .setLabels(ImmutableMap.of("instance_id", "test-instance", "zone", "us-central1-f"));

    // Set up the Metrics infrastructure.
    MetricWriter stackdriverWriter = new StackdriverWriter(createAuthorizedMonitoringClient(), project,
            monitoredResource, STACKDRIVER_MAX_QPS, STACKDRIVER_MAX_POINTS_PER_REQUEST);
    final MetricReporter reporter = new MetricReporter(stackdriverWriter, METRICS_REPORTING_INTERVAL,
            Executors.defaultThreadFactory());
    reporter.startAsync().awaitRunning();

    // Set up a handler to stop sleeping on SIGINT.
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            reporter.stopAsync().awaitTerminated();
            // Allow the LogManager to cleanup the loggers.
            DelayedShutdownLogManager.resetFinally();
        }
    }));

    System.err.println("Send SIGINT (Ctrl+C) to stop sleeping.");
    while (true) {
        // Count some Googley sheep.
        int colorIndex = new Random().nextInt(SHEEP_COLORS.size());
        int speciesIndex = new Random().nextInt(SHEEP_SPECIES.size());
        sheepCounter.incrementBy(1, SHEEP_COLORS.get(colorIndex), SHEEP_SPECIES.get(speciesIndex));
        sheepFluffiness.record(new Random().nextDouble() * 200, SHEEP_COLORS.get(colorIndex),
                SHEEP_SPECIES.get(speciesIndex));
        isSleeping.set(true);

        logger.info("zzz...");
        Thread.sleep(5000);
    }
}

From source file:org.usc.wechat.mp.sdk.util.platform.BasicUtil.java

public static JsonRtn shortUrl(License license, String url) {
    if (StringUtils.isEmpty(url)) {
        return JsonRtnUtil.buildFailureJsonRtn(JsonRtn.class, "missing url");
    }/*from   w w  w.  j  a  v  a  2s.c o m*/

    Map<String, String> paramMap = ImmutableMap.of("action", "long2short", "long_url", url);
    return HttpUtil.postBodyRequest(WechatRequest.SHORT_URL, license, paramMap, JsonRtn.class);
}