Example usage for java.net HttpURLConnection HTTP_NO_CONTENT

List of usage examples for java.net HttpURLConnection HTTP_NO_CONTENT

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_NO_CONTENT.

Prototype

int HTTP_NO_CONTENT

To view the source code for java.net HttpURLConnection HTTP_NO_CONTENT.

Click Source Link

Document

HTTP Status-Code 204: No Content.

Usage

From source file:mobi.jenkinsci.alm.assembla.client.AssemblaClient.java

private String getData(final String dataSuffix, final boolean autoLogin) throws IOException {
    loginWhenNecessary(autoLogin);/*from ww  w .j  a v  a 2s.  co  m*/
    final HttpGet get = new HttpGet(getTargetUrl(dataSuffix));
    setRequestHeaders(get, autoLogin);

    try {
        final HttpResponse response = httpClient.execute(get, httpContext);
        switch (response.getStatusLine().getStatusCode()) {
        case HttpURLConnection.HTTP_OK:
            final ByteArrayOutputStream bout = new ByteArrayOutputStream();
            final InputStream in = response.getEntity().getContent();
            IOUtils.copy(in, bout);
            return new String(bout.toByteArray());

        case HttpURLConnection.HTTP_NO_CONTENT:
            return null;

        case HttpURLConnection.HTTP_NOT_FOUND:
            LOG.warn("Resource at " + dataSuffix + " was not found: returning NULL");
            return null;

        case HttpURLConnection.HTTP_UNAUTHORIZED:
            if (autoLogin) {
                loginRefresh();
                return getData(dataSuffix, false);
            }

        default:
            throw new IOException("Cannot GET " + dataSuffix + " from Assembla: " + response.getStatusLine());
        }
    } finally {
        get.releaseConnection();
    }
}

From source file:com.ontotext.s4.client.HttpClient.java

/**
* Read a response or error message from the given connection, and update the state of the given object.
*//*from w  ww .  j  av a2s  .co  m*/
private void readResponseOrErrorForUpdate(HttpURLConnection connection, Object responseObject)
        throws HttpClientException {

    InputStream stream = null;
    try {
        if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
            // successful response with no content
            return;
        }
        stream = connection.getInputStream();
        try {
            MAPPER.readerForUpdating(responseObject).readValue(stream);
        } finally {
            stream.close();
        }
    } catch (Exception e) {
        readError(connection);
    }
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

/**
 * Updates a tenant./*from   ww  w .j  a v  a  2s . co  m*/
 *
 * @param tenantId The identifier of the tenant.
 * @param tenantSpec The information to update the tenant with.
 * @return The outcome of the operation indicating success or failure.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
