Search in sources :

Example 1 with UriBuilder

use of javax.ws.rs.core.UriBuilder in project hbase by apache.

the class ScannerResource method update.

Response update(final ScannerModel model, final boolean replace, final UriInfo uriInfo) {
    servlet.getMetrics().incrementRequests(1);
    if (servlet.isReadOnly()) {
        return Response.status(Response.Status.FORBIDDEN).type(MIMETYPE_TEXT).entity("Forbidden" + CRLF).build();
    }
    byte[] endRow = model.hasEndRow() ? model.getEndRow() : null;
    RowSpec spec = null;
    if (model.getLabels() != null) {
        spec = new RowSpec(model.getStartRow(), endRow, model.getColumns(), model.getStartTime(), model.getEndTime(), model.getMaxVersions(), model.getLabels());
    } else {
        spec = new RowSpec(model.getStartRow(), endRow, model.getColumns(), model.getStartTime(), model.getEndTime(), model.getMaxVersions());
    }
    try {
        Filter filter = ScannerResultGenerator.buildFilterFromModel(model);
        String tableName = tableResource.getName();
        ScannerResultGenerator gen = new ScannerResultGenerator(tableName, spec, filter, model.getCaching(), model.getCacheBlocks());
        String id = gen.getID();
        ScannerInstanceResource instance = new ScannerInstanceResource(tableName, id, gen, model.getBatch());
        scanners.put(id, instance);
        if (LOG.isTraceEnabled()) {
            LOG.trace("new scanner: " + id);
        }
        UriBuilder builder = uriInfo.getAbsolutePathBuilder();
        URI uri = builder.path(id).build();
        servlet.getMetrics().incrementSucessfulPutRequests(1);
        return Response.created(uri).build();
    } catch (Exception e) {
        servlet.getMetrics().incrementFailedPutRequests(1);
        if (e instanceof TableNotFoundException) {
            return Response.status(Response.Status.NOT_FOUND).type(MIMETYPE_TEXT).entity("Not found" + CRLF).build();
        } else if (e instanceof RuntimeException) {
            return Response.status(Response.Status.BAD_REQUEST).type(MIMETYPE_TEXT).entity("Bad request" + CRLF).build();
        }
        return Response.status(Response.Status.SERVICE_UNAVAILABLE).type(MIMETYPE_TEXT).entity("Unavailable" + CRLF).build();
    }
}
Also used : TableNotFoundException(org.apache.hadoop.hbase.TableNotFoundException) Filter(org.apache.hadoop.hbase.filter.Filter) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) TableNotFoundException(org.apache.hadoop.hbase.TableNotFoundException) IOException(java.io.IOException)

Example 2 with UriBuilder

use of javax.ws.rs.core.UriBuilder in project hadoop by apache.

the class WebAppProxyServlet method buildTrackingUrl.

/**
   * Return a URL based on the {@code trackingUri} that includes the
   * user-provided path and query parameters.
   *
   * @param trackingUri the base tracking URI
   * @param req the service request
   * @param rest the user-provided path
   * @return the new tracking URI
   * @throws UriBuilderException if there's an error building the URL
   */
private URI buildTrackingUrl(URI trackingUri, final HttpServletRequest req, String rest) throws UriBuilderException {
    UriBuilder builder = UriBuilder.fromUri(trackingUri);
    String queryString = req.getQueryString();
    if (queryString != null) {
        List<NameValuePair> queryPairs = URLEncodedUtils.parse(queryString, null);
        for (NameValuePair pair : queryPairs) {
            builder.queryParam(pair.getName(), pair.getValue());
        }
    }
    return builder.path(rest).build();
}
Also used : NameValuePair(org.apache.http.NameValuePair) UriBuilder(javax.ws.rs.core.UriBuilder)

Example 3 with UriBuilder

use of javax.ws.rs.core.UriBuilder in project che by eclipse.

the class Service method generateLinkForMethod.

