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:org.eclipse.hono.service.credentials.CredentialsHttpEndpoint.java

private void removeCredentialsForDevice(final RoutingContext ctx) {

    final String tenantId = getTenantParam(ctx);
    final String deviceId = getDeviceIdParam(ctx);

    logger.debug("removeCredentialsForDevice: [tenant: {}, device-id: {}]", tenantId, deviceId);

    final JsonObject payload = new JsonObject();
    payload.put(CredentialsConstants.FIELD_PAYLOAD_DEVICE_ID, deviceId);
    payload.put(CredentialsConstants.FIELD_TYPE, CredentialsConstants.SPECIFIER_WILDCARD);

    final JsonObject requestMsg = EventBusMessage
            .forOperation(CredentialsConstants.CredentialsAction.remove.toString()).setTenant(tenantId)
            .setDeviceId(deviceId).setJsonPayload(payload).toJson();

    sendAction(ctx, requestMsg,/*www.  ja v a 2s.co m*/
            getDefaultResponseHandler(ctx, status -> status == HttpURLConnection.HTTP_NO_CONTENT, null));
}

From source file:uk.ac.gate.cloud.client.RestClient.java

/**
 * Make an API request and return the raw data from the response as an
 * InputStream.//from ww  w  .  j  a v a2 s.  c om
 * 
 * @param target the URL to request (relative URLs will resolve
 *          against the {@link #getBaseUrl() base URL}).
 * @param method the request method (GET, POST, DELETE, etc.)
 * @param requestBody the value to send as the request body. If
 *          <code>null</code>, no request body is sent. If an
 *          <code>InputStream</code> or a <code>StreamWriteable</code>
 *          then its content will be sent as-is and an appropriate
 *          <code>Content-Type</code> should be given in the
 *          <code>extraHeaders</code> (note that the input stream will
 *          <em>not</em> be closed by this method, that is the
 *          responsibility of the caller). Otherwise the provided
 *          object will be serialized to JSON and sent with the
 *          default <code>application/json</code> MIME type.
 * @param gzipThreshold size threshold above which the request body
 *          should be GZIP compressed. If negative, the request will
 *          never be compressed.
 * @param extraHeaders any additional HTTP headers, specified as an
 *          alternating sequence of header names and values
 * @return for a successful response, the response stream, or
 *         <code>null</code> for a 201 response
 * @throws RestClientException if an exception occurs during
 *           processing, or the server returns a 4xx or 5xx error
 *           response (in which case the response JSON message will be
 *           available as a {@link JsonNode} in the exception).
 */
public InputStream requestForStream(String target, String method, Object requestBody, int gzipThreshold,
        String... extraHeaders) throws RestClientException {
    try {
        HttpURLConnection connection = sendRequest(target, method, requestBody, gzipThreshold, extraHeaders);
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            // successful response with no content
            return null;
        } else if (responseCode >= 400) {
            readError(connection);
            return null; // not reachable, readError always throws exception
        } else if (responseCode >= 300) {
            // redirect - all redirects we care about from the GATE Cloud
            // APIs are 303. We have to follow them manually to make
            // authentication work properly.
            String location = connection.getHeaderField("Location");
            // consume body
            InputStream stream = connection.getInputStream();
            IOUtils.copy(stream, new NullOutputStream());
            IOUtils.closeQuietly(stream);
            // follow the redirect
            return requestForStream(location, method, requestBody, gzipThreshold, extraHeaders);
        } else {
            storeHeaders(connection);
            if ("gzip".equals(connection.getHeaderField("Content-Encoding"))) {
                return new GZIPInputStream(connection.getInputStream());
            } else {
                return connection.getInputStream();
            }
        }
    } catch (IOException e) {
        throw new RestClientException(e);
    }

}

From source file:uk.co.firstzero.webdav.Push.java

/**
 * Uploads the file. The File object (f) is used for creating a FileInputStream for uploading
 * files to webdav/* w ww  .j a  va 2  s . c o  m*/
 * @param f   The File object of the file to be uploaded
 * @param filename   The relatvie path of the file
 */
