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:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.connotea.ConnoteaUtils.java

/** send a POST Request and return the response as string */
String sendPostRequest(String url, String bodytext) throws Exception {
    String sresponse;/*  www  . j  a va  2s.  com*/

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    // set authentication header
    httppost.addHeader("Authorization", authHeader);

    // very important. otherwise there comes a invalid request error
    httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    StringEntity body = new StringEntity(bodytext);
    body.setContentType("application/x-www-form-urlencoded");

    httppost.setEntity(body);

    HttpResponse response = httpclient.execute(httppost);

    // check status code.
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK
            || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED
            || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
        // Not found too. no exception should be thrown.
        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, "Connotea Error", RDFUtils.parseError(sresponse));
    }
    return sresponse;

}

From source file:hudson.plugins.boundary.Boundary.java

public void sendEvent(AbstractBuild<?, ?> build, BuildListener listener) throws IOException {
    final HashMap<String, Object> event = new HashMap<String, Object>();
    event.put("fingerprintFields", Arrays.asList("build name"));

    final Map<String, String> source = new HashMap<String, String>();
    String hostname = "localhost";

    try {/*w  w  w  .  j ava  2  s.c  o  m*/
        hostname = java.net.InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        listener.getLogger().println("host lookup exception: " + e);
    }

    source.put("ref", hostname);
    source.put("type", "jenkins");
    event.put("source", source);

    final Map<String, String> properties = new HashMap<String, String>();
    properties.put("build status", build.getResult().toString());
    properties.put("build number", build.getDisplayName());
    properties.put("build name", build.getProject().getName());
    event.put("properties", properties);

    event.put("title",
            String.format("Jenkins Build Job - %s - %s", build.getProject().getName(), build.getDisplayName()));

    if (Result.SUCCESS.equals(build.getResult())) {
        event.put("severity", "INFO");
        event.put("status", "CLOSED");
    } else {
        event.put("severity", "WARN");
        event.put("status", "OPEN");
    }

    final String url = String.format("https://api.boundary.com/%s/events", this.id);
    final HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    final String authHeader = "Basic " + new String(Base64.encodeBase64((token + ":").getBytes(), false));
    conn.setRequestProperty("Authorization", authHeader);
    conn.setDoInput(true);
    conn.setDoOutput(true);

    InputStream is = null;
    OutputStream os = null;
    try {
        os = conn.getOutputStream();
        OBJECT_MAPPER.writeValue(os, event);
        os.flush();
        is = conn.getInputStream();
    } finally {
        close(is);
        close(os);
    }

    final int responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_CREATED) {
        listener.getLogger().println("Invalid HTTP response code from Boundary API: " + responseCode);
    } else {
        String location = conn.getHeaderField("Location");
        if (location.startsWith("http:")) {
            location = "https" + location.substring(4);
        }
        listener.getLogger().println("Created Boundary Event: " + location);
    }
}

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

/**
 * Creates a test project with the given name.
 * @throws SAXException //from  w  w w . j av a 2  s.  c  o m
 * @throws IOException 
 */
protected void createTestProject(String name) throws Exception {
    //create workspace
    String workspaceName = getClass().getName() + "#" + name;
    URI workspaceLocation = createWorkspace(workspaceName);

    //create a project
    String projectName = name + "Project";
    WebRequest request = getCreateProjectRequest(workspaceLocation, projectName, null);
    WebResponse response = webConversation.getResponse(request);
    if (response.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
        String msg = "Unexpected " + response.getResponseCode() + " response creating project " + projectName
                + ": " + response.getText();
        System.out.println(msg);
        LogHelper.log(new Status(IStatus.ERROR, ServerTestsActivator.PI_TESTS, msg));
        fail(msg);
    }
    IPath workspacePath = new Path(workspaceLocation.getPath());
    String workspaceId = new Path(workspaceLocation.getPath()).segment(workspacePath.segmentCount() - 1);
    testProjectBaseLocation = "/" + workspaceId + '/' + projectName;
    JSONObject project = new JSONObject(response.getText());
    testProjectLocalFileLocation = "/" + project.optString(ProtocolConstants.KEY_ID, null);
}

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