public TenantResult<JsonObject> update(final String tenantId, final JsonObject tenantSpec) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(tenantSpec);

    if (getConfig().isModificationEnabled()) {
        if (tenants.containsKey(tenantId)) {
            try {
                final TenantObject tenant = tenantSpec.mapTo(TenantObject.class);
                tenant.setTenantId(tenantId);
                final TenantObject conflictingTenant = getByCa(tenant.getTrustedCaSubjectDn());
                if (conflictingTenant != null && !tenantId.equals(conflictingTenant.getTenantId())) {
                    // we are trying to use the same CA as another tenant
                    return TenantResult.from(HttpURLConnection.HTTP_CONFLICT);
                } else {
                    tenants.put(tenantId, tenant);
                    dirty = true;
                    return TenantResult.from(HttpURLConnection.HTTP_NO_CONTENT);
                }
            } catch (IllegalArgumentException e) {
                return TenantResult.from(HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } else {
            return TenantResult.from(HttpURLConnection.HTTP_NOT_FOUND);
        }
    } else {
        return TenantResult.from(HttpURLConnection.HTTP_FORBIDDEN);
    }
}

From source file:org.openbaton.sdk.api.util.RestRequest.java

/**
 * Executes a http post with to a given url, while serializing the object content as json. The
 * type parameter specifies to which object type the post response should be mapped before
 * returning it. This can be useful if the method's return type is not the same as the type of the
 * object parameter.//from w w w. java2  s .c  o  m
 *
 * @param object the object content to be serialized as json
 * @param type the object type to which the response should be mapped
 * @return a string containing the response content
 */
public Serializable requestPost(final String id, final Serializable object, final Type type)
        throws SDKException {
    CloseableHttpResponse response = null;
    HttpPost httpPost = null;
    try {
        log.trace("Object is: " + object);
        String fileJSONNode = mapper.toJson(object);
        log.trace("sending: " + fileJSONNode.toString());
        log.debug("baseUrl: " + baseUrl);
        log.debug("id: " + baseUrl + "/" + id);

        try {
            checkToken();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new SDKException("Could not get token", e);
        }

        // call the api here
        log.debug("Executing post on: " + this.baseUrl + "/" + id);
        httpPost = new HttpPost(this.baseUrl + "/" + id);
        httpPost.setHeader(new BasicHeader("accept", "application/json"));
        httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
        httpPost.setHeader(new BasicHeader("project-id", projectId));
        if (token != null)
            httpPost.setHeader(new BasicHeader("authorization", bearerToken.replaceAll("\"", "")));
        httpPost.setEntity(new StringEntity(fileJSONNode));

        response = httpClient.execute(httpPost);

        // check response status
        checkStatus(response, HttpURLConnection.HTTP_CREATED);
        // return the response of the request
        String result = "";
        if (response.getEntity() != null)
            result = EntityUtils.toString(response.getEntity());

        if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) {
            JsonParser jsonParser = new JsonParser();
            JsonElement jsonElement = jsonParser.parse(result);
            result = mapper.toJson(jsonElement);
            log.trace("received: " + result);

            log.trace("Casting it into: " + type);
            return mapper.fromJson(result, type);
        }
        response.close();
        httpPost.releaseConnection();
        return null;
    } catch (IOException e) {
        // catch request exceptions here
        log.error(e.getMessage(), e);
        if (httpPost != null)
            httpPost.releaseConnection();
        throw new SDKException("Could not http-post or open the object properly", e);
    } catch (SDKException e) {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            token = null;
            if (httpPost != null)
                httpPost.releaseConnection();
            return requestPost(id);
        } else {
            if (httpPost != null)
                httpPost.releaseConnection();
            throw new SDKException("Status is " + response.getStatusLine().getStatusCode());
        }
    }
}

From source file:org.shredzone.flattr4j.connector.impl.FlattrConnection.java

/**
 * Assert that the HTTP result is OK, otherwise generate and throw an appropriate
 * {@link FlattrException}./*w  w  w.  ja va  2  s .com*/
 *
 * @param conn
 *            {@link HttpURLConnection} to assert
 * @return {@code true} if the status is OK and there is a content, {@code false} if
 *         the status is OK but there is no content. (If the status is not OK, an
 *         exception is thrown.)
 */
private boolean assertStatusOk(HttpURLConnection conn) throws FlattrException {
    String error = null, desc = null, httpStatus = null;

    try {
        int statusCode = conn.getResponseCode();

        if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) {
            return true;
        }
        if (statusCode == HttpURLConnection.HTTP_NO_CONTENT) {
            return false;
        }

        httpStatus = "HTTP " + statusCode + ": " + conn.getResponseMessage();

        JSONObject errorData = (JSONObject) new JSONTokener(readResponse(conn)).nextValue();
        LOG.verbose("<- ERROR {0}: {1}", statusCode, errorData);

        error = errorData.optString("error");
        desc = errorData.optString("error_description");
        LOG.error("Flattr ERROR {0}: {1}", error, desc);
    } catch (HttpRetryException ex) {
        // Could not read error response because HttpURLConnection sucketh
    } catch (IOException ex) {
        throw new FlattrException("Could not read response", ex);
    } catch (ClassCastException ex) {
        // An unexpected JSON type was returned, just throw a generic error
    } catch (JSONException ex) {
        // No valid error message was returned, just throw a generic error
    }

    if (error != null && desc != null) {
        if ("flattr_once".equals(error) || "flattr_owner".equals(error) || "thing_owner".equals(error)
                || "forbidden".equals(error) || "insufficient_scope".equals(error)
                || "unauthorized".equals(error) || "subscribed".equals(error)) {
            throw new ForbiddenException(error, desc);

        } else if ("no_means".equals(error) || "no_money".equals(error)) {
            throw new NoMoneyException(error, desc);

        } else if ("not_found".equals(error)) {
            throw new NotFoundException(error, desc);

        } else if ("rate_limit_exceeded".equals(error)) {
            throw new RateLimitExceededException(error, desc);

        } else if ("invalid_parameters".equals(error) || "invalid_scope".equals(error)
                || "validation".equals(error)) {
            throw new ValidationException(error, desc);
        }

        // "not_acceptable", "server_error", "invalid_request", everything else...
        throw new FlattrServiceException(error, desc);
    }

    LOG.error("Flattr {0}", httpStatus);
    throw new FlattrException(httpStatus);
}

