Example usage for org.apache.commons.httpclient HttpStatus SC_CREATED

List of usage examples for org.apache.commons.httpclient HttpStatus SC_CREATED

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_CREATED.

Prototype

int SC_CREATED

To view the source code for org.apache.commons.httpclient HttpStatus SC_CREATED.

Click Source Link

Document

<tt>201 Created</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:org.n52.wps.io.datahandler.generator.GeoServerUploader.java

private String sendRasterRequest(String target, String request, String method, String username, String password)
        throws HttpException, IOException {
    HttpClient client = new HttpClient();
    EntityEnclosingMethod requestMethod = null;
    if (method.equalsIgnoreCase("POST")) {
        requestMethod = new PostMethod(target);
        requestMethod.setRequestHeader("Content-type", "application/xml");
    }//ww w  .j a  v  a2  s . c o m
    if (method.equalsIgnoreCase("PUT")) {
        requestMethod = new PutMethod(target);
        requestMethod.setRequestHeader("Content-type", "text/plain");

    }

    requestMethod.setRequestBody(request);

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    client.getState().setCredentials(null, null, creds);

    int statusCode = client.executeMethod(requestMethod);

    if (!((statusCode == HttpStatus.SC_OK) || (statusCode == HttpStatus.SC_CREATED))) {
        System.err.println("Method failed: " + requestMethod.getStatusLine());
    }

    // Read the response body.
    byte[] responseBody = requestMethod.getResponseBody();
    return new String(responseBody);
}

From source file:org.n52.wps.io.datahandler.generator.GeoServerUploader.java

private String sendShpRequest(String target, InputStream request, String method, String username,
        String password) throws HttpException, IOException {
    HttpClient client = new HttpClient();
    EntityEnclosingMethod requestMethod = null;
    if (method.equalsIgnoreCase("POST")) {
        requestMethod = new PostMethod(target);
        requestMethod.setRequestHeader("Content-type", "text/xml");
    }//w  w w  .  j  av  a 2 s .c o  m
    if (method.equalsIgnoreCase("PUT")) {
        requestMethod = new PutMethod(target);
        requestMethod.setRequestHeader("Content-type", "application/zip");

    }

    requestMethod.setRequestBody(request);

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    client.getState().setCredentials(null, null, creds);

    int statusCode = client.executeMethod(requestMethod);

    if (!((statusCode == HttpStatus.SC_OK) || (statusCode == HttpStatus.SC_CREATED))) {
        System.err.println("Method failed: " + requestMethod.getStatusLine());
    }

    // Read the response body.
    byte[] responseBody = requestMethod.getResponseBody();
    return new String(responseBody);
}

From source file:org.nuxeo.ecm.webdav.WebDavClientTest.java

@Test
public void testCreateFolder() throws Exception {
    String name = "newfolder";

    DavMethod method = new MkColMethod(ROOT_URI + name);
    int status = client.executeMethod(method);
    assertEquals(HttpStatus.SC_CREATED, status);

    // check using Nuxeo Core APIs
    session.save(); // process invalidations
    PathRef pathRef = new PathRef("/workspaces/workspace/" + name);
    assertTrue(session.exists(pathRef));
    DocumentModel doc = session.getDocument(pathRef);
    assertEquals("Folder", doc.getType());
    assertEquals(name, doc.getTitle());/*from   ww w . j ava 2 s. c o  m*/
}

From source file:org.nuxeo.ecm.webdav.WebDavClientTest.java

protected void doTestPutFile(String name, byte[] bytes, String mimeType, String expectedType) throws Exception {
    InputStream is = new ByteArrayInputStream(bytes);
    PutMethod method = new PutMethod(ROOT_URI + name);
    method.setRequestEntity(new InputStreamRequestEntity(is, bytes.length, mimeType));
    int status = client.executeMethod(method);
    assertEquals(HttpStatus.SC_CREATED, status);

    // check using Nuxeo Core APIs
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();
    PathRef pathRef = new PathRef("/workspaces/workspace/" + name);
    assertTrue(session.exists(pathRef));
    DocumentModel doc = session.getDocument(pathRef);
    assertEquals(expectedType, doc.getType());
    assertEquals(name, doc.getTitle());/* www .  j  ava  2  s  .c  o m*/
    BlobHolder bh = doc.getAdapter(BlobHolder.class);
    assertNotNull(bh);
    Blob blob = bh.getBlob();
    assertNotNull(blob);
    assertEquals(bytes.length, blob.getLength());
    assertEquals(mimeType, blob.getMimeType());
    assertArrayEquals(bytes, blob.getByteArray());
}

From source file:org.opencastproject.adminui.endpoint.BlacklistsEndpointTest.java

