Example usage for org.apache.commons.httpclient.methods PostMethod PostMethod

List of usage examples for org.apache.commons.httpclient.methods PostMethod PostMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PostMethod PostMethod.

Prototype

public PostMethod(String paramString) 

Source Link

Usage

From source file:com.twinsoft.convertigo.engine.util.RemoteAdmin.java

public void login(String username, String password) throws RemoteAdminException, EngineException {
    PostMethod loginMethod = null;//from   ww  w  . j av  a2  s .  c om

    try {
        String loginServiceURL = (bHttps ? "https" : "http") + "://" + serverBaseUrl
                + "/admin/services/engine.Authenticate";

        Protocol myhttps = null;

        hostConfiguration = httpClient.getHostConfiguration();

        if (bHttps) {
            if (bTrustAllCertificates) {
                ProtocolSocketFactory socketFactory = new EasySSLProtocolSocketFactory();
                myhttps = new Protocol("https", socketFactory, serverPort);
                Protocol.registerProtocol("https", myhttps);

                hostConfiguration.setHost(host, serverPort, myhttps);
            }
        }

        if (("").equals(username) || username == null) {
            throw new RemoteAdminException(
                    "Unable to connect to the Convertigo server: \"Server administrator\" field is empty.");
        }
        if (("").equals(password) || password == null) {
            throw new RemoteAdminException(
                    "Unable to connect to the Convertigo server: \"Password\" field is empty.");
        }

        URL url = new URL(loginServiceURL);

        HttpState httpState = new HttpState();
        httpClient.setState(httpState);
        // Proxy configuration
        Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);

        loginMethod = new PostMethod(loginServiceURL);
        loginMethod.addParameter("authType", "login");
        loginMethod.addParameter("authUserName", username);
        loginMethod.addParameter("authPassword", password);

        int returnCode = httpClient.executeMethod(loginMethod);
        String httpResponse = loginMethod.getResponseBodyAsString();

        if (returnCode == HttpStatus.SC_OK) {
            Document domResponse;
            try {
                DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                domResponse = parser.parse(new InputSource(new StringReader(httpResponse)));
                domResponse.normalize();

                NodeList nodeList = domResponse.getElementsByTagName("error");

                if (nodeList.getLength() != 0) {
                    throw new RemoteAdminException(
                            "Unable to connect to the Convertigo server: wrong username or password.");
                }
            } catch (ParserConfigurationException e) {
                throw new RemoteAdminException("Unable to parse the Convertigo server response: \n"
                        + e.getMessage() + ".\n" + "Received response: " + httpResponse);
            } catch (IOException e) {
                throw new RemoteAdminException(
                        "An unexpected error has occured during the Convertigo server login.\n"
                                + "(IOException) " + e.getMessage() + "\n" + "Received response: "
                                + httpResponse,
                        e);
            } catch (SAXException e) {
                throw new RemoteAdminException("Unable to parse the Convertigo server response: "
                        + e.getMessage() + ".\n" + "Received response: " + httpResponse);
            }
        } else {
            decodeResponseError(httpResponse);
        }
    } catch (HttpException e) {
        throw new RemoteAdminException("An unexpected error has occured during the Convertigo server login.\n"
                + "Cause: " + e.getMessage(), e);
    } catch (UnknownHostException e) {
        throw new RemoteAdminException(
                "Unable to find the Convertigo server (unknown host): " + e.getMessage());
    } catch (IOException e) {
        String message = e.getMessage();

        if (message.indexOf("unable to find valid certification path") != -1) {
            throw new RemoteAdminException(
                    "The SSL certificate of the Convertigo server is not trusted.\nPlease check the 'Trust all certificates' checkbox.");
        } else
            throw new RemoteAdminException(
                    "Unable to reach the Convertigo server: \n" + "(IOException) " + e.getMessage(), e);
    } catch (GeneralSecurityException e) {
        throw new RemoteAdminException(
                "Unable to reach the Convertigo server: \n" + "(GeneralSecurityException) " + e.getMessage(),
                e);
    } finally {
        Protocol.unregisterProtocol("https");
        if (loginMethod != null)
            loginMethod.releaseConnection();
    }
}

