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:co.cask.cdap.gateway.handlers.AppLifecycleHttpHandler.java

private BodyConsumer deployApplication(final HttpResponder responder, final String namespaceId,
        final String appId, final String archiveName, final String configString) throws IOException {
    Id.Namespace namespace = Id.Namespace.from(namespaceId);
    if (!namespaceAdmin.hasNamespace(namespace)) {
        LOG.warn("Namespace '{}' not found.", namespaceId);
        responder.sendString(HttpResponseStatus.NOT_FOUND,
                String.format("Deploy failed - namespace '%s' not found.", namespaceId));
        return null;
    }//w ww  .  j av a 2 s  . c om

    Location namespaceHomeLocation = namespacedLocationFactory.get(namespace);
    if (!namespaceHomeLocation.exists()) {
        String msg = String.format("Home directory %s for namespace %s not found",
                namespaceHomeLocation.toURI().getPath(), namespaceId);
        LOG.error(msg);
        responder.sendString(HttpResponseStatus.NOT_FOUND, msg);
        return null;
    }

    if (archiveName == null || archiveName.isEmpty()) {
        responder.sendString(HttpResponseStatus.BAD_REQUEST, ARCHIVE_NAME_HEADER + " header not present",
                ImmutableMultimap.of(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE));
        return null;
    }

    // Store uploaded content to a local temp file
    String namespacesDir = configuration.get(Constants.Namespace.NAMESPACES_DIR);
    File localDataDir = new File(configuration.get(Constants.CFG_LOCAL_DATA_DIR));
    File namespaceBase = new File(localDataDir, namespacesDir);
    File tempDir = new File(new File(namespaceBase, namespaceId),
            configuration.get(Constants.AppFabric.TEMP_DIR)).getAbsoluteFile();
    if (!DirUtils.mkdirs(tempDir)) {
        throw new IOException("Could not create temporary directory at: " + tempDir);
    }

    String appFabricDir = configuration.get(Constants.AppFabric.OUTPUT_DIR);
    // note: cannot create an appId subdirectory under the namespace directory here because appId could be null here
    final Location archive = namespaceHomeLocation.append(appFabricDir).append(Constants.ARCHIVE_DIR)
            .append(archiveName);

    return new AbstractBodyConsumer(File.createTempFile("app-", ".jar", tempDir)) {

        @Override
        protected void onFinish(HttpResponder responder, File uploadedFile) {
            try {
                DeploymentInfo deploymentInfo = new DeploymentInfo(uploadedFile, archive, configString);
                deploy(namespaceId, appId, deploymentInfo);
                responder.sendString(HttpResponseStatus.OK, "Deploy Complete");
            } catch (Exception e) {
                LOG.error("Deploy failure", e);
                responder.sendString(HttpResponseStatus.BAD_REQUEST, e.getMessage());
            }
        }
    };
}

From source file:com.spotify.helios.client.HeliosClient.java

/**
 * Returns a list of all hosts registered in the Helios cluster whose name matches the given
 * pattern.//w  w  w  .  j a v  a2s .co m
 */
public ListenableFuture<List<String>> listHosts(final String namePattern) {
    return listHosts(ImmutableMultimap.of("namePattern", namePattern));
}

From source file:org.sosy_lab.cpachecker.util.LoopStructure.java

/**
 * Gets the loop structure of a control flow automaton with one single loop.
 * Do not call this method outside of the frontend,
 * use {@link org.sosy_lab.cpachecker.cfa.CFA#getLoopStructure()} instead.
 * @param pSingleLoopHead the loop head of the single loop.
 * @return the loop structure of the control flow automaton.
 *//*from   ww w . j a v a  2s. c o  m*/
