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:com.netflix.genie.server.resources.ClusterConfigResource.java

/**
 * Create cluster configuration.//from w  ww .  j  a  v  a2  s  .c  o  m
 *
 * @param cluster contains the cluster information to create
 * @return The created cluster
 * @throws GenieException For any error
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create a cluster", notes = "Create a cluster from the supplied information.", response = Cluster.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Created", response = Cluster.class),
        @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = "A cluster with the supplied id already exists"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Response createCluster(
        @ApiParam(value = "The cluster to create.", required = true) final Cluster cluster)
        throws GenieException {
    LOG.info("Called to create new cluster " + cluster);
    final Cluster createdCluster = this.clusterConfigService.createCluster(cluster);
    return Response.created(this.uriInfo.getAbsolutePathBuilder().path(createdCluster.getId()).build())
            .entity(createdCluster).build();
}

From source file:org.apache.hadoop.hdfs.server.namenode.web.resources.TestWebHdfsCreatePermissions.java

@Test
public void testCreateFile666Permissions() throws Exception {
    testPermissions(HttpURLConnection.HTTP_CREATED, "rw-rw-rw-", "/test-file", "op=CREATE&permission=666");
}

From source file:com.netflix.genie.server.resources.ApplicationConfigResource.java

/**
 * Create an Application./*from w  w  w.java  2 s .  c om*/
 *
 * @param app The application to create
 * @return The created application configuration
 * @throws GenieException For any error
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create an application", notes = "Create an application from the supplied information.", response = Application.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Application created successfully.", response = Application.class),
        @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = "An application with the supplied id already exists"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "A precondition failed"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Response createApplication(
        @ApiParam(value = "The application to create.", required = true) final Application app)
        throws GenieException {
    LOG.info("Called to create new application");
    final Application createdApp = this.applicationConfigService.createApplication(app);
    return Response.created(this.uriInfo.getAbsolutePathBuilder().path(createdApp.getId()).build())
            .entity(createdApp).build();
}

From source file:com.netflix.genie.server.resources.JobResource.java

/**
 * Submit a new job.// www.j  av  a  2 s. c  o  m
 *
 * @param job request object containing job info element for new job
 * @return The submitted job
 * @throws GenieException For any error
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Submit a job", notes = "Submit a new job to run to genie", response = Job.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Created", response = Job.class),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"),
        @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = "Job with ID already exists."),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Precondition Failed"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Response submitJob(@ApiParam(value = "Job object to run.", required = true) final Job job)
        throws GenieException {
    if (job == null) {
        throw new GenieException(HttpURLConnection.HTTP_PRECON_FAILED, "No job entered. Unable to submit.");
    }
    LOG.info("Called to submit job: " + job);

    // get client's host from the context
    String clientHost = this.httpServletRequest.getHeader(FORWARDED_FOR_HEADER);
    if (clientHost != null) {
        clientHost = clientHost.split(",")[0];
    } else {
        clientHost = this.httpServletRequest.getRemoteAddr();
    }

    // set the clientHost, if it is not overridden already
    if (StringUtils.isNotBlank(clientHost)) {
        LOG.debug("called from: " + clientHost);
        job.setClientHost(clientHost);
    }

    final Job createdJob = this.executionService.submitJob(job);
    return Response.created(this.uriInfo.getAbsolutePathBuilder().path(createdJob.getId()).build())
            .entity(createdJob).build();
}

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

private String attachWithOctetStream(String entityUrl, byte[] fileData, String filename) throws Exception {

    Map<String, String> requestHeaders = new HashMap<String, String>();
    requestHeaders.put("Slug", filename);
    requestHeaders.put("Content-Type", "application/octet-stream");

    ALMResponse response = httpPost(entityUrl + "/attachments", fileData, requestHeaders);

    if (response.getStatusCode() != HttpURLConnection.HTTP_CREATED) {
        throw new Exception(response.toString());
    }/*from w w  w  .j a  v  a 2  s. c  om*/

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

From source file:org.eclipse.orion.server.tests.servlets.xfer.TransferTest.java