@Test
public void testETagPutNotMatch() throws JSONException, IOException, SAXException, CoreException {
    String fileName = "testfile.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());
    String etag = response.getHeaderField(ProtocolConstants.KEY_ETAG);
    assertNotNull(etag);/* w  w w  .  j  av a2  s . c  om*/

    //change the file on disk
    IFileStore fileStore = EFS.getStore(makeLocalPathAbsolute(fileName));
    OutputStream out = fileStore.openOutputStream(EFS.NONE, null);
    out.write("New Contents".getBytes());
    out.close();

    //now a PUT should fail
    request = getPutFileRequest(fileName, "something");
    request.setHeaderField("If-Match", etag);
    try {
        response = webConversation.getResponse(request);
    } catch (IOException e) {
        //inexplicably HTTPUnit throws IOException on PRECON_FAILED rather than just giving us response
        assertTrue(e.getMessage().indexOf(Integer.toString(HttpURLConnection.HTTP_PRECON_FAILED)) > 0);
    }
}

From source file:jp.realglobe.util.uploader.DirectoryUploaderWithServerTest.java

private void handle(final HttpExchange exchange) throws IOException {
    final String path = exchange.getRequestURI().getPath();

    if (path.equals(Constants.URL_PATH_TOKEN)) {
        final Map<String, Object> tokenData = new HashMap<>();
        tokenData.put(Constants.TOKEN_RESPONSE_KEY_TOKEN, "abcde");
        final Map<String, Object> data = new HashMap<>();
        data.put(Constants.TOKEN_RESPONSE_KEY_DATA, tokenData);
        Utils.readAll(exchange.getRequestBody());
        exchange.sendResponseHeaders(HttpURLConnection.HTTP_CREATED, 0);
        exchange.getResponseBody().write((new JSONObject(data)).toString().getBytes());
    } else if (path.startsWith(Constants.URL_PATH_UPLOAD_PREFIX) && path
            .substring(Constants.URL_PATH_UPLOAD_PREFIX.length()).endsWith(Constants.URL_PATH_UPLOAD_SUFFIX)) {
        this.requestQueue.offer(new HttpRequest(exchange));
        exchange.sendResponseHeaders(HttpURLConnection.HTTP_CREATED, 0);
    }//from w w w  .  ja  v  a  2  s  .  c  o m
    exchange.close();
}

From source file:org.apache.hadoop.fs.azure.metrics.ResponseReceivedMetricUpdater.java

/**
 * Handle the response-received event from Azure SDK.
 *//*from  www.  j a va 2s . co m*/
@Override
public void eventOccurred(ResponseReceivedEvent eventArg) {
    instrumentation.webResponse();
    if (!(eventArg.getConnectionObject() instanceof HttpURLConnection)) {
        // Typically this shouldn't happen, but just let it pass
        return;
    }
    HttpURLConnection connection = (HttpURLConnection) eventArg.getConnectionObject();
    RequestResult currentResult = eventArg.getRequestResult();
    if (currentResult == null) {
        // Again, typically shouldn't happen, but let it pass
        return;
    }

    long requestLatency = currentResult.getStopDate().getTime() - currentResult.getStartDate().getTime();

    if (currentResult.getStatusCode() == HttpURLConnection.HTTP_CREATED
            && connection.getRequestMethod().equalsIgnoreCase("PUT")) {
        // If it's a PUT with an HTTP_CREATED status then it's a successful
        // block upload.
        long length = getRequestContentLength(connection);
        if (length > 0) {
            blockUploadGaugeUpdater.blockUploaded(currentResult.getStartDate(), currentResult.getStopDate(),
                    length);
            instrumentation.rawBytesUploaded(length);
            instrumentation.blockUploaded(requestLatency);
        }
    } else if (currentResult.getStatusCode() == HttpURLConnection.HTTP_PARTIAL
            && connection.getRequestMethod().equalsIgnoreCase("GET")) {
        // If it's a GET with an HTTP_PARTIAL status then it's a successful
        // block download.
        long length = getResponseContentLength(connection);
        if (length > 0) {
            blockUploadGaugeUpdater.blockDownloaded(currentResult.getStartDate(), currentResult.getStopDate(),
                    length);
            instrumentation.rawBytesDownloaded(length);
            instrumentation.blockDownloaded(requestLatency);
        }
    }
}