public static LoopStructure getLoopStructureForSingleLoop(CFANode pSingleLoopHead) throws InterruptedException {
    Predicate<CFAEdge> noFunctionReturnEdge = not(edgeHasType(FunctionReturnEdge));

    // First, find all nodes reachable via the loop head
    Deque<CFANode> waitlist = new ArrayDeque<>();
    Set<CFANode> reachableSuccessors = new HashSet<>();
    Set<CFANode> visited = new HashSet<>();
    waitlist.push(pSingleLoopHead);
    boolean firstIteration = true;
    while (!waitlist.isEmpty()) {
        CFANode current = waitlist.pop();
        for (CFAEdge leavingEdge : CFAUtils.allLeavingEdges(current).filter(noFunctionReturnEdge)) {
            CFANode successor = leavingEdge.getSuccessor();
            if (visited.add(successor)) {
                waitlist.push(successor);
            }
        }
        if (firstIteration) {
            firstIteration = false;
        } else {
            reachableSuccessors.add(current);
        }
    }

    // If the loop head cannot reach itself, there is no loop
    if (!reachableSuccessors.contains(pSingleLoopHead)) {
        return new LoopStructure(ImmutableMultimap.<String, Loop>of());
    }

    /*
     * Now, Find all loop nodes by checking which of the nodes reachable via
     * the loop head, the loop head itself is reachable from.
     */
    visited.clear();
    waitlist.offer(pSingleLoopHead);
    Set<CFANode> loopNodes = new HashSet<>();
    while (!waitlist.isEmpty()) {
        CFANode current = waitlist.poll();
        if (reachableSuccessors.contains(current)) {
            loopNodes.add(current);
            for (CFAEdge enteringEdge : CFAUtils.allEnteringEdges(current)) {
                CFANode predecessor = enteringEdge.getPredecessor();
                if (visited.add(predecessor)) {
                    waitlist.offer(predecessor);
                }
            }
        }
    }
    String loopFunction = pSingleLoopHead.getFunctionName();
    // A size of one means only the loop head is contained
    if (loopNodes.isEmpty() || loopNodes.size() == 1 && !pSingleLoopHead.hasEdgeTo(pSingleLoopHead)) {
        return new LoopStructure(ImmutableMultimap.<String, Loop>of());
    }

    return new LoopStructure(ImmutableMultimap.of(loopFunction, new Loop(pSingleLoopHead, loopNodes)));
}

From source file:com.google.api.explorer.client.history.JsonPrettifier.java

/**
 * Create a drop down menu that allows the user to navigate to compatible methods for the
 * specified resource./*from   w ww . jav  a 2  s  . c  om*/
 *
 * @param methods Methods for which to build the menu.
 * @param service Service to which the methods correspond.
 * @param objectToPackage Object which should be passed to the destination menus.
 * @param linkFactory Factory that will be used to create links.
 * @return A button that will show the menu that was generated or {@code null} if there are no
 *         compatible methods.
 */
private static PushButton createRequestMenu(final Collection<ApiMethod> methods, final ApiService service,
        DynamicJso objectToPackage, PrettifierLinkFactory linkFactory) {

    // Determine if a menu even needs to be generated.
    if (methods.isEmpty()) {
        return null;
    }

    // Create the parameters that will be passed to the destination menu.
    String resourceContents = new JSONObject(objectToPackage).toString();
    final Multimap<String, String> resourceParams = ImmutableMultimap.of(UrlBuilder.BODY_QUERY_PARAM_KEY,
            resourceContents);

    // Create the menu itself.
    FlowPanel menuContents = new FlowPanel();

    // Add a description of what the menu does.
    Label header = new Label("Use this resource in one of the following methods:");
    header.addStyleName(style.dropDownMenuItem());
    menuContents.add(header);

    // Add a menu item for each method.
    for (ApiMethod method : methods) {
        PushButton methodItem = new PushButton();
        methodItem.addStyleName(style.dropDownMenuItem());
        methodItem.addStyleName(style.selectableDropDownMenuItem());
        methodItem.setText(method.getId());
        menuContents.add(methodItem);

        // When clicked, Navigate to the menu item.
        UrlBuilder builder = new UrlBuilder();
        String newUrl = builder.addRootNavigationItem(RootNavigationItem.ALL_VERSIONS)
                .addService(service.getName(), service.getVersion()).addMethodName(method.getId())
                .addQueryParams(resourceParams).toString();
        methodItem.addClickHandler(linkFactory.generateMenuHandler(newUrl));
    }

    // Create the panel which will be disclosed.
    final PopupPanel popupMenu = new PopupPanel(/* auto hide */ true);
    popupMenu.setStyleName(style.dropDownMenuPopup());

    FocusPanel focusContents = new FocusPanel();
    focusContents.addMouseOutHandler(new MouseOutHandler() {
        @Override
        public void onMouseOut(MouseOutEvent event) {
            popupMenu.hide();
        }
    });
    focusContents.setWidget(menuContents);

    popupMenu.setWidget(focusContents);

    // Create the button which will disclose the menu.
    final PushButton menuButton = new PushButton(new Image(resources.downArrow()));
    menuButton.addStyleName(style.reusableResourceButton());

    menuButton.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            popupMenu.setPopupPositionAndShow(new PositionCallback() {
                @Override
                public void setPosition(int offsetWidth, int offsetHeight) {
                    popupMenu.setPopupPosition(
                            menuButton.getAbsoluteLeft() + menuButton.getOffsetWidth() - offsetWidth,
                            menuButton.getAbsoluteTop() + menuButton.getOffsetHeight());
                }
            });
        }
    });

    // Return only the button to the caller.
    return menuButton;
}

