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

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

Introduction

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

Prototype

public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1) 

Source Link

Document

Returns an immutable multimap containing a single entry.

Usage

From source file:org.jclouds.demo.tweetstore.controller.EnqueueStoresController.java

@VisibleForTesting
void enqueueStoreTweetTasks() {
    for (String contextName : contextNames) {
        logger.debug("enqueuing task to store tweets in blobstore '%s'", contextName);
        taskQueue.add(taskQueue.getHttpRequestFactory()
                .create(HttpRequest.builder().endpoint(URI.create(baseUrl + "/store/do"))
                        .headers(ImmutableMultimap.of("context", contextName)).method("GET").build()));
    }//from w w  w.  ja  v  a2  s .  c om
}

From source file:co.cask.cdap.security.authentication.client.basic.BasicAuthenticationClient.java

@Override
protected Multimap<String, String> getAuthenticationHeaders() {
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
        throw new IllegalStateException("Base authentication client is not configured!");
    }/* ww w .j  ava2s .  co  m*/

    String auth = Base64.encodeBase64String(String.format("%s:%s", username, password).getBytes());
    auth = auth.replaceAll("(\r|\n)", StringUtils.EMPTY);
    return ImmutableMultimap.of(HttpHeaders.AUTHORIZATION, AUTHENTICATION_HEADER_PREFIX_BASIC + auth);
}

From source file:co.cask.cdap.internal.app.runtime.webapp.IntactJarHttpHandler.java