From source file:cn.vlabs.duckling.aone.client.impl.EmailAttachmentSenderImpl.java

/**
 * ?DDL/*from w  w  w. j  a va  2  s  .  c  o m*/
 * @param email
 * @param attachment
 * @return
 */
private AttachmentPushResult validateExsit(String email, int teamId, AttachmentInfo attachment) {
    if (attachment.getCoverFlag()) {
        return null;
    }
    PostMethod method = new PostMethod(getDDLValidateIp());
    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
    method.addParameter(FILENAME, attachment.getFileName());
    method.addParameter(EMAIL, email);
    method.addParameter(FILESIZE, attachment.getFileSize() + "");
    method.addParameter(FILEID, attachment.getFileId());
    method.addParameter(TEAMID, teamId + "");
    AttachmentPushResult result = new AttachmentPushResult();
    result.setFileName(attachment.getFileName());
    try {
        int status = ddlClient.executeMethod(method);
        if (status >= 200 && status < 300) {
            String responseString = method.getResponseBodyAsString();
            return dealValidateResult(responseString);
        } else {
            result.setStatusCode(AttachmentPushResult.NETWORK_ERROR);
            result.setMessage("DDL?" + status + "");
            return result;
        }
    } catch (HttpException e) {
        result.setStatusCode(AttachmentPushResult.NETWORK_ERROR);
        result.setMessage("DDL?" + e.getMessage() + "");
        return result;
    } catch (IOException e) {
        result.setStatusCode(AttachmentPushResult.IO_ERROR);
        result.setMessage("ddlIo");
        e.printStackTrace();
        return result;
    } finally {
        method.releaseConnection();
    }
}

From source file:com.tribune.uiautomation.testscripts.Photo.java

public boolean create() throws JSONException {
    checkValidStateForCreate();// w  w  w  .j a v a 2  s  .c om

    PostMethod post = new PostMethod(constructCreateUrl());

    try {
        setRequestHeaders(post);
        setParameters(post);

        HttpClient client = new HttpClient();
        int status = client.executeMethod(post);

        log.debug("Photo Service create return status: " + post.getStatusLine());
        if (status == HttpStatus.SC_CREATED) {
            processResponse(this, post.getResponseBodyAsStream());
            persisted = true;
            return true;
        }
    } catch (HttpException e) {
        log.fatal("Fatal protocol violation: " + e.getMessage(), e);
    } catch (IOException e) {
        log.fatal("Fatal transport error: " + e.getMessage(), e);
    } finally {
        // Release the connection.
        post.releaseConnection();
    }

    return false;
}

From source file:edu.wisc.ssec.mcidasv.supportform.Submitter.java

/**
 * Attempts to {@code POST} to {@code url} using the information from 
 * {@code form}.//from   ww w  .j  a  v  a 2s. c  om
 * 
 * @param url URL that'll accept the {@code POST}. Typically 
 * {@link #requestUrl}.
 * @param form The {@link SupportForm} that contains the data to use in the
 * support request.
 * 
 * @return Big honkin' object that contains the support request.
 */