From source file:com.google.gerrit.httpd.restapi.RestApiServlet.java

static void replyText(@Nullable HttpServletRequest req, HttpServletResponse res, String text)
        throws IOException {
    if ((req == null || "GET".equals(req.getMethod())) && isMaybeHTML(text)) {
        replyJson(req, res, ImmutableMultimap.of("pp", "0"), new JsonPrimitive(text));
    } else {//from  w  w  w.ja  va2 s.c  o m
        if (!text.endsWith("\n")) {
            text += "\n";
        }
        replyBinaryResult(req, res, BinaryResult.create(text).setContentType("text/plain"));
    }
}

From source file:com.continuuity.weave.internal.appmaster.ApplicationMasterService.java

private RunnableContainerRequest createRunnableContainerRequest(final String runnableName) {
    // Find the current order of the given runnable in order to create a RunnableContainerRequest.
    WeaveSpecification.Order order = Iterables.find(weaveSpec.getOrders(),
            new Predicate<WeaveSpecification.Order>() {
                @Override//from  w  ww.  j a v  a  2  s .  c  o m
                public boolean apply(WeaveSpecification.Order input) {
                    return (input.getNames().contains(runnableName));
                }
            });

    RuntimeSpecification runtimeSpec = weaveSpec.getRunnables().get(runnableName);
    Resource capability = createCapability(runtimeSpec.getResourceSpecification());
    return new RunnableContainerRequest(order.getType(), ImmutableMultimap.of(capability, runtimeSpec));
}

From source file:co.cask.cdap.gateway.handlers.AppFabricHttpHandler.java