private Link generateLinkForMethod(UriInfo uriInfo, String linkRel, Method method, Object... pathParameters) {
    String httpMethod = null;
    final HttpMethod httpMethodAnnotation = getMetaAnnotation(method, HttpMethod.class);
    if (httpMethodAnnotation != null) {
        httpMethod = httpMethodAnnotation.value();
    }
    if (httpMethod == null) {
        throw new IllegalArgumentException(format("Method '%s' has not any HTTP method annotation and may not be used to produce link.", method.getName()));
    }
    final Consumes consumes = getAnnotation(method, Consumes.class);
    final Produces produces = getAnnotation(method, Produces.class);
    final UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder();
    final LinkedList<String> matchedURIs = new LinkedList<>(uriInfo.getMatchedURIs());
    // Get path to the root resource.
    if (uriInfo.getMatchedResources().size() < matchedURIs.size()) {
        matchedURIs.remove();
    }
    while (!matchedURIs.isEmpty()) {
        baseUriBuilder.path(matchedURIs.pollLast());
    }
    final Path path = method.getAnnotation(Path.class);
    if (path != null) {
        baseUriBuilder.path(path.value());
    }
    final Link link = DtoFactory.getInstance().createDto(Link.class).withRel(linkRel).withHref(baseUriBuilder.build(pathParameters).toString()).withMethod(httpMethod);
    if (consumes != null) {
        link.setConsumes(consumes.value()[0]);
    }
    if (produces != null) {
        link.setProduces(produces.value()[0]);
    }
    Class<?>[] parameterClasses = method.getParameterTypes();
    if (parameterClasses.length > 0) {
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < parameterClasses.length; i++) {
            if (annotations[i].length > 0) {
                boolean isBodyParameter = false;
                QueryParam queryParam = null;
                Description description = null;
                Required required = null;
                Valid valid = null;
                DefaultValue defaultValue = null;
                for (int j = 0; j < annotations[i].length; j++) {
                    Annotation annotation = annotations[i][j];
                    isBodyParameter |= !JAX_RS_ANNOTATIONS.contains(annotation.annotationType().getName());
                    Class<?> annotationType = annotation.annotationType();
                    if (annotationType == QueryParam.class) {
                        queryParam = (QueryParam) annotation;
                    } else if (annotationType == Description.class) {
                        description = (Description) annotation;
                    } else if (annotationType == Required.class) {
                        required = (Required) annotation;
                    } else if (annotationType == Valid.class) {
                        valid = (Valid) annotation;
                    } else if (annotationType == DefaultValue.class) {
                        defaultValue = (DefaultValue) annotation;
                    }
                }
                if (queryParam != null) {
                    LinkParameter parameter = DtoFactory.getInstance().createDto(LinkParameter.class).withName(queryParam.value()).withRequired(required != null).withType(getParameterType(parameterClasses[i]));
                    if (defaultValue != null) {
                        parameter.setDefaultValue(defaultValue.value());
                    }
                    if (description != null) {
                        parameter.setDescription(description.value());
                    }
                    if (valid != null) {
                        parameter.setValid(Arrays.asList(valid.value()));
                    }
                    link.getParameters().add(parameter);
                } else if (isBodyParameter) {
                    if (description != null) {
                        link.setRequestBody(DtoFactory.getInstance().createDto(RequestBodyDescriptor.class).withDescription(description.value()));
                    }
                }
            }
        }
    }
    return link;
}
Also used : Path(javax.ws.rs.Path) RequestBodyDescriptor(org.eclipse.che.api.core.rest.shared.dto.RequestBodyDescriptor) Description(org.eclipse.che.api.core.rest.annotations.Description) LinkParameter(org.eclipse.che.api.core.rest.shared.dto.LinkParameter) LinkedList(java.util.LinkedList) Annotation(java.lang.annotation.Annotation) DefaultValue(javax.ws.rs.DefaultValue) Required(org.eclipse.che.api.core.rest.annotations.Required) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) QueryParam(javax.ws.rs.QueryParam) Valid(org.eclipse.che.api.core.rest.annotations.Valid) UriBuilder(javax.ws.rs.core.UriBuilder) HttpMethod(javax.ws.rs.HttpMethod) Link(org.eclipse.che.api.core.rest.shared.dto.Link) GenerateLink(org.eclipse.che.api.core.rest.annotations.GenerateLink)

Example 4 with UriBuilder

use of javax.ws.rs.core.UriBuilder in project che by eclipse.

the class PagingUtil method createLinkHeader.