public boolean uploadFile(File f, String filename) throws IOException {
    String uploadUrl = url + "/" + filename;
    boolean uploaded = false;

    deleteFile(uploadUrl);
    PutMethod putMethod = new PutMethod(uploadUrl);

    logger.debug("Check if file exists - " + fileExists(uploadUrl));

    if (!fileExists(uploadUrl)) {
        RequestEntity requestEntity = new InputStreamRequestEntity(new FileInputStream(f));

        putMethod.setRequestEntity(requestEntity);
        httpClient.executeMethod(putMethod);

        logger.trace("uploadFile - statusCode - " + putMethod.getStatusCode());

        switch (putMethod.getStatusCode()) {
        case HttpURLConnection.HTTP_NO_CONTENT:
            logger.info("IGNORE - File already exists " + f.getAbsolutePath());
            break;
        case HttpURLConnection.HTTP_OK:
            uploaded = true;
            logger.info("Transferred " + f.getAbsolutePath());
            break;
        case HttpURLConnection.HTTP_CREATED: //201 Created => No issues
            uploaded = true;
            logger.info("Transferred " + f.getAbsolutePath());
            break;
        default:
            logger.error("ERR " + " " + putMethod.getStatusCode() + " " + putMethod.getStatusText() + " "
                    + f.getAbsolutePath());
            break;
        }
    } else {
        logger.info("IGNORE - File already exists " + f.getAbsolutePath());
    }
    return uploaded;
}

From source file:org.eclipse.orion.server.tests.metastore.RemoteMetaStoreTests.java

/**
 * Create a plugins preference on the Orion server for the test user.
 * /*from w  ww .j ava 2  s . c  o  m*/
 * @param webConversation
 * @param login
 * @param password
 * @param projectName
 * @return
 * @throws IOException
 * @throws JSONException
 * @throws URISyntaxException
 * @throws SAXException 
 */
protected int createPluginsPref(WebConversation webConversation, String login, String password)
        throws IOException, JSONException, URISyntaxException, SAXException {
    assertEquals(HttpURLConnection.HTTP_OK, login(webConversation, login, password));

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("http://mamacdon.github.io/0.3/plugins/bugzilla/plugin.html", true);
    WebRequest request = new PutMethodWebRequest(getOrionServerURI("/prefs/user/plugins"),
            IOUtilities.toInputStream(jsonObject.toString()), "application/json");
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode());

    System.out.println("Created Preference /prefs/user/plugins");
    return response.getResponseCode();
}

From source file:org.eclipse.orion.server.tests.servlets.files.AdvancedFilesTest.java

@Test
public void testMetadataHandling() throws JSONException, IOException, SAXException {

    String fileName = "testMetadataHandling.txt";

    //setup: create a file
    WebRequest request = getPostFilesRequest("", getNewFileJSON(fileName).toString(), fileName);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

    //obtain file metadata and ensure data is correct
    request = getGetFilesRequest(fileName + "?parts=meta");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject responseObject = new JSONObject(response.getText());
    assertNotNull("No file information in response", responseObject);
    checkFileMetadata(responseObject, fileName, new Long(-1), null, null, request.getURL().getRef(),
            new Long(0), null, null, null);

    //modify the metadata
    request = getPutFileRequest(fileName + "?parts=meta", getFileMetadataObject(true, true).toString());
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode());

    //fetch the metadata again and ensure it is changed
    request = getGetFilesRequest(fileName + "?parts=meta");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    responseObject = new JSONObject(response.getText());
    checkFileMetadata(responseObject, fileName, new Long(-1), null, null, request.getURL().getRef(),
            new Long(0), new Boolean(true), new Boolean(true), null);

    //make the file writeable again so test can clean up
    request = getPutFileRequest(fileName + "?parts=meta", getFileMetadataObject(false, false).toString());
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode());

}

