Example usage for java.net HttpURLConnection HTTP_CREATED

List of usage examples for java.net HttpURLConnection HTTP_CREATED

Introduction

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

Prototype

int HTTP_CREATED

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

Click Source Link

Document

HTTP Status-Code 201: Created.

Usage

From source file:org.eclipse.hono.service.tenant.TenantHttpEndpoint.java

private void addTenant(final RoutingContext ctx) {

    final String tenantId = getTenantIdFromContext(ctx);

    final String location = String.format("/%s/%s", TenantConstants.TENANT_ENDPOINT, tenantId);

    doTenantHttpRequest(ctx, tenantId, TenantConstants.TenantAction.add,
            status -> status == HttpURLConnection.HTTP_CREATED,
            response -> response.putHeader(HttpHeaders.LOCATION, location));
}

From source file:fm.last.moji.impl.FileUploadOutputStream.java

private void flushAndClose() throws IOException {
    try {//from  w w w .j a va 2  s.  c o  m
        delegate.flush();
        size = delegate.getByteCount();
        log.debug("Bytes written: {}", size);
        int code = httpConnection.getResponseCode();
        if (HttpURLConnection.HTTP_OK != code && HttpURLConnection.HTTP_CREATED != code) {
            String message = httpConnection.getResponseMessage();
            throw new IOException(
                    "HTTP Error during flush: " + code + ", " + message + ", peer: '{" + httpConnection + "}'");
        }
    } finally {
        try {
            delegate.close();
        } catch (Exception e) {
            log.warn("Error closing stream", e);
        }
        try {
            httpConnection.disconnect();
        } catch (Exception e) {
            log.warn("Error closing connection", e);
        }
    }
}

From source file:poisondog.vfs.webdav.WebdavFileFactory.java

public boolean move(String from, String to, boolean overwrite)
        throws FileNotFoundException, IOException, DavException {
    return execute(new MoveMethod(mTask.process(from), mTask.process(to),
            overwrite)) == HttpURLConnection.HTTP_CREATED;
}

From source file:jetbrains.buildServer.commitPublisher.github.api.impl.GitHubApiImpl.java

public void setChangeStatus(@NotNull final String repoOwner, @NotNull final String repoName,
        @NotNull final String hash, @NotNull final GitHubChangeState status, @NotNull final String targetUrl,
        @NotNull final String description, @Nullable final String context) throws IOException {
    final GSonEntity requestEntity = new GSonEntity(myGson,
            new CommitStatus(status.getState(), targetUrl, description, context));
    final HttpPost post = new HttpPost(myUrls.getStatusUrl(repoOwner, repoName, hash));
    try {/*w  w w .  j  a  v a 2s .c om*/
        post.setEntity(requestEntity);
        includeAuthentication(post);
        setDefaultHeaders(post);

        logRequest(post, requestEntity.getText());
        final HttpResponse execute = myClient.execute(post);
        if (execute.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_CREATED) {
            logFailedResponse(post, requestEntity.getText(), execute);
            throw new IOException("Failed to complete request to GitHub. Status: " + execute.getStatusLine());
        }
    } finally {
        post.abort();
    }
}

From source file:org.eclipse.hono.service.credentials.CredentialsHttpEndpoint.java

private void addCredentials(final RoutingContext ctx) {

    final JsonObject payload = (JsonObject) ctx.get(KEY_REQUEST_BODY);
    final String deviceId = payload.getString(CredentialsConstants.FIELD_PAYLOAD_DEVICE_ID);
    final String authId = payload.getString(CredentialsConstants.FIELD_AUTH_ID);
    final String type = payload.getString(CredentialsConstants.FIELD_TYPE);
    final String tenantId = getTenantParam(ctx);
    logger.debug("adding credentials [tenant: {}, device-id: {}, auth-id: {}, type: {}]", tenantId, deviceId,
            authId, type);/*from   ww  w  .  j  av a  2 s  .  co  m*/

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

    sendAction(ctx, requestMsg,
            getDefaultResponseHandler(ctx, status -> status == HttpURLConnection.HTTP_CREATED,
                    httpServerResponse -> httpServerResponse.putHeader(HttpHeaders.LOCATION,
                            String.format("/%s/%s/%s/%s", CredentialsConstants.CREDENTIALS_ENDPOINT, tenantId,
                                    authId, type))));
}

From source file:org.xframium.integrations.alm.ALMRESTConnection.java

private String attachWithMultipart(String entityUrl, byte[] fileData, String contentType, String filename,
        String description) throws Exception {

    // Note the order - extremely important:
    // Filename and description before file data.
    // Name of file in file part and filename part value MUST MATCH.
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bytes.write(String.format(fieldTemplate, boundary, "filename", filename).getBytes());
    bytes.write(String.format(fieldTemplate, boundary, "description", description).getBytes());
    bytes.write(("\r\n--" + boundary + "--").getBytes());
    bytes.write(fileData);/*from  w  ww. j  a  v a2s. c  o m*/
    bytes.write(String.format(fileDataPrefixTemplate, boundary, "file", filename, contentType).getBytes());
    bytes.close();

    Map<String, String> requestHeaders = new HashMap<String, String>();

    requestHeaders.put("Content-Type", "multipart/form-data; boundary=" + boundary);

    ALMResponse response = httpPost(entityUrl + "/attachments", bytes.toByteArray(), requestHeaders);

    if (response.getStatusCode() != HttpURLConnection.HTTP_CREATED) {
        throw new Exception(response.toString());
    }

    return response.getResponseHeaders().get("Location").iterator().next();
}