From source file:com.adaptris.http.HttpClientTransport.java

/**
 * Is the HTTP response code considered to be a success.
 * <p>/*from ww  w  .ja v  a2 s.  c o m*/
 * There are 7 possible HTTP codes that signify success or partial success :-
 * <code>200,201,202,203,204,205,206</code>
 * </p>
 * 
 * @return true if the transaction was successful.
 */
private boolean wasSuccessful(HttpSession session) {

    boolean rc = false;
    switch (session.getResponseLine().getResponseCode()) {
    case HttpURLConnection.HTTP_ACCEPTED:
    case HttpURLConnection.HTTP_CREATED:
    case HttpURLConnection.HTTP_NO_CONTENT:
    case HttpURLConnection.HTTP_NOT_AUTHORITATIVE:
    case HttpURLConnection.HTTP_OK:
    case HttpURLConnection.HTTP_PARTIAL:
    case HttpURLConnection.HTTP_RESET: {
        rc = true;
        break;
    }
    default: {
        rc = false;
        break;
    }
    }
    return rc;
}

From source file:com.arcbees.vcs.AbstractVcsApi.java

private HttpResponse doExecuteRequest(HttpClientWrapper httpClient, HttpUriRequest request,
        Credentials credentials) throws IOException {
    includeAuthentication(request, credentials);
    setDefaultHeaders(request);//w ww  . j av  a 2s.c  o m

    HttpResponse httpResponse = httpClient.execute(request);
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    if (statusCode != HttpURLConnection.HTTP_OK && statusCode != HttpURLConnection.HTTP_CREATED) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        httpResponse.getEntity().writeTo(outputStream);
        String json = outputStream.toString(CharEncoding.UTF_8);
        throw new UnexpectedHttpStatusException(statusCode,
                "Failed to complete request. Status: " + httpResponse.getStatusLine() + '\n' + json);
    }

    return httpResponse;
}

From source file:i5.las2peer.services.todolist.Todolist.java

/**
 * //from  w ww  .  j a v  a2s  .  com
 * createData
 * 
 * 
 * @return HttpResponse
 * 
 */
@POST
@Path("/data/{name}")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "responseCreateData") })
@ApiOperation(value = "createData", notes = "")
public HttpResponse createData(@PathParam("name") String name) {
    Connection conn = null;
    try {

        conn = dbm.getConnection();
        PreparedStatement stmt = conn
                .prepareStatement("INSERT INTO gamificationCAE.todolist (name) VALUES (?)");
        stmt.setString(1, name);

        stmt.executeUpdate();

        return new HttpResponse(name + " is added!", HttpURLConnection.HTTP_OK);

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

        return new HttpResponse("Database connection error", HttpURLConnection.HTTP_INTERNAL_ERROR);
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitStatusTest.java

@Test
public void testStatusAdded() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project/folder metadata
        WebRequest request = getGetRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject folder = new JSONObject(response.getText());

        String fileName = "new.txt";
        request = getPostFilesRequest(folder.getString(ProtocolConstants.KEY_LOCATION),
                getNewFileJSON(fileName).toString(), fileName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        // git section for the new file
        JSONObject newFile = getChild(folder, "new.txt");

        // "git add {path}"
        addFile(newFile);//from w  ww .  j ava 2 s  .  c o m

        // git section for the folder
        JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
        gitSection.getString(GitConstants.KEY_INDEX);
        String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS);

        assertStatus(new StatusResult().setAddedNames(fileName), gitStatusUri);
    }
}