Search in sources :

Example 66 with UriBuilder

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

the class RestServer method advertisedUrl.

/**
     * Get the URL to advertise to other workers and clients. This uses the default connector from the embedded Jetty
     * server, unless overrides for advertised hostname and/or port are provided via configs.
     */
public URI advertisedUrl() {
    UriBuilder builder = UriBuilder.fromUri(jettyServer.getURI());
    String advertisedHostname = config.getString(WorkerConfig.REST_ADVERTISED_HOST_NAME_CONFIG);
    if (advertisedHostname != null && !advertisedHostname.isEmpty())
        builder.host(advertisedHostname);
    Integer advertisedPort = config.getInt(WorkerConfig.REST_ADVERTISED_PORT_CONFIG);
    if (advertisedPort != null)
        builder.port(advertisedPort);
    else
        builder.port(config.getInt(WorkerConfig.REST_PORT_CONFIG));
    return builder.build();
}
Also used : UriBuilder(javax.ws.rs.core.UriBuilder)

Example 67 with UriBuilder

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

the class HDFSCommand method runCommand.

// The operator that runs all commands
public String runCommand(Op op, String path, Arg[] args) throws Exception {
    // Check arguments
    String error = checkArgs(op, path, args);
    if (error != null) {
        logger.error("Bad arguments to command: " + error);
        return "ERROR: BAD ARGS";
    }
    // Build URI
    UriBuilder builder = UriBuilder.fromPath(url).path(path).queryParam("op", op.op);
    if (args != null) {
        for (Arg a : args) {
            builder = builder.queryParam(a.key, a.value);
        }
    }
    java.net.URI uri = builder.build();
    // Connect and get response string
    URL hdfsUrl = uri.toURL();
    HttpURLConnection con = (HttpURLConnection) hdfsUrl.openConnection();
    if (op.cmd == HttpType.GET) {
        con.setRequestMethod("GET");
        int responseCode = con.getResponseCode();
        logger.info("Sending 'GET' request to URL : " + hdfsUrl);
        logger.info("Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        int i = 0;
        while ((inputLine = in.readLine()) != null) {
            if (inputLine.length() < maxLength)
                response.append(inputLine);
            i++;
            if (i >= maxLength)
                break;
        }
        in.close();
        return response.toString();
    }
    return null;
}
Also used : HttpURLConnection(java.net.HttpURLConnection) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) UriBuilder(javax.ws.rs.core.UriBuilder) URL(java.net.URL)

Example 68 with UriBuilder

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

the class DefaultHttpJsonRequest method doRequest.

/**
     * Makes this request using {@link HttpURLConnection}.
     *
     * <p>Uses {@link HttpHeaders#AUTHORIZATION} header with value from {@link EnvironmentContext}.
     * <br>uses {@link HttpHeaders#ACCEPT} header with "application/json" value.
     * <br>Encodes query parameters in "UTF-8".
     *
     * @param timeout
     *         request timeout, used only if it is greater than 0
     * @param url
     *         request url
     * @param method
     *         request method
     * @param body
     *         request body, must be instance of {@link JsonSerializable}
     * @param parameters
     *         query parameters, may be null
     * @param authorizationHeaderValue
     *         value of authorization header, may be null
     * @return response to this request
     * @throws IOException
     *         when connection content type is not "application/json"
     * @throws ServerException
     *         when response code is 500 or it is different from 400, 401, 403, 404, 409
     * @throws ForbiddenException
     *         when response code is 403
     * @throws NotFoundException
     *         when response code is 404
     * @throws UnauthorizedException
     *         when response code is 401
     * @throws ConflictException
     *         when response code is 409
     * @throws BadRequestException
     *         when response code is 400
     */