private static PostMethod buildPostMethod(String url, SupportForm form) {
    PostMethod method = new PostMethod(url);

    List<Part> parts = new ArrayList<Part>();
    parts.add(new StringPart("form_data[fromName]", form.getUser()));
    parts.add(new StringPart("form_data[email]", form.getEmail()));
    parts.add(new StringPart("form_data[organization]", form.getOrganization()));
    parts.add(new StringPart("form_data[subject]", form.getSubject()));
    parts.add(new StringPart("form_data[description]", form.getDescription()));
    parts.add(new StringPart("form_data[submit]", ""));
    parts.add(new StringPart("form_data[p_version]", "p_version=ignored"));
    parts.add(new StringPart("form_data[opsys]", "opsys=ignored"));
    parts.add(new StringPart("form_data[hardware]", "hardware=ignored"));
    parts.add(new StringPart("form_data[cc_user]", Boolean.toString(form.getSendCopy())));

    // attach the files the user has explicitly attached.
    if (form.hasAttachmentOne()) {
        parts.add(buildRealFilePart("form_data[att_two]", form.getAttachmentOne()));
    }
    if (form.hasAttachmentTwo()) {
        parts.add(buildRealFilePart("form_data[att_three]", form.getAttachmentTwo()));
    }
    // if the user wants, attach an XML bundle of the state
    if (form.canBundleState() && form.getSendBundle()) {
        parts.add(
                buildFakeFilePart("form_data[att_state]", form.getBundledStateName(), form.getBundledState()));
    }

    // attach system properties
    parts.add(buildFakeFilePart("form_data[att_extra]", form.getExtraStateName(), form.getExtraState()));

    // attach mcidasv.log (if it exists)
    if (form.canSendLog()) {
        parts.add(buildRealFilePart("form_data[att_log]", form.getLogPath()));
    }

    // attach RESOLV.SRV (if it exists)
    if (form.canSendResolvSrv()) {
        parts.add(buildRealFilePart("form_data[att_resolvsrv]", form.getResolvSrvPath()));
    }

    // tack on the contents of runMcV.prefs
    parts.add(buildRealFilePart("form_data[att_prefs]", form.getPrefsPath()));

    Part[] arr = parts.toArray(new Part[0]);
    MultipartRequestEntity mpr = new MultipartRequestEntity(arr, method.getParams());
    method.setRequestEntity(mpr);
    return method;
}

From source file:gr.upatras.ece.nam.fci.uop.UoPGWClient.java

/**
 * It makes a POST towards the gateway//from www .  j  a  v  a  2s  . c  o m
 * @author ctranoris
 * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27
 * @param ptmAlias sets the name of the provider URI, e.g.: uop
 * @param content sets the name of the content; send in utf8
 */
public boolean POSTExecute(String resourceInstance, String ptmAlias, String content) {

    boolean status = false;
    log.info("content body=" + "\n" + content);
    HttpClient client = new HttpClient();
    String tgwcontent = content;

    // resource instance is like uop.rubis_db-6 so we need to make it like
    // this /uop/uop.rubis_db-6
    String ptm = ptmAlias;
    String url = uopGWAddress + "/" + ptm + "/" + resourceInstance;
    log.info("Request: " + url);

    // Create a method instance.
    PostMethod post = new PostMethod(url);
    post.setRequestHeader("User-Agent", userAgent);
    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    // Provide custom retry handler is necessary
    post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    //HttpMethodParams.
    RequestEntity requestEntity = null;
    try {
        requestEntity = new StringRequestEntity(tgwcontent, "application/x-www-form-urlencoded", "utf-8");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    post.setRequestEntity(requestEntity);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(post);

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

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary
        // data
        // print the status and response
        InputStream responseBody = post.getResponseBodyAsStream();

        CopyInputStream cis = new CopyInputStream(responseBody);
        response_stream = cis.getCopy();
        log.info("Response body=" + "\n" + convertStreamToString(response_stream));
        response_stream.reset();

        //         log.info("for address: " + url + " the response is:\n "
        //               + post.getResponseBodyAsString());

        status = true;
    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        return false;
    } finally {
        // Release the connection.
        post.releaseConnection();
    }

    return status;

}

From source file:com.tops.hotelmanager.util.CommonHttpClient.java