/**
     * Generates link header value from the page object and base uri.
     * <a href="https://tools.ietf.org/html/rfc5988">The Link header spec</a>
     *
     * @param page
     *         the page used to generate link
     * @param uri
     *         the uri which is used for adding {@code skipCount} & {@code maxItems} query parameters
     * @return 'Link' header value
     * @throws NullPointerException
     *         when either {@code page} or {@code uri} is null
     */
public static String createLinkHeader(Page<?> page, URI uri) {
    requireNonNull(page, "Required non-null page");
    requireNonNull(uri, "Required non-null uri");
    final ArrayList<Pair<String, Page.PageRef>> pageRefs = new ArrayList<>(4);
    pageRefs.add(Pair.of("first", page.getFirstPageRef()));
    pageRefs.add(Pair.of("last", page.getLastPageRef()));
    if (page.hasPreviousPage()) {
        pageRefs.add(Pair.of("prev", page.getPreviousPageRef()));
    }
    if (page.hasNextPage()) {
        pageRefs.add(Pair.of("next", page.getNextPageRef()));
    }
    final UriBuilder ub = UriBuilder.fromUri(uri);
    return pageRefs.stream().map(refPair -> format("<%s>; rel=\"%s\"", ub.clone().replaceQueryParam("skipCount", refPair.second.getItemsBefore()).replaceQueryParam("maxItems", refPair.second.getPageSize()).build().toString(), refPair.first)).collect(joining(LINK_HEADER_SEPARATOR));
}
Also used : Collections.emptyMap(java.util.Collections.emptyMap) Page(org.eclipse.che.api.core.Page) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) HashMap(java.util.HashMap) Pair(org.eclipse.che.commons.lang.Pair) String.format(java.lang.String.format) Collectors.joining(java.util.stream.Collectors.joining) ArrayList(java.util.ArrayList) Matcher(java.util.regex.Matcher) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) Pattern(java.util.regex.Pattern) ArrayList(java.util.ArrayList) Page(org.eclipse.che.api.core.Page) UriBuilder(javax.ws.rs.core.UriBuilder) Pair(org.eclipse.che.commons.lang.Pair)

Example 5 with UriBuilder

use of javax.ws.rs.core.UriBuilder in project che by eclipse.

the class SshMachineInstance method getRuntime.

public MachineRuntimeInfoImpl getRuntime() {
    // lazy initialization
    if (machineRuntime == null) {
        synchronized (this) {
            if (machineRuntime == null) {
                UriBuilder uriBuilder = UriBuilder.fromUri("http://" + sshClient.getHost());
                final Map<String, ServerImpl> servers = new HashMap<>();
                for (ServerConf serverConf : machinesServers) {
                    servers.put(serverConf.getPort(), serverConfToServer(serverConf, uriBuilder.clone()));
                }
                machineRuntime = new MachineRuntimeInfoImpl(emptyMap(), emptyMap(), servers);
            }
        }
    // todo get env from client
    }
    return machineRuntime;
}
Also used : MachineRuntimeInfoImpl(org.eclipse.che.api.machine.server.model.impl.MachineRuntimeInfoImpl) ServerConf(org.eclipse.che.api.core.model.machine.ServerConf) ServerImpl(org.eclipse.che.api.machine.server.model.impl.ServerImpl) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) UriBuilder(javax.ws.rs.core.UriBuilder)

Aggregations

UriBuilder (javax.ws.rs.core.UriBuilder)123 URI (java.net.URI)45 Test (org.junit.Test)42 HashMap (java.util.HashMap)15 Consumes (javax.ws.rs.Consumes)15 Link (org.eclipse.che.api.core.rest.shared.dto.Link)15 PUT (javax.ws.rs.PUT)11 IOException (java.io.IOException)10 Path (javax.ws.rs.Path)10 ArrayList (java.util.ArrayList)8 Produces (javax.ws.rs.Produces)8 LinksHelper.createLink (org.eclipse.che.api.core.util.LinksHelper.createLink)8 GET (javax.ws.rs.GET)7 URL (java.net.URL)6 ServerException (org.eclipse.che.api.core.ServerException)6 POST (javax.ws.rs.POST)5 ApiException (org.eclipse.che.api.core.ApiException)4 WorkspaceService (org.eclipse.che.api.workspace.server.WorkspaceService)4 ExternalTestContainerFactory (org.glassfish.jersey.test.external.ExternalTestContainerFactory)4 ExceptionMetered (com.codahale.metrics.annotation.ExceptionMetered)3