From source file:jetbrains.buildServer.vmgr.agent.Utils.java

public String executeVSIFLaunch(String[] vsifs, String url, boolean requireAuth, String user, String password,
        BuildProgressLogger logger, boolean dynamicUserId, String buildID, String workPlacePath)
        throws Exception {

    boolean notInTestMode = true;
    if (logger == null) {
        notInTestMode = false;//from   w  w  w  .ja v  a 2 s  .  co m
    }

    String apiURL = url + "/rest/sessions/launch";

    for (int i = 0; i < vsifs.length; i++) {

        if (notInTestMode) {
            logger.message("vManager vAPI - Trying to launch vsif file: '" + vsifs[i] + "'");
        }
        String input = "{\"vsif\":\"" + vsifs[i] + "\"}";
        HttpURLConnection conn = getVAPIConnection(apiURL, requireAuth, user, password, "POST", dynamicUserId,
                buildID, workPlacePath, logger);
        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK
                && conn.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT
                && conn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED
                && conn.getResponseCode() != HttpURLConnection.HTTP_CREATED
                && conn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL
                && conn.getResponseCode() != HttpURLConnection.HTTP_RESET) {
            String reason = "";
            if (conn.getResponseCode() == 503)
                reason = "vAPI process failed to connect to remote vManager server.";
            if (conn.getResponseCode() == 401)
                reason = "Authentication Error";
            if (conn.getResponseCode() == 412)
                reason = "vAPI requires vManager 'Integration Server' license.";
            if (conn.getResponseCode() == 406)
                reason = "VSIF file '" + vsifs[i]
                        + "' was not found on file system, or is not accessed by the vAPI process.";
            String errorMessage = "Failed : HTTP error code : " + conn.getResponseCode() + " (" + reason + ")";
            if (notInTestMode) {
                logger.message(errorMessage);
                logger.message(conn.getResponseMessage());

                BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

                StringBuilder result = new StringBuilder();
                String output;
                while ((output = br.readLine()) != null) {
                    result.append(output);
                }
                logger.message(result.toString());

            }

            System.out.println(errorMessage);
            return errorMessage;
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        StringBuilder result = new StringBuilder();
        String output;
        while ((output = br.readLine()) != null) {
            result.append(output);
        }

        conn.disconnect();

        JSONObject tmp = JSONObject.fromObject(result.toString());

        String textOut = "Session Launch Success: Session ID: " + tmp.getString("value");

        if (notInTestMode) {
            logger.message(textOut);
        } else {

            System.out.println(textOut);
        }

    }

    return "success";
}

From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritHttpClient.java