@Test
public void testPostBlacklist() throws ParseException, IOException {
    given().log().all().expect().statusCode(HttpStatus.SC_BAD_REQUEST).when().post(rt.host("/"));
    given().formParam("start", "123").log().all().expect().statusCode(HttpStatus.SC_BAD_REQUEST).when()
            .post(rt.host("/"));
    given().formParam("start", "2014-05-11T13:35:20Z").formParam("end", "2014-05-11T13:40:00Z")
            .formParam("type", "test").log().all().expect().statusCode(HttpStatus.SC_BAD_REQUEST).when()
            .post(rt.host("/"));
    given().formParam("start", "2014-05-11T13:35:20Z").formParam("end", "2014-05-11T13:40:00Z")
            .formParam("type", "person").formParam("blacklistedId", 0).log().all().expect()
            .statusCode(HttpStatus.SC_NOT_FOUND).when().post(rt.host("/"));
    // Start time after end time should be a bad request.
    given().formParam("start", "2016-05-11T13:35:20Z").formParam("end", "2014-05-11T13:40:00Z")
            .formParam("type", "person").formParam("blacklistedId", 5).log().all().expect()
            .statusCode(HttpStatus.SC_BAD_REQUEST).when().post(rt.host("/")).asString();
    String responseString = given().formParam("start", "2014-05-11T13:35:20Z")
            .formParam("end", "2014-05-11T13:40:00Z").formParam("type", "person").formParam("blacklistedId", 5)
            .log().all().expect().statusCode(HttpStatus.SC_CREATED).when().post(rt.host("/")).asString();

    JSONObject responseJson = (JSONObject) parser.parse(responseString);
    Assert.assertNotNull(responseJson);/*w w  w .j  av  a 2  s .co m*/
    long id = Long.parseLong(responseJson.get("id").toString());
    Assert.assertEquals(27L, id);
    Assert.assertEquals("2014-05-11T13:35:20Z", responseJson.get("start"));
    Assert.assertEquals("2014-05-11T13:40:00Z", responseJson.get("end"));

    responseString = given().formParam("start", "2014-05-11T13:35:20Z").formParam("end", "2014-05-11T13:40:00Z")
            .formParam("type", "person").formParam("blacklistedId", 7).log().all().expect()
            .statusCode(HttpStatus.SC_CREATED).when().post(rt.host("/")).asString();

    responseJson = (JSONObject) parser.parse(responseString);
    Assert.assertNotNull(responseJson);
    id = Long.parseLong(responseJson.get("id").toString());
    Assert.assertEquals(27L, id);
    Assert.assertEquals("2014-05-11T13:35:20Z", responseJson.get("start"));
    Assert.assertEquals("2014-05-11T13:40:00Z", responseJson.get("end"));
}

From source file:org.openo.nfvo.monitor.dac.util.APIHttpClient.java

@SuppressWarnings({ "resource" })
public static String doPost2Str(String url, JSONObject json, String token) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    String response = null;//from w ww.j  a  v a2  s .co  m
    try {
        if (null != json) {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json"); // set contentType
            post.setEntity(s);
        }
        if (!Global.isEmpty(token)) {
            post.addHeader("X-Auth-Token", token);
        }
        HttpResponse res = client.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                || res.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            String result = EntityUtils.toString(res.getEntity());
            logger.info("post result is :{}", result);
            if (!Global.isEmpty(result)) {
                response = result;
            } else {
                response = null;
            }
        }
    } catch (Exception e) {
        logger.error("Exception", e);
    }
    return response;
}

From source file:org.openo.nfvo.monitor.dac.util.APIHttpClient.java

@SuppressWarnings({ "resource" })
public static JSONObject doPost(String url, JSONObject json, String token) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    JSONObject response = null;/*  w ww. ja va2 s.  c  o  m*/
    try {
        if (null != json) {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
        }
        if (!Global.isEmpty(token)) {
            post.addHeader("X-Auth-Token", token);
        }
        HttpResponse res = client.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                || res.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            String result = EntityUtils.toString(res.getEntity());
            logger.info("post result is :{}", result);
            if (!Global.isEmpty(result)) {
                response = JSONObject.fromObject(result);
            } else {
                response = null;
            }
        }
    } catch (Exception e) {
        logger.error("Exception", e);
    }
    return response;
}

From source file:org.openo.nfvo.monitor.umc.util.APIHttpClient.java

@SuppressWarnings({ "resource" })
public static String doPost2Str(String url, JSONObject json, String token) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    String response = null;/*from  w w w  . jav a  2  s.  c o  m*/
    try {
        if (null != json) {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json"); // set contentType
            post.setEntity(s);
        }
        if (!Global.isEmpty(token)) {
            post.addHeader("X-Auth-Token", token);
        }
        HttpResponse res = client.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                || res.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            String result = EntityUtils.toString(res.getEntity());
            if (!Global.isEmpty(result)) {
                response = result;
            } else {
                response = null;
            }
        }
    } catch (Exception e) {
        logger.error("Exception", e);
    }
    return response;
}