protected DefaultHttpJsonResponse doRequest(int timeout, String url, String method, Object body, List<Pair<String, ?>> parameters, String authorizationHeaderValue) throws IOException, ServerException, ForbiddenException, NotFoundException, UnauthorizedException, ConflictException, BadRequestException {
    final String authToken = EnvironmentContext.getCurrent().getSubject().getToken();
    final boolean hasQueryParams = parameters != null && !parameters.isEmpty();
    if (hasQueryParams || authToken != null) {
        final UriBuilder ub = UriBuilder.fromUri(url);
        //remove sensitive information from url.
        ub.replaceQueryParam("token", EMPTY_ARRAY);
        if (hasQueryParams) {
            for (Pair<String, ?> parameter : parameters) {
                ub.queryParam(parameter.first, parameter.second);
            }
        }
        url = ub.build().toString();
    }
    final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(timeout > 0 ? timeout : 60000);
    conn.setReadTimeout(timeout > 0 ? timeout : 60000);
    try {
        conn.setRequestMethod(method);
        //drop a hint for server side that we want to receive application/json
        conn.addRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
        if (!isNullOrEmpty(authorizationHeaderValue)) {
            conn.setRequestProperty(HttpHeaders.AUTHORIZATION, authorizationHeaderValue);
        } else if (authToken != null) {
            conn.setRequestProperty(HttpHeaders.AUTHORIZATION, authToken);
        }
        if (body != null) {
            conn.addRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
            conn.setDoOutput(true);
            if (HttpMethod.DELETE.equals(method)) {
                //to avoid jdk bug described here http://bugs.java.com/view_bug.do?bug_id=7157360
                conn.setRequestMethod(HttpMethod.POST);
                conn.setRequestProperty("X-HTTP-Method-Override", HttpMethod.DELETE);
            }
            try (OutputStream output = conn.getOutputStream()) {
                output.write(DtoFactory.getInstance().toJson(body).getBytes());
            }
        }
        final int responseCode = conn.getResponseCode();
        if ((responseCode / 100) != 2) {
            InputStream in = conn.getErrorStream();
            if (in == null) {
                in = conn.getInputStream();
            }
            final String str;
            try (Reader reader = new InputStreamReader(in)) {
                str = CharStreams.toString(reader);
            }
            final String contentType = conn.getContentType();
            if (contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON)) {
                final ServiceError serviceError = DtoFactory.getInstance().createDtoFromJson(str, ServiceError.class);
                if (serviceError.getMessage() != null) {
                    if (responseCode == Response.Status.FORBIDDEN.getStatusCode()) {
                        throw new ForbiddenException(serviceError);
                    } else if (responseCode == Response.Status.NOT_FOUND.getStatusCode()) {
                        throw new NotFoundException(serviceError);
                    } else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
                        throw new UnauthorizedException(serviceError);
                    } else if (responseCode == Response.Status.CONFLICT.getStatusCode()) {
                        throw new ConflictException(serviceError);
                    } else if (responseCode == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
                        throw new ServerException(serviceError);
                    } else if (responseCode == Response.Status.BAD_REQUEST.getStatusCode()) {
                        throw new BadRequestException(serviceError);
                    }
                    throw new ServerException(serviceError);
                }
            }
            // Can't parse content as json or content has format other we expect for error.
            throw new IOException(String.format("Failed access: %s, method: %s, response code: %d, message: %s", UriBuilder.fromUri(url).replaceQuery("token").build(), method, responseCode, str));
        }
        final String contentType = conn.getContentType();
        if (contentType != null && !contentType.startsWith(MediaType.APPLICATION_JSON)) {
            throw new IOException(conn.getResponseMessage());
        }
        try (Reader reader = new InputStreamReader(conn.getInputStream())) {
            return new DefaultHttpJsonResponse(CharStreams.toString(reader), responseCode);
        }
    } finally {
        conn.disconnect();
    }
}
Also used : ServiceError(org.eclipse.che.api.core.rest.shared.dto.ServiceError) ForbiddenException(org.eclipse.che.api.core.ForbiddenException) ServerException(org.eclipse.che.api.core.ServerException) InputStreamReader(java.io.InputStreamReader) ConflictException(org.eclipse.che.api.core.ConflictException) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) NotFoundException(org.eclipse.che.api.core.NotFoundException) IOException(java.io.IOException) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) BadRequestException(org.eclipse.che.api.core.BadRequestException) UriBuilder(javax.ws.rs.core.UriBuilder)

Example 69 with UriBuilder

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