public <T> T execute(Request<T> request, boolean authenticateIfNeeded, IProgressMonitor monitor)
        throws IOException, GerritException {
    String openIdProvider = getOpenIdProvider();

    hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);

    for (int attempt = 0; attempt < 2; attempt++) {
        if (authenticateIfNeeded) {
            // force authentication
            if (needsAuthentication()) {
                AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY);
                if (openIdProvider != null || credentials != null) {
                    authenticate(openIdProvider, monitor);
                }/*from w  ww . ja v a  2s  .c  o m*/
            }
            if (!obtainedXsrfKey) {
                updateXsrfKey(monitor);
            }
        }

        HttpMethodBase method = request.createMethod();
        if (obtainedXsrfKey) {
            // required to authenticate against Gerrit 2.6+ REST endpoints
            // harmless in previous versions
            method.setRequestHeader(X_GERRIT_AUTHORITY, xsrfKey);
        }
        try {
            // Execute the method.
            WebUtil.execute(httpClient, hostConfiguration, method, monitor);
        } catch (IOException e) {
            WebUtil.releaseConnection(method, monitor);
            throw e;
        } catch (RuntimeException e) {
            WebUtil.releaseConnection(method, monitor);
            throw e;
        }

        int code = method.getStatusCode();
        if (code == HttpURLConnection.HTTP_OK || code == HttpURLConnection.HTTP_ACCEPTED
                || code == HttpURLConnection.HTTP_CREATED) {
            try {
                return request.process(method);
            } finally {
                WebUtil.releaseConnection(method, monitor);
            }
        } else if (code == HttpURLConnection.HTTP_NO_CONTENT) {
            try {
                return null;
            } finally {
                WebUtil.releaseConnection(method, monitor);
            }

        } else {
            try {
                request.handleError(method);
            } finally {
                WebUtil.releaseConnection(method, monitor);
            }
            if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) {
                // login or re-authenticate due to an expired session
                authenticate(openIdProvider, monitor);
            } else {
                throw new GerritHttpException(code);
            }
        }
    }

    throw new GerritLoginException();
}

From source file:org.eclipse.orion.server.tests.prefs.PreferenceTest.java