private static String executePOSTRequestV1(String url, Map<String, Object> requestData,
        Map<String, String> headerMap, String contentType, int timeOut, int retry) {
    PostMethod post = new PostMethod(url);
    Gson gson = new Gson();
    String errorMsg = "error~Request Failed";
    try {/* w w  w.j  a v a 2  s  .  com*/
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setSoTimeout(timeOut);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut);
        if (requestData == null || requestData.isEmpty()) {
            throw new CustomException("Request data is null");
        }
        if (contentType != null && contentType.equals(CommonHttpClient.CONTENT_TYPE_JSON)) {
            StringRequestEntity requestEntity = new StringRequestEntity(gson.toJson(requestData), contentType,
                    "UTF-8");
            post.setRequestEntity(requestEntity);
        } else {
            // SET REQUEST PARAMETER
            for (Map.Entry<String, Object> entry : requestData.entrySet()) {
                post.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        // SET REQUEST HEADER
        if (headerMap != null) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                post.addRequestHeader(entry.getKey(), entry.getValue());
            }
        }
        int status = client.executeMethod(post);
        // System.out.println("URL:" + url);
        // System.out.println("\n REQUEST HEADERS:");
        // Header[] requestHeaders = post.getRequestHeaders();
        // for (Header header : requestHeaders) {
        // System.out.println(header.getName() + "=" + header.getValue());
        // }
        // System.out.println("\n RESPONSE HEADERS:");
        // Header[] responseHeaders = post.getResponseHeaders();
        // for (Header header : responseHeaders) {
        // System.out.println(header.getName() + "=" + header.getValue());
        // }
        // System.out.println(post.getStatusText());
        // System.out.println(post.getStatusLine().getReasonPhrase());
        // System.out.println(post.getResponseBodyAsString());
        if (status == HttpStatus.SC_OK) {
            return post.getResponseBodyAsString();
        } else if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
            Header header = post.getResponseHeader("Location");
            if (retry != 1) {
                errorMsg = executePOSTRequestV1(header.getValue(), requestData, headerMap, contentType, timeOut,
                        retry++);
            }
        } else {
            errorMsg += ",HttpStatus:" + status;
        }
    } catch (Exception ex) {
        logger.error("executePOSTRequestV1 url: " + url + ", Parameters: " + requestData, ex);
        errorMsg = errorMsg + ":" + ex.getMessage();
    } finally {
        post.releaseConnection();
    }
    return errorMsg;
}

From source file:fr.msch.wissl.server.TestUsers.java