From source file:io.joynr.messaging.bounceproxy.monitoring.BounceProxyStartupReporter.java

/**
 * Reports the lifecycle event to the monitoring service as HTTP request.
 * /*from  w w w .java2  s.  c o  m*/
 * @throws IOException
 *             if the connection with the bounce proxy controller could not
 *             be established
 * @throws JoynrHttpException
 *             if the bounce proxy responded that registering the bounce
 *             proxy did not succeed
 */
private void reportEventAsHttpRequest() throws IOException {

    final String url = bounceProxyControllerUrl.buildReportStartupUrl(controlledBounceProxyUrl);
    logger.debug("Using monitoring service URL: {}", url);

    HttpPut putReportStartup = new HttpPut(url.trim());

    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(putReportStartup);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        switch (statusCode) {
        case HttpURLConnection.HTTP_NO_CONTENT:
            // bounce proxy instance was already known at the bounce proxy
            // controller
            // nothing else to do
            logger.info("Bounce proxy was already registered with the controller");
            break;

        case HttpURLConnection.HTTP_CREATED:
            // bounce proxy instance was registered for the very first time
            // TODO maybe read URL
            logger.info("Registered bounce proxy with controller");
            break;

        default:
            logger.error("Failed to send startup notification: {}", response);
            throw new JoynrHttpException(statusCode,
                    "Failed to send startup notification. Bounce Proxy won't get any channels assigned.");
        }

    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:org.eclipse.hono.client.impl.RegistrationClientImpl.java

/**
 * Invokes the <em>Deregister Device</em> operation of Hono's
 * <a href="https://www.eclipse.org/hono/api/Device-Registration-API">Device Registration API</a>
 * on the service represented by the <em>sender</em> and <em>receiver</em> links.
 *///from w  w  w.j  a  v  a 2 s . co  m
@Override
public final Future<Void> deregister(final String deviceId) {

    Objects.requireNonNull(deviceId);

    final Future<RegistrationResult> regResultTracker = Future.future();
    createAndSendRequest(RegistrationConstants.ACTION_DEREGISTER, createDeviceIdProperties(deviceId), null,
            regResultTracker.completer());
    return regResultTracker.map(response -> {
        switch (response.getStatus()) {
        case HttpURLConnection.HTTP_NO_CONTENT:
            return null;
        default:
            throw StatusCodeMapper.from(response);
        }
    });
}

From source file:com.upnext.blekit.util.http.HttpClient.java

public <T> Response<T> fetchResponse(Class<T> clazz, String path, Map<String, String> params, String httpMethod,
        String payload, String payloadContentType) {
    try {//from w w w  .  j  a va2  s . c om
        String fullUrl = urlWithParams(path != null ? url + path : url, params);
        L.d("[" + httpMethod + "] " + fullUrl);
        final URLConnection connection = new URL(fullUrl).openConnection();
        if (connection instanceof HttpURLConnection) {
            final HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setDoInput(true);
            if (httpMethod != null) {
                httpConnection.setRequestMethod(httpMethod);
                if (httpMethod.equals("POST")) {
                    connection.setDoOutput(true); // Triggers POST.
                    connection.setRequestProperty("Accept-Charset", "UTF-8");
                    connection.setRequestProperty("Content-Type", payloadContentType);
                }
            } else {
                httpConnection.setRequestMethod(params != null ? "POST" : "GET");
            }
            httpConnection.addRequestProperty("Accept", "application/json");
            httpConnection.connect();
            if (payload != null) {
                OutputStream outputStream = httpConnection.getOutputStream();
                try {
                    if (LOG_RESPONSE) {
                        L.d("[payload] " + payload);
                    }
                    OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
                    writer.write(payload);
                    writer.close();
                } finally {
                    outputStream.close();
                }
            }
            InputStream input = null;
            try {
                input = connection.getInputStream();
            } catch (IOException e) {
                // workaround for Android HttpURLConnection ( IOException is thrown for 40x error codes ).
                final int statusCode = httpConnection.getResponseCode();
                if (statusCode == -1)
                    throw e;
                return new Response<T>(Error.httpError(httpConnection.getResponseCode()));
            }
            final int statusCode = httpConnection.getResponseCode();
            L.d("statusCode " + statusCode);
            if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) {
                try {
                    T value = null;
                    if (clazz != Void.class) {
                        if (LOG_RESPONSE || clazz == String.class) {
                            StringBuilder sb = new StringBuilder();
                            BufferedReader br = new BufferedReader(new InputStreamReader(input));
                            String read = br.readLine();
                            while (read != null) {
                                sb.append(read);
                                read = br.readLine();
                            }
                            String response = sb.toString();
                            if (LOG_RESPONSE) {
                                L.d("response " + response);
                            }
                            if (clazz == String.class) {
                                value = (T) response;
                            } else {
                                value = (T) objectMapper.readValue(response, clazz);
                            }
                        } else {
                            value = (T) objectMapper.readValue(input, clazz);
                        }
                    }
                    return new Response<T>(value);
                } catch (JsonMappingException e) {
                    return new Response<T>(Error.serlizerError(e));
                } catch (JsonParseException e) {
                    return new Response<T>(Error.serlizerError(e));
                }
            } else if (statusCode == HttpURLConnection.HTTP_NO_CONTENT) {
                try {
                    T def = clazz.newInstance();
                    if (LOG_RESPONSE) {
                        L.d("statusCode  == HttpURLConnection.HTTP_NO_CONTENT");
                    }
                    return new Response<T>(def);
                } catch (InstantiationException e) {
                    return new Response<T>(Error.ioError(e));
                } catch (IllegalAccessException e) {
                    return new Response<T>(Error.ioError(e));
                }
            } else {
                if (LOG_RESPONSE) {
                    L.d("error, statusCode " + statusCode);
                }
                return new Response<T>(Error.httpError(statusCode));
            }
        }
        return new Response<T>(Error.ioError(new Exception("Url is not a http link")));
    } catch (IOException e) {
        if (LOG_RESPONSE) {
            L.d("error, ioError " + e);
        }
        return new Response<T>(Error.ioError(e));
    }
}

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