@Test
public void testGetNode() throws IOException, JSONException {
    List<String> locations = getTestPreferenceNodes();
    for (String location : locations) {
        //unknown node should return 404
        WebRequest request = new GetMethodWebRequest(location);
        setAuthentication(request);//from w  ww  . j a  v a  2  s.  c  o m
        WebResponse response = webConversation.getResource(request);
        assertEquals("1." + location, HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());

        //put a value
        request = createSetPreferenceRequest(location, "Name", "Frodo");
        setAuthentication(request);
        response = webConversation.getResource(request);
        assertEquals("2." + location, HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode());

        //now doing a get should succeed
        request = new GetMethodWebRequest(location);
        setAuthentication(request);
        response = webConversation.getResource(request);
        assertEquals("3." + location, HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject result = new JSONObject(response.getText());
        assertEquals("4." + location, "Frodo", result.optString("Name"));
    }
}

From source file:org.eclipse.che.api.builder.internal.SourcesManagerImpl.java

private void download(String downloadUrl, java.io.File downloadTo) throws IOException {
    HttpURLConnection conn = null;
    try {//w  ww. j  a v  a2 s . c om
        final LinkedList<java.io.File> q = new LinkedList<>();
        q.add(downloadTo);
        final long start = System.currentTimeMillis();
        final List<Pair<String, String>> md5sums = new LinkedList<>();
        while (!q.isEmpty()) {
            java.io.File current = q.pop();
            java.io.File[] list = current.listFiles();
            if (list != null) {
                for (java.io.File f : list) {
                    if (f.isDirectory()) {
                        q.push(f);
                    } else {
                        md5sums.add(Pair.of(com.google.common.io.Files.hash(f, Hashing.md5()).toString(),
                                downloadTo.toPath().relativize(f.toPath()).toString().replace("\\", "/"))); //Replacing of "\" is need for windows support
                    }
                }
            }
        }
        final long end = System.currentTimeMillis();
        if (md5sums.size() > 0) {
            LOG.debug("count md5sums of {} files, time: {}ms", md5sums.size(), (end - start));
        }
        conn = (HttpURLConnection) new URL(downloadUrl).openConnection();
        conn.setConnectTimeout(CONNECT_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        final EnvironmentContext context = EnvironmentContext.getCurrent();
        if (context.getUser() != null && context.getUser().getToken() != null) {
            conn.setRequestProperty(HttpHeaders.AUTHORIZATION, context.getUser().getToken());
        }
        if (!md5sums.isEmpty()) {
            conn.setRequestMethod(HttpMethod.POST);
            conn.setRequestProperty("Content-type", MediaType.TEXT_PLAIN);
            conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.MULTIPART_FORM_DATA);
            conn.setDoOutput(true);
            try (OutputStream output = conn.getOutputStream(); Writer writer = new OutputStreamWriter(output)) {
                for (Pair<String, String> pair : md5sums) {
                    writer.write(pair.first);
                    writer.write(' ');
                    writer.write(pair.second);
                    writer.write('\n');
                }
            }
        }
        final int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentType = conn.getHeaderField("content-type");
            if (contentType.startsWith(MediaType.MULTIPART_FORM_DATA)) {
                final HeaderParameterParser headerParameterParser = new HeaderParameterParser();
                final String boundary = headerParameterParser.parse(contentType).get("boundary");
                try (InputStream in = conn.getInputStream()) {
                    MultipartStream multipart = new MultipartStream(in, boundary.getBytes());
                    boolean hasMore = multipart.skipPreamble();
                    while (hasMore) {
                        final Map<String, List<String>> headers = parseChunkHeader(
                                CharStreams.readLines(new StringReader(multipart.readHeaders())));
                        final List<String> contentDisposition = headers.get("content-disposition");
                        final String name = headerParameterParser.parse(contentDisposition.get(0)).get("name");
                        if ("updates".equals(name)) {
                            int length = -1;
                            List<String> contentLengthHeader = headers.get("content-length");
                            if (contentLengthHeader != null && !contentLengthHeader.isEmpty()) {
                                length = Integer.parseInt(contentLengthHeader.get(0));
                            }
                            if (length < 0 || length > 204800) {
                                java.io.File tmp = java.io.File.createTempFile("tmp", ".zip", directory);
                                try {
                                    try (FileOutputStream fOut = new FileOutputStream(tmp)) {
                                        multipart.readBodyData(fOut);
                                    }
                                    ZipUtils.unzip(tmp, downloadTo);
                                } finally {
                                    if (tmp.exists()) {
                                        tmp.delete();
                                    }
                                }
                            } else {
                                final ByteArrayOutputStream bOut = new ByteArrayOutputStream(length);
                                multipart.readBodyData(bOut);
                                ZipUtils.unzip(new ByteArrayInputStream(bOut.toByteArray()), downloadTo);
                            }
                        } else if ("removed-paths".equals(name)) {
                            final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                            multipart.readBodyData(bOut);
                            final String[] removed = JsonHelper.fromJson(
                                    new ByteArrayInputStream(bOut.toByteArray()), String[].class, null);
                            for (String path : removed) {
                                java.io.File f = new java.io.File(downloadTo, path);
                                if (!f.delete()) {
                                    throw new IOException(String.format("Unable delete %s", path));
                                }
                            }
                        } else {
                            // To /dev/null :)
                            multipart.readBodyData(DEV_NULL);
                        }
                        hasMore = multipart.readBoundary();
                    }
                }
            } else {
                try (InputStream in = conn.getInputStream()) {
                    ZipUtils.unzip(in, downloadTo);
                }
            }
        } else if (responseCode != HttpURLConnection.HTTP_NO_CONTENT) {
            throw new IOException(
                    String.format("Invalid response status %d from remote server. ", responseCode));
        }
    } catch (ParseException | JsonParseException e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerRestClient.java

public boolean delete(String sessionId, String dataspacePath, String path, List<String> includes,
        List<String> excludes) throws Exception {
    StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL)
            .append(addSlashIfMissing(restEndpointURL)).append("data/").append(dataspacePath).append('/');
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine).providerFactory(providerFactory)
            .build();/*  ww w .  j  a  v  a  2 s.  com*/
    ResteasyWebTarget target = client.target(uriTmpl.toString()).path(path);
    if (includes != null && !includes.isEmpty()) {
        target = target.queryParam("includes", includes.toArray(new Object[includes.size()]));
    }
    if (excludes != null && !excludes.isEmpty()) {
        target = target.queryParam("excludes", excludes.toArray(new Object[excludes.size()]));
    }
    Response response = null;
    try {
        response = target.request().header("sessionid", sessionId).delete();
        if (response.getStatus() != HttpURLConnection.HTTP_NO_CONTENT) {
            if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new NotConnectedRestException("User not authenticated or session timeout.");
            } else {
                throwException(String.format("Cannot delete file(s). Status code: %s", response.getStatus()),
                        response);
            }
        }
        return true;
    } finally {
        if (response != null) {
            response.close();
        }
    }
}