@GET
@Path("**")
public void serve(HttpRequest request, HttpResponder responder) {
    try {/*from w ww . ja v a2  s.  co  m*/
        String path = request.getUri();
        if (path == null) {
            responder.sendStatus(HttpResponseStatus.NOT_FOUND);
            return;
        }

        if (path.startsWith("/") && path.length() > 1) {
            path = path.substring(1);
        }

        JarEntry jarEntry = jarFile.getJarEntry(path);
        if (jarEntry == null) {
            responder.sendStatus(HttpResponseStatus.NOT_FOUND);
            return;
        }

        InputStream in = jarFile.getInputStream(jarEntry);
        if (in == null) {
            // path is directory
            responder.sendStatus(HttpResponseStatus.FORBIDDEN);
            return;
        }

        try {
            responder.sendByteArray(HttpResponseStatus.OK, ByteStreams.toByteArray(in),
                    ImmutableMultimap.of(HttpHeaders.Names.CONTENT_TYPE, mimeTypesMap.getContentType(path)));

        } finally {
            in.close();
        }
    } catch (Throwable t) {
        LOG.error("Got exception: ", t);
        responder.sendStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:com.palantir.atlasdb.keyvalue.partition.PartitionedBoundStore.java

private void putValue(long value) {
    kv.delete(TIMESTAMP_TABLE, ImmutableMultimap.of(TS_CELL, KV_TS));
    kv.put(TIMESTAMP_TABLE, ImmutableMap.of(TS_CELL, PtBytes.toBytes(value)), KV_TS);
}

From source file:co.cask.cdap.messaging.server.FetchHandler.java

@POST
@Path("poll")
public void poll(HttpRequest request, HttpResponder responder, @PathParam("namespace") String namespace,
        @PathParam("topic") String topic) throws Exception {

    TopicId topicId = new NamespaceId(namespace).topic(topic);

    // Currently only support avro
    if (!"avro/binary".equals(request.getHeader(HttpHeaders.Names.CONTENT_TYPE))) {
        throw new BadRequestException("Only avro/binary content type is supported.");
    }/*from   w  w  w.j  a v  a2  s  .  c  om*/

    // Decode the poll request
    Decoder decoder = DecoderFactory.get()
            .directBinaryDecoder(new ChannelBufferInputStream(request.getContent()), null);
    DatumReader<GenericRecord> datumReader = new GenericDatumReader<>(Schemas.V1.ConsumeRequest.SCHEMA);

    // Fetch the messages
    CloseableIterator<RawMessage> iterator = fetchMessages(datumReader.read(null, decoder), topicId);
    try {
        responder.sendContent(HttpResponseStatus.OK, new MessagesBodyProducer(iterator, messageChunkSize),
                ImmutableMultimap.of(HttpHeaders.Names.CONTENT_TYPE, "avro/binary"));
    } catch (Throwable t) {
        iterator.close();
        throw t;
    }
}

From source file:co.cask.cdap.internal.app.runtime.webapp.ExplodeJarHttpHandler.java

@GET
@Path("**")
public void serve(HttpRequest request, HttpResponder responder) {
    try {// w ww .j  av a 2 s  . c o  m

        String path = request.getUri();
        if (path == null) {
            responder.sendStatus(HttpResponseStatus.NOT_FOUND);
            return;
        }

        File file = new File(path);
        if (!file.getCanonicalPath().startsWith(cannonicalBaseDir)) {
            responder.sendStatus(HttpResponseStatus.NOT_FOUND);
            return;
        }

        if (!file.exists()) {
            responder.sendStatus(HttpResponseStatus.NOT_FOUND);
            return;
        }

        if (!file.isFile()) {
            responder.sendStatus(HttpResponseStatus.FORBIDDEN);
            return;
        }

        responder.sendFile(file, ImmutableMultimap.of(HttpHeaders.Names.CONTENT_TYPE,
                mimeTypesMap.getContentType(file.getAbsolutePath())));

    } catch (Throwable t) {
        LOG.error("Got exception: ", t);
        responder.sendStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.jboss.errai.demo.grocery.client.local.StoreWidget.java

@EventHandler
private void onClick(ClickEvent e) {
    toStorePage.go(ImmutableMultimap.of("id", String.valueOf(storeBinder.getModel().getId())));
}

From source file:io.wcm.caravan.pipeline.extensions.hal.crawler.HalCrawler.java

@Override
public Observable<JsonPipelineOutput> execute(JsonPipelineOutput previousStepOutput,
        JsonPipelineContext pipelineContext) {

    String currentUrl = getCurrentUrl(previousStepOutput);
    processedUrls.add(currentUrl);// w  w w  .  ja v  a  2 s  .c  o m
    JsonPipeline startingPipeline = pipelineContext.getFactory().createEmpty(pipelineContext.getProperties());

    HalResource currentHalResource = getCurrentHalResource(previousStepOutput, currentUrl);
    ListMultimap<String, Link> links = linkExtractor.extract(currentHalResource);

    return Observable.from(links.entries())
            // create pipeline action
            .map(entry -> {
                String relation = entry.getKey();
                Link link = entry.getValue();
                Map<String, Object> parameters = uriParametersProvider.getParameters(currentHalResource,
                        relation, link);
                LoadLink action = client.load(link, parameters);
                action.setHttpHeaders(ImmutableMultimap.of(HEADER_CRAWLER_RELATION, relation));
                if (cacheStrategy != null) {
                    action.setCacheStrategy(cacheStrategy);
                }
                return action;
            })
            // filter unique by URL
            .distinct(action -> action.getUrl())
            // filter already processed URLs
            .filter(action -> !startedUrls.contains(action.getUrl())
                    && !processedUrls.contains(action.getUrl()))
            // filter actions for stopped crawler
            .filter(action -> !stopCriterion.isStopRequested())
            // add URL to processed and create pipeline
            .map(action -> {
                startedUrls.add(action.getUrl());
                return startingPipeline.applyAction(action);
            })
            // add this action to the pipeline
            .map(pipeline -> pipeline.applyAction(this))
            // get pipeline outputs
            .flatMap(JsonPipeline::getOutput)
            // get pipeline outputs list
            .toList()
            // process output
            .map(linkOutputs -> outputProcessor.process(previousStepOutput, linkOutputs));

}

From source file:com.palantir.atlasdb.keyvalue.impl.KVTableMappingService.java

@Override
public void removeTable(TableReference tableRef) {
    Cell key = Cell.create(getBytesForTableRef(tableRef), AtlasDbConstants.NAMESPACE_SHORT_COLUMN_BYTES);
    if (kv.getAllTableNames().contains(AtlasDbConstants.NAMESPACE_TABLE)) {
        kv.delete(AtlasDbConstants.NAMESPACE_TABLE, ImmutableMultimap.of(key, 0L));
    }// w  w w . j ava2s .  co  m
    // Need to invalidate the table ref in case we end up re-creating the same table
    // again. Frequently when we drop one table we end up dropping a bunch of tables,
    // so just invalidate everything.
    tableMap.set(HashBiMap.<TableReference, String>create());
}

From source file:co.cask.cdap.data.stream.service.StreamFetchHandler.java

/**
 * Handler for the HTTP API {@code /streams/[stream_name]/events?start=[start_ts]&end=[end_ts]&limit=[event_limit]}
 * <p>/* ww w .ja v  a  2 s .  c o m*/
 * Responds with:
 * <ul>
 * <li>404 if stream does not exist</li>
 * <li>204 if no event in the given start/end time range exists</li>
 * <li>200 if there is are one or more events</li>
 * </ul>
 * </p>
 * <p>
 * Response body is a JSON array of the StreamEvent object.
 * </p>
 *
 * @see StreamEventTypeAdapter StreamEventTypeAdapter for the format of the StreamEvent object
 */
@GET
@Path("/{stream}/events")
public void fetch(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId,
        @PathParam("stream") String stream, @QueryParam("start") @DefaultValue("0") String start,
        @QueryParam("end") @DefaultValue("9223372036854775807") String end,
        @QueryParam("limit") @DefaultValue("2147483647") int limit) throws Exception {
    long startTime = TimeMathParser.parseTime(start, TimeUnit.MILLISECONDS);
    long endTime = TimeMathParser.parseTime(end, TimeUnit.MILLISECONDS);

    Id.Stream streamId = Id.Stream.from(namespaceId, stream);
    if (!verifyGetEventsRequest(streamId, startTime, endTime, limit, responder)) {
        return;
    }

    StreamConfig streamConfig = streamAdmin.getConfig(streamId);
    long now = System.currentTimeMillis();
    startTime = Math.max(startTime, now - streamConfig.getTTL());
    endTime = Math.min(endTime, now);

    // Create the stream event reader
    try (FileReader<StreamEventOffset, Iterable<StreamFileOffset>> reader = createReader(streamConfig,
            startTime)) {
        TimeRangeReadFilter readFilter = new TimeRangeReadFilter(startTime, endTime);
        List<StreamEvent> events = Lists.newArrayListWithCapacity(100);

        // Reads the first batch of events from the stream.
        int eventsRead = readEvents(reader, events, limit, readFilter);

        // If empty already, return 204 no content
        if (eventsRead <= 0) {
            responder.sendStatus(HttpResponseStatus.NO_CONTENT);
            return;
        }

        // Send with chunk response, as we don't want to buffer all events in memory to determine the content-length.
        ChunkResponder chunkResponder = responder.sendChunkStart(HttpResponseStatus.OK,
                ImmutableMultimap.of(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=utf-8"));
        ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
        JsonWriter jsonWriter = new JsonWriter(
                new OutputStreamWriter(new ChannelBufferOutputStream(buffer), Charsets.UTF_8));
        // Response is an array of stream event
        jsonWriter.beginArray();
        while (limit > 0 && eventsRead > 0) {
            limit -= eventsRead;

            for (StreamEvent event : events) {
                GSON.toJson(event, StreamEvent.class, jsonWriter);
                jsonWriter.flush();

                // If exceeded chunk size limit, send a new chunk.
                if (buffer.readableBytes() >= CHUNK_SIZE) {
                    // If the connect is closed, sendChunk will throw IOException.
                    // No need to handle the exception as it will just propagated back to the netty-http library
                    // and it will handle it.
                    // Need to copy the buffer because the buffer will get reused and send chunk is an async operation
                    chunkResponder.sendChunk(buffer.copy());
                    buffer.clear();
                }
            }
            events.clear();

            if (limit > 0) {
                eventsRead = readEvents(reader, events, limit, readFilter);
            }
        }
        jsonWriter.endArray();
        jsonWriter.close();

        // Send the last chunk that still has data
        if (buffer.readable()) {
            // No need to copy the last chunk, since the buffer will not be reused
            chunkResponder.sendChunk(buffer);
        }
        Closeables.closeQuietly(chunkResponder);
    }
}