the class RecipeDownloader method getRecipe.

/**
     * Downloads recipe by location.
     *
     * @param location
     *         location of recipe
     * @return recipe with set content and type
     * @throws ServerException
     *         if any error occurs
     */
public String getRecipe(String location) throws ServerException {
    URL recipeUrl;
    File file = null;
    try {
        UriBuilder targetUriBuilder = UriBuilder.fromUri(location);
        // add user token to be able to download user's private recipe
        final URI recipeUri = targetUriBuilder.build();
        if (!recipeUri.isAbsolute() && recipeUri.getHost() == null) {
            targetUriBuilder.scheme(apiEndpoint.getScheme()).host(apiEndpoint.getHost()).port(apiEndpoint.getPort()).replacePath(apiEndpoint.getPath() + location);
            if (EnvironmentContext.getCurrent().getSubject().getToken() != null) {
                targetUriBuilder.queryParam("token", EnvironmentContext.getCurrent().getSubject().getToken());
            }
        }
        recipeUrl = targetUriBuilder.build().toURL();
        file = IoUtil.downloadFileWithRedirect(null, "recipe", null, recipeUrl);
        return IoUtil.readAndCloseQuietly(new FileInputStream(file));
    } catch (IOException | IllegalArgumentException | UriBuilderException e) {
        throw new MachineException(format("Failed to download recipe %s. Error: %s", location, e.getLocalizedMessage()));
    } finally {
        if (file != null && !file.delete()) {
            LOG.error(String.format("Removal of recipe file %s failed.", file.getAbsolutePath()));
        }
    }
}
Also used : MachineException(org.eclipse.che.api.machine.server.exception.MachineException) IOException(java.io.IOException) UriBuilderException(javax.ws.rs.core.UriBuilderException) UriBuilder(javax.ws.rs.core.UriBuilder) File(java.io.File) URI(java.net.URI) URL(java.net.URL) FileInputStream(java.io.FileInputStream)

Example 70 with UriBuilder

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

the class RecipeDownloader method getRecipe.

/**
     * Downloads recipe by location from {@link MachineSource#getLocation()}.
     *
     * @param machineConfig
     *         config used to get recipe location
     * @return recipe with set content and type
     * @throws MachineException
     *         if any error occurs
     */
public RecipeImpl getRecipe(MachineConfig machineConfig) throws MachineException {
    URL recipeUrl;
    File file = null;
    final String location = machineConfig.getSource().getLocation();
    try {
        UriBuilder targetUriBuilder = UriBuilder.fromUri(location);
        // add user token to be able to download user's private recipe
        final URI recipeUri = targetUriBuilder.build();
        if (!recipeUri.isAbsolute() && recipeUri.getHost() == null) {
            targetUriBuilder.scheme(apiEndpoint.getScheme()).host(apiEndpoint.getHost()).port(apiEndpoint.getPort()).replacePath(apiEndpoint.getPath() + location);
            if (EnvironmentContext.getCurrent().getSubject().getToken() != null) {
                targetUriBuilder.queryParam("token", EnvironmentContext.getCurrent().getSubject().getToken());
            }
        }
        recipeUrl = targetUriBuilder.build().toURL();
        file = IoUtil.downloadFileWithRedirect(null, "recipe", null, recipeUrl);
        return new RecipeImpl().withType(machineConfig.getSource().getType()).withScript(IoUtil.readAndCloseQuietly(new FileInputStream(file)));
    } catch (IOException | IllegalArgumentException e) {
        throw new MachineException(format("Failed to download recipe for machine %s. Recipe url %s. Error: %s", machineConfig.getName(), location, e.getLocalizedMessage()));
    } finally {
        if (file != null && !file.delete()) {
            LOG.error(String.format("Removal of recipe file %s failed.", file.getAbsolutePath()));
        }
    }
}
Also used : RecipeImpl(org.eclipse.che.api.machine.server.recipe.RecipeImpl) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) IOException(java.io.IOException) UriBuilder(javax.ws.rs.core.UriBuilder) File(java.io.File) URI(java.net.URI) URL(java.net.URL) FileInputStream(java.io.FileInputStream)

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