private void runnableSpecification(HttpRequest request, HttpResponder responder, final String appId,
        ProgramType runnableType, final String runnableId) {
    try {//from w  w  w  .j  a  v  a2s.c o m
        String accountId = getAuthenticatedAccountId(request);
        Id.Program id = Id.Program.from(accountId, appId, runnableId);
        String specification = getProgramSpecification(id, runnableType);
        if (specification == null || specification.isEmpty()) {
            responder.sendStatus(HttpResponseStatus.NOT_FOUND);
        } else {
            responder.sendByteArray(HttpResponseStatus.OK, specification.getBytes(Charsets.UTF_8),
                    ImmutableMultimap.of(HttpHeaders.Names.CONTENT_TYPE, "application/json"));
        }
    } catch (SecurityException e) {
        responder.sendStatus(HttpResponseStatus.UNAUTHORIZED);
    } catch (Throwable e) {
        LOG.error("Got exception:", e);
        responder.sendStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:co.cask.cdap.gateway.handlers.AppFabricHttpHandler.java

@GET
@Path("/apps/{app-id}/workflows/{workflow-name}/current")
public void workflowStatus(HttpRequest request, final HttpResponder responder,
        @PathParam("app-id") String appId, @PathParam("workflow-name") String workflowName) {

    try {//www  .ja v  a  2s.c o m
        String accountId = getAuthenticatedAccountId(request);
        workflowClient.getWorkflowStatus(accountId, appId, workflowName, new WorkflowClient.Callback() {
            @Override
            public void handle(WorkflowClient.Status status) {
                if (status.getCode() == WorkflowClient.Status.Code.NOT_FOUND) {
                    responder.sendStatus(HttpResponseStatus.NOT_FOUND);
                } else if (status.getCode() == WorkflowClient.Status.Code.OK) {
                    responder.sendByteArray(HttpResponseStatus.OK, status.getResult().getBytes(),
                            ImmutableMultimap.of(HttpHeaders.Names.CONTENT_TYPE,
                                    "application/json; charset=utf-8"));

                } else {
                    responder.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR, status.getResult());
                }
            }
        });
    } catch (SecurityException e) {
        responder.sendStatus(HttpResponseStatus.UNAUTHORIZED);
    } catch (Throwable e) {
        LOG.error("Caught exception", e);
        responder.sendStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:co.cask.cdap.gateway.handlers.AppFabricHttpHandler.java

private void getAppDetails(HttpRequest request, HttpResponder responder, String appid) {
    if (appid != null && appid.isEmpty()) {
        responder.sendString(HttpResponseStatus.BAD_REQUEST, "app-id is empty");
        return;/*ww w. jav a 2s  . com*/
    }

    try {
        String accountId = getAuthenticatedAccountId(request);
        Id.Account accId = Id.Account.from(accountId);
        List<ApplicationRecord> result = Lists.newArrayList();
        List<ApplicationSpecification> specList;
        if (appid == null) {
            specList = new ArrayList<ApplicationSpecification>(store.getAllApplications(accId));
        } else {
            ApplicationSpecification appSpec = store.getApplication(new Id.Application(accId, appid));
            if (appSpec == null) {
                responder.sendStatus(HttpResponseStatus.NOT_FOUND);
                return;
            }
            specList = Collections.singletonList(store.getApplication(new Id.Application(accId, appid)));
        }

        for (ApplicationSpecification appSpec : specList) {
            result.add(makeAppRecord(appSpec));
        }

        String json;
        if (appid == null) {
            json = GSON.toJson(result);
        } else {
            json = GSON.toJson(result.get(0));
        }

        responder.sendByteArray(HttpResponseStatus.OK, json.getBytes(Charsets.UTF_8),
                ImmutableMultimap.of(HttpHeaders.Names.CONTENT_TYPE, "application/json"));
    } catch (SecurityException e) {
        responder.sendStatus(HttpResponseStatus.UNAUTHORIZED);
    } catch (Throwable e) {
        LOG.error("Got exception : ", e);
        responder.sendStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:co.cask.cdap.gateway.handlers.AppFabricHttpHandler.java

private void programList(HttpRequest request, HttpResponder responder, ProgramType type, String appid) {
    if (appid != null && appid.isEmpty()) {
        responder.sendString(HttpResponseStatus.BAD_REQUEST, "app-id is null or empty");
        return;/*  w w  w.ja v a  2  s .  c  o  m*/
    }

    try {
        String accountId = getAuthenticatedAccountId(request);
        String list;
        if (appid == null) {
            Id.Account accId = Id.Account.from(accountId);
            list = listPrograms(accId, type);
        } else {
            Id.Application appId = Id.Application.from(accountId, appid);
            list = listProgramsByApp(appId, type);
        }

        if (list.isEmpty()) {
            responder.sendStatus(HttpResponseStatus.NOT_FOUND);
        } else {
            responder.sendByteArray(HttpResponseStatus.OK, list.getBytes(Charsets.UTF_8),
                    ImmutableMultimap.of(HttpHeaders.Names.CONTENT_TYPE, "application/json"));
        }
    } catch (SecurityException e) {
        responder.sendStatus(HttpResponseStatus.UNAUTHORIZED);
    } catch (Throwable e) {
        LOG.error("Got exception: ", e);
        responder.sendStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
}