@Test
public void test() throws IOException, JSONException {
    HttpClient client = new HttpClient();

    // check the users and sessions created by TServer
    GetMethod get = new GetMethod(TServer.URL + "users");
    get.addRequestHeader("sessionId", this.user_sessionId);
    client.executeMethod(get);//ww w  .jav  a2s . c  om
    Assert.assertEquals(200, get.getStatusCode());
    JSONObject obj = new JSONObject(get.getResponseBodyAsString());
    JSONArray users = obj.getJSONArray("users");
    Assert.assertEquals(2, users.length());
    for (int i = 0; i < 2; i++) {
        JSONObject u = users.getJSONObject(i);
        String username = u.getString("username");
        if (username.equals(this.user_username)) {
            Assert.assertEquals(this.user_userId, u.getInt("id"));
            Assert.assertEquals(2, u.getInt("auth"));
            Assert.assertEquals(0, u.getInt("downloaded"));
        } else if (username.equals(this.admin_username)) {
            Assert.assertEquals(this.admin_userId, u.getInt("id"));
            Assert.assertEquals(1, u.getInt("auth"));
            Assert.assertEquals(0, u.getInt("downloaded"));
        } else {
            Assert.fail("Unexpected user:" + username);
        }
    }

    JSONArray sessions = obj.getJSONArray("sessions");
    Assert.assertEquals(2, sessions.length());
    for (int i = 0; i < 2; i++) {
        JSONObject s = sessions.getJSONObject(i);
        String username = s.getString("username");
        if (username.equals(this.user_username)) {
            Assert.assertEquals(this.user_userId, s.getInt("user_id"));
            Assert.assertTrue(s.getInt("last_activity") >= 0); // might be 0
            Assert.assertTrue(s.getInt("created_at") >= 0);
            Assert.assertFalse(s.has("origins")); // admin only
            Assert.assertFalse(s.has("last_played_song"));
        }
    }

    // unknown user: 404
    get = new GetMethod(TServer.URL + "user/100");
    get.addRequestHeader("sessionId", this.user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(404, get.getStatusCode());

    // check admin user
    get = new GetMethod(TServer.URL + "user/" + this.admin_userId);
    get.addRequestHeader("sessionId", this.admin_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    JSONObject u = obj.getJSONObject("user");
    Assert.assertEquals(this.admin_userId, u.getInt("id"));
    Assert.assertEquals(this.admin_username, u.getString("username"));
    Assert.assertEquals(1, u.getInt("auth"));
    Assert.assertEquals(0, u.getInt("downloaded"));
    sessions = obj.getJSONArray("sessions");
    Assert.assertEquals(1, sessions.length());
    JSONObject s = sessions.getJSONObject(0);

    Assert.assertEquals(this.admin_userId, s.getInt("user_id"));
    Assert.assertTrue(s.getInt("last_activity") >= 0); // might be 0
    Assert.assertTrue(s.getInt("created_at") > 0);
    Assert.assertTrue(s.has("origins")); // admin only
    Assert.assertFalse(s.has("last_played_song"));
    Assert.assertTrue(obj.getJSONArray("playlists").length() == 0);

    // create a new user with user account: error 401
    PostMethod post = new PostMethod(TServer.URL + "user/add");
    post.addRequestHeader("sessionId", this.user_sessionId);
    post.addParameter("username", "new-user");
    post.addParameter("password", "new-pw");
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // create new user with empty username: err 400
    post = new PostMethod(TServer.URL + "user/add");
    post.addRequestHeader("sessionId", this.admin_sessionId);
    post.addParameter("username", "");
    post.addParameter("password", "new-pw");
    post.addParameter("auth", "1");
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    // create new user with short password: err 400
    post = new PostMethod(TServer.URL + "user/add");
    post.addRequestHeader("sessionId", this.admin_sessionId);
    post.addParameter("username", "new-user");
    post.addParameter("password", "pw");
    post.addParameter("auth", "1");
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    // create new user with invalid auth: err 400
    post = new PostMethod(TServer.URL + "user/add");
    post.addRequestHeader("sessionId", this.admin_sessionId);
    post.addParameter("username", "new-user");
    post.addParameter("password", "pw");
    post.addParameter("auth", "3");
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    int new_userId = -1;
    String new_sessionId = null;
    String new_username = "new-user";
    String new_password = "new-pw";

    // create new user
    post = new PostMethod(TServer.URL + "user/add");
    post.addRequestHeader("sessionId", this.admin_sessionId);
    post.addParameter("username", new_username);
    post.addParameter("password", new_password);
    post.addParameter("auth", "2");
    client.executeMethod(post);
    Assert.assertEquals(200, post.getStatusCode());
    u = new JSONObject(post.getResponseBodyAsString()).getJSONObject("user");
    new_userId = u.getInt("id");
    Assert.assertEquals(new_username, u.getString("username"));
    Assert.assertEquals(2, u.getInt("auth"));

    // check new user 
    get = new GetMethod(TServer.URL + "user/" + new_userId);
    get.addRequestHeader("sessionId", this.user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    Assert.assertTrue(obj.getJSONArray("playlists").length() == 0);
    Assert.assertEquals(0, obj.getJSONArray("sessions").length());

    // login new user
    obj = new JSONObject(this.login(new_username, new_password));
    Assert.assertEquals(new_userId, obj.getInt("userId"));
    new_sessionId = obj.getString("sessionId");

    // check if logged in with /users
    get = new GetMethod(URL + "users");
    get.addRequestHeader("sessionId", new_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    users = obj.getJSONArray("users");
    Assert.assertEquals(3, users.length());
    for (int i = 0; i < 3; i++) {
        u = users.getJSONObject(i);
        String username = u.getString("username");
        if (username.equals(new_username)) {
            Assert.assertEquals(new_userId, u.getInt("id"));
        } else {
            Assert.assertTrue(username.equals(user_username) || username.equals(admin_username));
        }
    }
    sessions = obj.getJSONArray("sessions");
    Assert.assertEquals(3, sessions.length());
    for (int i = 0; i < 3; i++) {
        s = sessions.getJSONObject(i);
        String username = s.getString("username");
        if (username.equals(new_username)) {
            Assert.assertEquals(new_userId, s.getInt("user_id"));
            Assert.assertTrue(s.getInt("last_activity") >= 0); // might be 0
            Assert.assertTrue(s.getInt("created_at") > 0);
            Assert.assertFalse(s.has("origins")); // admin only
            Assert.assertFalse(s.has("last_played_song"));
        } else {
            Assert.assertTrue(username.equals(user_username) || username.equals(admin_username));
        }
    }

    // try to change password without the old password: 401
    post = new PostMethod(URL + "user/password");
    post.addRequestHeader("sessionId", new_sessionId);
    post.addParameter("old_password", "password");
    post.addParameter("new_password", "password2");
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // change password for new user
    post = new PostMethod(URL + "user/password");
    post.addRequestHeader("sessionId", new_sessionId);
    post.addParameter("old_password", new_password);
    new_password = "something else";
    post.addParameter("new_password", new_password);
    client.executeMethod(post);
    Assert.assertEquals(204, post.getStatusCode());

    // logout and relogin with new password
    post = new PostMethod(URL + "logout");
    post.addRequestHeader("sessionId", new_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(204, post.getStatusCode());

    obj = new JSONObject(this.login(new_username, new_password));
    Assert.assertEquals(new_userId, obj.getInt("userId"));
    new_sessionId = obj.getString("sessionId");

    // try to delete an user as user: 401
    post = new PostMethod(URL + "user/remove");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("user_ids[]", "" + new_userId);
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // try to delete no user: 400
    post = new PostMethod(URL + "user/remove");
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    // try to delete admin with admin: 400
    post = new PostMethod(URL + "user/remove");
    post.addRequestHeader("sessionId", admin_sessionId);
    post.addParameter("user_ids[]", "" + admin_userId);
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    // delete both regular users
    post = new PostMethod(URL + "user/remove");
    post.addRequestHeader("sessionId", admin_sessionId);
    post.addParameter("user_ids[]", "" + user_userId);
    post.addParameter("user_ids[]", "" + new_userId);
    client.executeMethod(post);
    Assert.assertEquals(204, post.getStatusCode());

    // check that old sessions do not work anymore
    get = new GetMethod(URL + "users");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(401, get.getStatusCode());

    // check that there is only 1 user
    get = new GetMethod(URL + "users");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    Assert.assertEquals(obj.getJSONArray("users").length(), 1);
    Assert.assertEquals(obj.getJSONArray("sessions").length(), 1);

}

From source file:jp.primecloud.auto.zabbix.ZabbixAccessor.java

protected String post(String jsonRequest) {
    PostMethod postMethod = new PostMethod(apiUrl);
    postMethod.setRequestHeader("Content-Type", "application/json-rpc");
    postMethod.setRequestEntity(new ByteArrayRequestEntity(jsonRequest.getBytes()));

    int status;//from  ww w.  ja v a2 s  .c  o  m
    try {
        status = httpClient.executeMethod(postMethod);
    } catch (HttpException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (status < 200 || status >= 300) {
        String body;
        try {
            body = postMethod.getResponseBodyAsString();
        } catch (Exception ignore) {
            body = "";
        }
        throw new RuntimeException("Reponse Error: status=" + status + ", body=" + body);
    }

    String jsonResponse;
    try {
        jsonResponse = postMethod.getResponseBodyAsString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return jsonResponse;
}

From source file:com.honnix.yaacs.adapter.http.TestACHttpServer.java

public void testGetACList() {
    Map<String, String> paramMap = null;
    String sessionId = null;/*from  w  w w.j a  v a2 s .c o m*/

    try {
        paramMap = login();
        sessionId = paramMap.get(ACHttpConstant.SESSION_ID_KEY);

        assertNotNull(RESPONSE_ERROR, sessionId);
    } catch (HttpException e) {
        fail(FORCED_FAILURE);
    } catch (IOException e) {
        fail(FORCED_FAILURE);
    }

    StringBuilder sb = new StringBuilder(HOST).append(ACHttpPropertiesConstant.HTTP_LISTENING_PORT)
            .append(ACHttpPropertiesConstant.HTTP_AC_REQUEST_URL);
    postMethod = new PostMethod(sb.toString());

    postMethod.setRequestHeader(CONTENT_TYPE_KEY, CONTENT_TYPE);

    try {
        StringRequestEntity requestEntity = new StringRequestEntity(
                ACHttpBodyUtil.buildGetACListByAlbumRequestBody(sessionId, "Honnix", "2008", "Shadow of Light"),
                null, ACHttpPropertiesConstant.HTTP_CHARSET);

        postMethod.setRequestEntity(requestEntity);

        int statusCode = client.executeMethod(postMethod);

        assertEquals(SHOULD_BE_OK, HttpStatus.SC_OK, statusCode);

        String response = postMethod.getResponseBodyAsString();

        assertTrue(RESPONSE_ERROR, response.startsWith(SUCCESS_RESP));

        byte[] byteArray = new byte[3];

        byteArray[0] = 97;
        byteArray[1] = 98;
        byteArray[2] = 99;
        assertNotSame(RESPONSE_ERROR, -1, response.indexOf(StringUtil.encodeBase64(byteArray)));
    } catch (HttpException e) {
        fail(FORCED_FAILURE);
    } catch (IOException e) {
        fail(FORCED_FAILURE);
    }

    try {
        StringRequestEntity requestEntity = new StringRequestEntity(
                ACHttpBodyUtil.buildGetACListByDiscIdRequestBody(sessionId, "aac6400f48249cc9763771cc626a3571"),
                null, ACHttpPropertiesConstant.HTTP_CHARSET);
        postMethod = new PostMethod(sb.toString());

        postMethod.setRequestHeader(CONTENT_TYPE_KEY, CONTENT_TYPE);
        postMethod.setRequestEntity(requestEntity);

        int statusCode = client.executeMethod(postMethod);

        assertEquals(SHOULD_BE_OK, HttpStatus.SC_OK, statusCode);

        String response = postMethod.getResponseBodyAsString();

        assertTrue(RESPONSE_ERROR, response.startsWith(SUCCESS_RESP));

        byte[] byteArray = new byte[3];

        byteArray[0] = 97;
        byteArray[1] = 98;
        byteArray[2] = 99;
        assertNotSame(RESPONSE_ERROR, -1, response.indexOf(StringUtil.encodeBase64(byteArray)));
    } catch (HttpException e) {
        fail(FORCED_FAILURE);
    } catch (IOException e) {
        fail(FORCED_FAILURE);
    }
}

From source file:com.mirth.connect.client.core.UpdateClient.java

public void sendUsageStatistics() throws ClientException {
    // Only send stats if they haven't been sent in the last 24 hours.
    long now = System.currentTimeMillis();
    Long lastUpdate = client.getUpdateSettings().getLastStatsTime();

    if (lastUpdate != null) {
        long last = lastUpdate;
        // 86400 seconds in a day
        if ((now - last) < (86400 * 1000)) {
            return;
        }//from   w ww .  ja v  a  2  s  . c o m
    }

    List<UsageData> usageData = null;

    try {
        usageData = getUsageData();
    } catch (Exception e) {
        throw new ClientException(e);
    }

    HttpClientParams httpClientParams = new HttpClientParams();
    HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager();
    httpClientParams.setSoTimeout(10 * 1000);
    httpConnectionManager.getParams().setConnectionTimeout(10 * 1000);
    httpConnectionManager.getParams().setSoTimeout(10 * 1000);
    HttpClient httpClient = new HttpClient(httpClientParams, httpConnectionManager);

    PostMethod post = new PostMethod(client.getUpdateSettings().getUpdateUrl() + URL_USAGE_STATISTICS);
    NameValuePair[] params = { new NameValuePair("serverId", client.getServerId()),
            new NameValuePair("version", client.getVersion()),
            new NameValuePair("data", serializer.toXML(usageData)) };
    post.setRequestBody(params);

    try {
        int statusCode = httpClient.executeMethod(post);

        if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) {
            throw new Exception("Failed to connect to update server: " + post.getStatusLine());
        }

        // Save the sent time if sending was successful.
        UpdateSettings settings = new UpdateSettings();
        settings.setLastStatsTime(now);
        client.setUpdateSettings(settings);

    } catch (Exception e) {
        throw new ClientException(e);
    } finally {
        post.releaseConnection();
    }
}