TenantResult<JsonObject> removeTenant(final String tenantId) {

    Objects.requireNonNull(tenantId);

    if (getConfig().isModificationEnabled()) {
        if (tenants.remove(tenantId) != null) {
            dirty = true;/*from  www .j a  v  a  2  s.co m*/
            return TenantResult.from(HttpURLConnection.HTTP_NO_CONTENT);
        } else {
            return TenantResult.from(HttpURLConnection.HTTP_NOT_FOUND);
        }
    } else {
        return TenantResult.from(HttpURLConnection.HTTP_FORBIDDEN);
    }
}

From source file:com.lion328.xenonlauncher.minecraft.api.authentication.yggdrasil.YggdrasilMinecraftAuthenticator.java

private <T> T sendRequest(String endpoint, Object request, Class<T> clazz, boolean nullCheck)
        throws IOException, YggdrasilAPIException {
    String requestJson = gson.toJson(request);
    ResponseState state = sendRequest(endpoint, requestJson);

    try {//from  ww  w.  ja  v  a2s  .c  om
        gson.fromJson(state.getData(), Object.class);
    } catch (JsonParseException e) {
        throw new InvalidImplementationException();
    }

    if (state.getResponseCode() / 100 != 2) {
        YggdrasilErrorMessage message = gson.fromJson(state.getData(), YggdrasilErrorMessage.class);
        throw message.toException();
    }

    if (state.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT || state.getData().length() == 0) {
        if (nullCheck) {
            throw new InvalidImplementationException("Get empty response: " + endpoint);
        }

        return null;
    }

    if (clazz == null) {
        return null;
    }

    T ret = gson.fromJson(state.getData(), clazz);

    if (ret == null) {
        throw new InvalidImplementationException("GSON returns null");
    }

    return ret;
}