From source file:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.bibsonomy.BibsonomyUtils.java

/** send a POST request and return the response as string */
String sendPutRequest(String url, String bodytext) throws Exception {
    String sresponse;//from w ww .j ava2s. c  o m

    HttpClient httpclient = new DefaultHttpClient();
    HttpPut httpput = new HttpPut(url);

    // add authorization header
    httpput.addHeader("Authorization", authHeader);

    StringEntity body = new StringEntity(bodytext);
    httpput.setEntity(body);

    HttpResponse response = httpclient.execute(httpput);

    // check statuscode
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK
            || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED) {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());
        httpclient.getConnectionManager().shutdown();
    } else {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());
        String httpcode = Integer.toString(response.getStatusLine().getStatusCode());
        httpclient.getConnectionManager().shutdown();
        throw new ReferenceSystemException(httpcode, "Bibsonomy Error", XMLUtils.parseError(sresponse));
    }
    return sresponse;

}

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

@Test
public void testCopyFileNoOverwrite() throws Exception {
    String directoryPath = "testCopyFile/directory/path" + System.currentTimeMillis();
    String sourcePath = directoryPath + "/source.txt";
    String destName = "destination.txt";
    String destPath = directoryPath + "/" + destName;
    createDirectory(directoryPath);//w  w w . j  a  va2 s  . c o  m
    createFile(sourcePath, "This is the contents");
    JSONObject requestObject = new JSONObject();
    addSourceLocation(requestObject, sourcePath);
    WebRequest request = getPostFilesRequest(directoryPath, requestObject.toString(), "destination.txt");
    request.setHeaderField("X-Create-Options", "copy");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    JSONObject responseObject = new JSONObject(response.getText());
    checkFileMetadata(responseObject, destName, null, null, null, null, null, null, null, null);
    assertTrue(checkFileExists(sourcePath));
    assertTrue(checkFileExists(destPath));
}

From source file:org.jboss.narayana.rts.TransactionAwareResource.java

@GET
@Produces("text/plain")
public Response someServiceRequest(@Context UriInfo info, @QueryParam("tid") String wid,
        @QueryParam("enlistURL") String enlistUrl) {
    if (enlistUrl == null || enlistUrl.length() == 0)
        return Response.ok(NON_TXN_MSG).build();

    //        String wid = tid; // Integer.toString(workId.incrementAndGet());
    String serviceURL = info.getBaseUri() + info.getPath().substring(1); // avoid '//' in urls
    String linkHeader = makeTwoPhaseAwareParticipantLinkHeader(serviceURL, false, String.valueOf(wid), null);
    Response response;/* w w  w .  ja  v  a2s. c o m*/

    // enlist using linkHeader
    try {
        boolean jc = false;

        if (log.isTraceEnabled()) {
            log.tracef("[%s]: workId %s enlist%n", wid, wid);
            log.tracef("\tLink: %s%n", linkHeader);
        }

        if (jc) {
            response = getClient().target(enlistUrl).request().header("Link", linkHeader)
                    .post(Entity.entity(new Form(), TxMediaType.POST_MEDIA_TYPE));

            if (log.isTraceEnabled())
                log.tracef("[%s]: workId %s enlisted%n", wid, wid);
            if (response.getStatus() != HttpURLConnection.HTTP_CREATED)
                return Response.status(response.getStatus()).build();
        } else {
            enlist(enlistUrl, linkHeader);
        }
        response = Response.ok(wid).build();
        if (log.isTraceEnabled())
            log.tracef("[%s]: workId %s returning%n", wid, wid);
        return response;
    } catch (HttpResponseException e) {
        return Response.status(e.getActualResponse()).build();
    } catch (Throwable e) {
        return Response.serverError().build();
    }
}

From source file:org.cm.podd.report.util.RequestDataUtil.java

public static ResponseObject get(String path, String query, String token) {
    JSONObject jsonObj = null;//from   w w  w .ja va  2  s  .com
    String rawData = null;
    int statusCode = 0;

    //SharedPreferences settings = PoddApplication.getAppContext().getSharedPreferences("PoddPrefsFile", 0);
    String serverUrl = settings.getString("serverUrl", BuildConfig.SERVER_URL);

    String reqUrl = "";
    if (path.contains("http://") || path.contains("https://")) {
        reqUrl = String.format("%s%s", path, query == null ? "" : "?" + query);
    } else {
        reqUrl = String.format("%s%s%s", serverUrl, path, query == null ? "" : "?" + query);
    }
    Log.i(TAG, "submit url=" + reqUrl);

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpClient client = new DefaultHttpClient(params);

    try {
        HttpGet get = new HttpGet(reqUrl);
        if (token != null) {
            get.setHeader("Authorization", "Token " + token);
        }

        HttpResponse response;
        response = client.execute(get);
        HttpEntity entity = response.getEntity();

        // Detect server complaints
        statusCode = response.getStatusLine().getStatusCode();
        Log.v(TAG, "status code=" + statusCode);

        if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) {
            InputStream in = entity.getContent();
            rawData = FileUtil.convertInputStreamToString(in);

            entity.consumeContent();
        }

    } catch (ClientProtocolException e) {
        Log.e(TAG, "error post data", e);
    } catch (IOException e) {
        Log.e(TAG, "Can't connect server", e);
    } finally {
        client.getConnectionManager().shutdown();
    }

    ResponseObject respObj = new ResponseObject(statusCode, jsonObj);
    respObj.setRawData(rawData);
    return respObj;
}