From source file:org.openo.nfvo.vnfmadapter.service.adapter.impl.AdapterResourceManager.java

/**
 * Upload vnfpackage<br>/*w w  w.ja v a2s  .c om*/
 *
 * @param vnfpackage
 * @param vnfmurl
 * @param conntoken
 * @return
 * @since NFVO 0.5
 */
public JSONObject upload(JSONObject vnfpackage, String vnfmurl, String conntoken) {
    JSONObject resultObj = new JSONObject();
    HttpMethod httpMethodVnf = null;

    try {
        httpMethodVnf = new HttpRequests.Builder(Constant.CERTIFICATE)
                .setUrl(vnfmurl.trim(), UrlConstant.URL_VNFPACKAGE_POST).setParams(vnfpackage.toString())
                .addHeader(Constant.HEADER_AUTH_TOKEN, conntoken).post().execute();

        int statusCodeUp = httpMethodVnf.getStatusCode();

        String resultUp = httpMethodVnf.getResponseBodyAsString();

        if (statusCodeUp == HttpStatus.SC_CREATED || statusCodeUp == HttpStatus.SC_OK) {
            LOG.info(
                    "uploadVNFPackage upload VNF package successful, code:" + statusCodeUp + " re:" + resultUp);
            resultObj = JSONObject.fromObject(resultUp);
            resultObj.put(Constant.RETCODE, statusCodeUp);
        } else {
            LOG.error("uploadVNFPackage upload VNF package failed, code:" + statusCodeUp + " re:" + resultUp);
            resultObj.put(Constant.RETCODE, statusCodeUp);
            resultObj.put("data", "upload VNF package failed, code:" + statusCodeUp + " re:" + resultUp);
            return resultObj;
        }
    } catch (JSONException e) {
        LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage upload VNF package JSONException e={}.", e);
        resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR);
        resultObj.put("reason", "upload VNF package failed and JSONException." + e.getMessage());
        return resultObj;
    } catch (VnfmException e) {
        LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage upload VNF package VnfmException e={}.", e);
        resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR);
        resultObj.put("reason", "upload VNF package failed and VnfmException." + e.getMessage());
        return resultObj;
    } catch (IOException e) {
        LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage upload VNF package IOException e={}.", e);
        resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR);
        resultObj.put("reason", "upload VNF package failed and IOException." + e.getMessage());
        return resultObj;
    }
    return resultObj;
}

From source file:org.openo.nfvo.vnfmadapter.service.csm.connect.ConnectMgrVnfm.java

/**
 * Make connection/*from   ww w .j  av a  2 s.c o  m*/
 * <br>
 *
 * @param vnfmObj
 * @return
 * @since  NFVO 0.5
 */
public int connect(JSONObject vnfmObj, String authModel) {
    LOG.info("function=connect, msg=enter connect function.");

    ConnectInfo info = new ConnectInfo(vnfmObj.getString("url"), vnfmObj.getString("userName"),
            vnfmObj.getString("password"), authModel);
    HttpMethod httpMethod = null;
    int statusCode = Constant.INTERNAL_EXCEPTION;

    try {
        httpMethod = new HttpRequests.Builder(info.getAuthenticateMode())
                .setUrl(info.getUrl(), ParamConstants.CSM_AUTH_CONNECT)
                .setParams(String.format(ParamConstants.GET_TOKENS_V2, info.getUserName(), info.getUserPwd()))
                .post().execute();
        statusCode = httpMethod.getStatusCode();

        String result = httpMethod.getResponseBodyAsString();
        LOG.info("connect result:" + result);
        if (statusCode == HttpStatus.SC_CREATED) {
            JSONObject accessObj = JSONObject.fromObject(result);
            JSONObject tokenObj = accessObj.getJSONObject("token");
            Header header = httpMethod.getResponseHeader("accessSession");
            setAccessSession(header.getValue());
            setRoaRand(tokenObj.getString("roa_rand"));
            statusCode = HttpStatus.SC_OK;
        } else {
            LOG.error("connect fail, code:" + statusCode + " re:" + result);
        }

    } catch (JSONException e) {
        LOG.error("function=connect, msg=connect JSONException e={}.", e);
    } catch (VnfmException e) {
        LOG.error("function=connect, msg=connect VnfmException e={}.", e);
    } catch (IOException e) {
        LOG.error("function=connect, msg=connect IOException e={}.", e);
    } finally {
        clearCSMPwd(info);
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
    return statusCode;

}