private void doImport(File source, long length, String location, String contentType)
        throws FileNotFoundException, IOException, SAXException {
    if (source.length() == 0) {
        PutMethodWebRequest put = new PutMethodWebRequest(location, new ByteArrayInputStream(new byte[0], 0, 0),
                contentType);/*from w w  w. j a v a  2 s.  c o m*/
        put.setHeaderField("Content-Range", "bytes 0-0/0");
        put.setHeaderField("Content-Length", "0");
        put.setHeaderField("Content-Type", "application/zip");
        setAuthentication(put);
        WebResponse putResponse = webConversation.getResponse(put);
        assertEquals(HttpURLConnection.HTTP_CREATED, putResponse.getResponseCode());
        return;
    }
    //repeat putting chunks until done
    byte[] chunk = new byte[64 * 1024];
    InputStream in = new BufferedInputStream(new FileInputStream(source));
    int chunkSize = 0;
    int totalTransferred = 0;
    while ((chunkSize = in.read(chunk, 0, chunk.length)) > 0) {
        byte[] content = getContent(chunk, chunkSize, contentType);
        PutMethodWebRequest put = new PutMethodWebRequest(location, new ByteArrayInputStream(content),
                contentType);
        put.setHeaderField("Content-Range",
                "bytes " + totalTransferred + "-" + (totalTransferred + chunkSize - 1) + "/" + length);
        put.setHeaderField("Content-Length", "" + content.length);
        put.setHeaderField("Content-Type", contentType);
        setAuthentication(put);
        totalTransferred += chunkSize;
        WebResponse putResponse = webConversation.getResponse(put);
        if (totalTransferred == length) {
            assertEquals(HttpURLConnection.HTTP_CREATED, putResponse.getResponseCode());
        } else {
            assertEquals(308, putResponse.getResponseCode());//308 = Permanent Redirect
            String range = putResponse.getHeaderField("Range");
            assertEquals("bytes 0-" + (totalTransferred - 1), range);
        }
    }
    in.close();
}

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 sendPostRequest(String url, String bodytext) throws Exception {
    String sresponse;//from   w  w w.j a v  a  2s. c  o m

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

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

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

    HttpResponse response = httpclient.execute(httppost);

    // 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:hanulhan.cas.client.CasRestActions.java

public String doLoginCasRest() {

    jsonStatus = new JsonStatus();
    String myUrlParameters = "username=uhansen01&password=Ava030374Lon_";
    CookieHandler.setDefault(new CookieManager());
    StringBuilder myResult;// w ww  . j  ava2s .  co m
    String myServiceTicketUrl = null;
    String myTgt = "";
    String myServiceTicket = "";
    List<NameValuePair> postParams = new ArrayList<>();
    HttpResponse myResponse;

    // GET the TGT
    try {
        myResponse = sendPost(CAS_SERVER_URL + "/v1/tickets?" + myUrlParameters, postParams);
        if (myResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED) {
            myResult = getHttpResponseResult(myResponse);
            if (myResult != null && myResult.length() > 0) {
                myServiceTicketUrl = getServiceTicketUrl(myResult.toString());
                if (myServiceTicketUrl != null && myServiceTicketUrl.length() > 0) {
                    LOGGER.log(Level.INFO, "ServiceTicketURL: " + myServiceTicketUrl);
                    myTgt = getTGT(myServiceTicketUrl);
                    if (myTgt != null && myTgt.length() > 0) {
                        LOGGER.log(Level.INFO, "TGT: " + myTgt);
                    }
                }
            } else {
                LOGGER.log(Level.ERROR, "Status Code: " + myResponse.getStatusLine().getStatusCode());
            }
        }
    } catch (Exception ex) {
        LOGGER.log(Level.ERROR, ex);
    }

    // Get the ServiceTicket
    try {
        if (myTgt != null && myTgt.length() > 0) {
            postParams.add(new BasicNameValuePair("service", CAS_SERVICE));
            myResponse = sendPost(myServiceTicketUrl, postParams);
            if (myResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
                myServiceTicket = getHttpResponseResult(myResponse).toString();
                LOGGER.log(Level.INFO, "ServiceTicket: " + myServiceTicket);
                redirectUrl = GET_URL + "?authServiceTicket=" + myServiceTicket + "&authService=" + CAS_SERVICE;
                LOGGER.log(Level.INFO, "ServiceURL: " + redirectUrl);
            }
        }
    } catch (Exception ex) {
        LOGGER.log(Level.ERROR, ex);
    }

    return SUCCESS;

}

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

/**
 * Create a file in a project on the Orion server for the test user.
 * //from w  ww  .  jav a  2  s  . c  om
 * @param webConversation
 * @param login
 * @param password
 * @param projectName
 * @return
 * @throws IOException
 * @throws JSONException
 * @throws URISyntaxException
 * @throws SAXException 
 */
protected int createFile(WebConversation webConversation, String login, String password, String project)
        throws IOException, JSONException, URISyntaxException, SAXException {
    assertEquals(HttpURLConnection.HTTP_OK, login(webConversation, login, password));

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("Directory", "false");
    jsonObject.put("Name", "file.json");
    jsonObject.put("LocalTimeStamp", "0");
    String parent = "/file/" + getWorkspaceId(login) + "/" + project + "/folder/";
    WebRequest request = new PostMethodWebRequest(getOrionServerURI(parent),
            IOUtilities.toInputStream(jsonObject.toString()), "application/json");
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    request.setHeaderField(ProtocolConstants.HEADER_SLUG, "file.json");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

    String file = "/file/" + getWorkspaceId(login) + "/" + project + "/folder/file.json";
    jsonObject = new JSONObject();
    jsonObject.put("Description", "This is a simple JSON file");
    String fileContent = jsonObject.toString(4);
    request = new PutMethodWebRequest(getOrionServerURI(file), IOUtilities.toInputStream(fileContent),
            "application/json");
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    System.out.println("Created File: " + parent + "file.json");
    return response.getResponseCode();
}