Example usage for org.json JSONObject toString

List of usage examples for org.json JSONObject toString

Introduction

In this page you can find the example usage for org.json JSONObject toString.

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONObject.

Usage

From source file:test.Testing.java

public static void main(String[] args) throws Exception {
    ////////////////////////////////////////////////////////////////////////////////////////////
    // Setup/*from  w  w w  .j av  a2s .c  o  m*/
    ////////////////////////////////////////////////////////////////////////////////////////////
    String key = "CHANGEME: YOUR_API_KEY";
    String secret = "CHANGEME: YOUR_API_SECRET";
    String version = "preview1";
    String practiceid = "000000";

    APIConnection api = new APIConnection(version, key, secret, practiceid);
    api.authenticate();

    // If you want to set the practice ID after construction, this is how.
    // api.setPracticeID("000000");

    ////////////////////////////////////////////////////////////////////////////////////////////
    // GET without parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    JSONArray customfields = (JSONArray) api.GET("/customfields");
    System.out.println("Custom fields:");
    for (int i = 0; i < customfields.length(); i++) {
        System.out.println("\t" + customfields.getJSONObject(i).get("name"));
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
    // GET with parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
    Calendar today = Calendar.getInstance();
    Calendar nextyear = Calendar.getInstance();
    nextyear.roll(Calendar.YEAR, 1);

    Map<String, String> search = new HashMap<String, String>();
    search.put("departmentid", "82");
    search.put("startdate", format.format(today.getTime()));
    search.put("enddate", format.format(nextyear.getTime()));
    search.put("appointmenttypeid", "2");
    search.put("limit", "1");

    JSONObject open_appts = (JSONObject) api.GET("/appointments/open", search);
    System.out.println(open_appts.toString());
    JSONObject appt = open_appts.getJSONArray("appointments").getJSONObject(0);
    System.out.println("Open appointment:");
    System.out.println(appt.toString());

    // add keys to make appt usable for scheduling
    appt.put("appointmenttime", appt.get("starttime"));
    appt.put("appointmentdate", appt.get("date"));

    ////////////////////////////////////////////////////////////////////////////////////////////
    // POST with parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    Map<String, String> patient_info = new HashMap<String, String>();
    patient_info.put("lastname", "Foo");
    patient_info.put("firstname", "Jason");
    patient_info.put("address1", "123 Any Street");
    patient_info.put("city", "Cambridge");
    patient_info.put("countrycode3166", "US");
    patient_info.put("departmentid", "1");
    patient_info.put("dob", "6/18/1987");
    patient_info.put("language6392code", "declined");
    patient_info.put("maritalstatus", "S");
    patient_info.put("race", "declined");
    patient_info.put("sex", "M");
    patient_info.put("ssn", "*****1234");
    patient_info.put("zip", "02139");

    JSONArray new_patient = (JSONArray) api.POST("/patients", patient_info);
    String new_patient_id = new_patient.getJSONObject(0).getString("patientid");
    System.out.println("New patient id:");
    System.out.println(new_patient_id);

    ////////////////////////////////////////////////////////////////////////////////////////////
    // PUT with parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    Map<String, String> appointment_info = new HashMap<String, String>();
    appointment_info.put("appointmenttypeid", "82");
    appointment_info.put("departmentid", "1");
    appointment_info.put("patientid", new_patient_id);

    JSONArray booked = (JSONArray) api.PUT("/appointments/" + appt.getString("appointmentid"),
            appointment_info);
    System.out.println("Booked:");
    System.out.println(booked.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // POST without parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    JSONObject checked_in = (JSONObject) api
            .POST("/appointments/" + appt.getString("appointmentid") + "/checkin");
    System.out.println("Check-in:");
    System.out.println(checked_in.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // DELETE with parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    Map<String, String> delete_params = new HashMap<String, String>();
    delete_params.put("departmentid", "1");
    JSONObject chart_alert = (JSONObject) api.DELETE("/patients/" + new_patient_id + "/chartalert",
            delete_params);
    System.out.println("Removed chart alert:");
    System.out.println(chart_alert.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // DELETE without parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    JSONObject photo = (JSONObject) api.DELETE("/patients/" + new_patient_id + "/photo");
    System.out.println("Removed photo:");
    System.out.println(photo.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // There are no PUTs without parameters
    ////////////////////////////////////////////////////////////////////////////////////////////

    ////////////////////////////////////////////////////////////////////////////////////////////
    // Error conditions
    ////////////////////////////////////////////////////////////////////////////////////////////
    JSONObject bad_path = (JSONObject) api.GET("/nothing/at/this/path");
    System.out.println("GET /nothing/at/this/path:");
    System.out.println(bad_path.toString());
    JSONObject missing_parameters = (JSONObject) api.GET("/appointments/open");
    System.out.println("Missing parameters:");
    System.out.println(missing_parameters.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // Testing token refresh
    //
    // NOTE: this test takes an hour, so it's disabled by default. Change false to true to run.
    ////////////////////////////////////////////////////////////////////////////////////////////
    if (false) {
        String old_token = api.getToken();
        System.out.println("Old token: " + old_token);

        JSONObject before_refresh = (JSONObject) api.GET("/departments");

        // Wait 3600 seconds = 1 hour for token to expire.
        try {
            Thread.sleep(3600 * 1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        JSONObject after_refresh = (JSONObject) api.GET("/departments");

        System.out.println("New token: " + api.getToken());
    }
}

From source file:com.skysql.manager.api.NodeInfo.java

/**
 * Save node info to API./*from w w  w .  j a va2 s .c om*/
 *
 * @return true, if successful
 */
public boolean save() {

    APIrestful api = new APIrestful();
    boolean success = false;

    try {
        if (ID != null) {
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("name", this.name);
            jsonParam.put("hostname", this.hostname);
            jsonParam.put("instanceid", this.instanceID);
            jsonParam.put("publicip", this.publicIP);
            jsonParam.put("privateip", this.privateIP);
            if (this.dbUsername != null) {
                jsonParam.put("dbusername", this.dbUsername);
            }
            if (this.dbPassword != null) {
                jsonParam.put("dbpassword", this.dbPassword != null ? this.dbPassword : JSONObject.NULL);
            }
            if (this.repUsername != null) {
                jsonParam.put("repusername", this.repUsername);
            }
            if (this.repPassword != null) {
                jsonParam.put("reppassword", this.repPassword != null ? this.repPassword : JSONObject.NULL);
            }
            success = api.put("system/" + parentID + "/node/" + ID, jsonParam.toString());
        } else {
            StringBuffer regParam = new StringBuffer();
            regParam.append("name=" + URLEncoder.encode(this.name, "UTF-8"));
            regParam.append("&hostname=" + URLEncoder.encode(this.hostname, "UTF-8"));
            regParam.append("&instanceid=" + URLEncoder.encode(this.instanceID, "UTF-8"));
            regParam.append("&publicip=" + URLEncoder.encode(this.publicIP, "UTF-8"));
            regParam.append("&privateip=" + URLEncoder.encode(this.privateIP, "UTF-8"));
            if (this.dbUsername != null) {
                regParam.append("&dbusername=" + URLEncoder.encode(this.dbUsername, "UTF-8"));
            }
            if (this.dbPassword != null) {
                regParam.append("&dbpassword=" + URLEncoder.encode(this.dbPassword, "UTF-8"));
            }
            if (this.repUsername != null) {
                regParam.append("&repusername=" + URLEncoder.encode(this.repUsername, "UTF-8"));
            }
            if (this.repPassword != null) {
                regParam.append("&reppassword=" + URLEncoder.encode(this.repPassword, "UTF-8"));
            }
            success = api.post("system/" + parentID + "/node", regParam.toString());
        }

    } catch (JSONException e) {
        new ErrorDialog(e, "Error encoding API request");
        throw new RuntimeException("Error encoding API request");
    } catch (UnsupportedEncodingException e) {
        new ErrorDialog(e, "Error encoding API request");
        throw new RuntimeException("Error encoding API request");
    }

    if (success) {
        WriteResponse writeResponse = APIrestful.getGson().fromJson(api.getResult(), WriteResponse.class);
        if (writeResponse != null && ID == null && !writeResponse.getInsertKey().isEmpty()) {
            ID = writeResponse.getInsertKey();
            return true;
        } else if (writeResponse != null && ID != null && writeResponse.getUpdateCount() > 0) {
            return true;
        }
    }

    return false;

}

From source file:com.intel.xdk.facebook.IntelXDKFacebook.java

@JavascriptInterface
public void requestWithGraphAPI(String[] arguments)// path, String method, String parameters)
{
    if (busy) {//from   w ww.j av a2 s  .com
        sendBusyEvent();
        return;
    }

    if (!session.isOpened()) {
        currentCommand = REQ_GRAPH_API;
        currentCommandArguments = arguments;
        login(defaultLoginPermissions);
        return;
    } else {
        busy = true;
    }

    final String path = arguments[0];
    String method = arguments[1];
    String parameters = arguments[2];

    JSONObject json = new JSONObject();
    try {
        json = new JSONObject(parameters);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    final JSONObject finalJson = json;

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {

            Request graphRequest = Request.newGraphPathRequest(session, path, new Request.Callback() {
                @Override
                public void onCompleted(Response response) {
                    FacebookRequestError error = response.getError();
                    if (error != null) {
                        String js = String.format(
                                "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.request.response',true,true);e.success=false;e.error='%s';e.raw='';e.data={};document.dispatchEvent(e);",
                                error.toString());
                        //webView.loadUrl(js);
                        injectJS(js);
                        resetFBStatus();
                        return;
                    } else if (session == Session.getActiveSession()) {
                        GraphObject graphObject = response.getGraphObject();
                        JSONArray array;

                        if (graphObject != null) {
                            JSONObject jsonObject = graphObject.getInnerJSONObject();

                            String responsestr = jsonObject.toString().replaceAll("'", "\\\\'");
                            responsestr = responsestr.replaceAll("\"", "\\\\\"");

                            String js = String.format(
                                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.request.response',true,true);e.success=true;e.raw='%s';e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){}e.error='';document.dispatchEvent(e);",
                                    responsestr);
                            //webView.loadUrl(js);
                            injectJS(js);
                            resetFBStatus();
                            return;
                        } else {
                            String js = String.format(
                                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.request.response',true,true);e.success=false;e.error='%s';e.raw='';e.data={};document.dispatchEvent(e);",
                                    "There was a problem with the FB graph call.");
                            //webView.loadUrl(js);
                            injectJS(js);
                            resetFBStatus();
                            return;
                        }

                    }
                }
            });
            Bundle params = JSONtoBundle(finalJson);
            //params.putString("fields", "name,first_name,last_name");
            graphRequest.setParameters(params);
            graphRequest.executeAndWait();

        }
    });
}

From source file:com.intel.xdk.facebook.IntelXDKFacebook.java

@JavascriptInterface
public void showAppRequestDialog(final String parameters) {
    if (!session.isOpened()) {
        currentCommand = APP_REQUEST_DIALOG;
        currentCommandArguments = new String[] { parameters };
        login(defaultLoginPermissions);/*w ww. java 2  s  . c  o  m*/
        return;
    } else {
        //busy=true;
    }

    activity.runOnUiThread(new Runnable() {
        //@Override
        public void run() {

            JSONObject json = new JSONObject();
            try {
                json = new JSONObject(parameters);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Bundle params = JSONtoBundle(json);

            params.putString("frictionless", useFrictionless);

            WebDialog requestsDialog = (new WebDialog.RequestsDialogBuilder(activity, session, params))
                    .setOnCompleteListener(new OnCompleteListener() {

                        @Override
                        public void onComplete(Bundle values, FacebookException error) {
                            if (error != null) {
                                if (error instanceof FacebookOperationCanceledException) {
                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);");
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                } else {
                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=false;e.error='%s';e.raw='';e.data={};document.dispatchEvent(e);",
                                            error.toString());
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                }
                            } else {
                                final String requestId = values.getString("request");
                                if (requestId != null) {
                                    JSONObject jsonData = BundleToJSON(values);
                                    String extra = "";

                                    try {
                                        String request = jsonData.getString("request");
                                        extra += "e.request=" + request + ";";
                                    } catch (JSONException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                    }

                                    int index = 0;
                                    if (jsonData.has("to[" + index + "]")) {
                                        extra += "e.to=[";
                                        while (jsonData.has("to[" + index + "]")) {
                                            try {
                                                extra += jsonData.getString("to[" + index + "]") + ",";
                                            } catch (JSONException e) {
                                            }
                                            index++;
                                        }
                                        extra += "];";
                                    }

                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=true;e.error='';e.raw='%s';e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){}%sdocument.dispatchEvent(e);",
                                            jsonData.toString(), extra);
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                } else {
                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);");
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                }
                            }
                        }

                    }).build();
            requestsDialog.show();
        }
    });

}

From source file:com.intel.xdk.facebook.IntelXDKFacebook.java

@JavascriptInterface
public void showNewsFeedDialog(final String parameters) {
    if (!session.isOpened()) {
        currentCommand = NEWS_FEED_DIALOG;
        currentCommandArguments = new String[] { parameters };
        login(defaultLoginPermissions);//from   www.  j  av a  2  s . c  o  m
        return;
    } else {
        busy = true;
    }

    activity.runOnUiThread(new Runnable() {
        //@Override
        public void run() {

            JSONObject json = new JSONObject();
            try {
                json = new JSONObject(parameters);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //facebook.dialog(activity, "feed", JSONtoBundle(json), FBDialogListener );
            //            Bundle params = new Bundle();
            //             params.putString("name", "Facebook SDK for Android");
            //             params.putString("caption", "Build great social apps and get more installs.");
            //             params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
            //             params.putString("link", "https://developers.facebook.com/android");
            //             params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
            Bundle params = JSONtoBundle(json);

            params.putString("frictionless", useFrictionless);

            WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(activity, session, params))
                    .setOnCompleteListener(new OnCompleteListener() {

                        @Override
                        public void onComplete(Bundle values, FacebookException error) {
                            if (error == null) {
                                // When the story is posted, echo the success
                                // and the post Id.
                                final String postId = values.getString("post_id");
                                if (postId != null) {
                                    //                                 Toast.makeText(activity,
                                    //                                     "Posted story, id: "+postId,
                                    //                                     Toast.LENGTH_SHORT).show();
                                    JSONObject jsonData = BundleToJSON(values);
                                    String extra = "";

                                    try {
                                        String request = jsonData.getString("request");
                                        extra += "e.request=" + request + ";";
                                    } catch (JSONException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                    }

                                    int index = 0;
                                    if (jsonData.has("to[" + index + "]")) {
                                        extra += "e.to=[";
                                        while (jsonData.has("to[" + index + "]")) {
                                            try {
                                                extra += jsonData.getString("to[" + index + "]") + ",";
                                            } catch (JSONException e) {
                                            }
                                            index++;
                                        }
                                        extra += "];";
                                    }

                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=true;e.error='';e.raw='%s';e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){}%sdocument.dispatchEvent(e);",
                                            jsonData.toString(), extra);
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                } else {
                                    // User clicked the Cancel button
                                    //                                 Toast.makeText(activity.getApplicationContext(), 
                                    //                                     "Publish cancelled", 
                                    //                                     Toast.LENGTH_SHORT).show();
                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);");
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                }
                            } else if (error instanceof FacebookOperationCanceledException) {
                                // User clicked the "x" button
                                //                             Toast.makeText(activity.getApplicationContext(), 
                                //                                 "Publish cancelled", 
                                //                                 Toast.LENGTH_SHORT).show();
                                String js = String.format(
                                        "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);");
                                webView.loadUrl(js);
                                resetFBStatus();
                            } else {
                                // Generic, ex: network error
                                //                             Toast.makeText(activity.getApplicationContext(), 
                                //                                 "Error posting story", 
                                //                                 Toast.LENGTH_SHORT).show();
                                String js = String.format(
                                        "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=false;e.error='%s';e.raw='';e.data={};document.dispatchEvent(e);",
                                        error.toString());
                                webView.loadUrl(js);
                                resetFBStatus();
                            }
                        }

                    }).build();
            feedDialog.show();
        }
    });

}

From source file:org.wso2.carbon.connector.clevertim.CreateContact.java

/**
 * Create JSON request for CreateContact.
 *
 * @return JSON payload.//  w  w w .  jav a  2s  .  com
 * @throws JSONException thrown when parsing JSON String.
 */
private String getJsonPayload() throws JSONException {

    JSONObject jsonPayload = new JSONObject();

    String firstName = (String) messageContext.getProperty(Constants.FIRST_NAME);
    if (firstName != null && !firstName.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.FIRST_NAME, firstName);
    }
    String lastName = (String) messageContext.getProperty(Constants.LAST_NAME);
    if (lastName != null && !lastName.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.LAST_NAME, lastName);
    }
    String title = (String) messageContext.getProperty(Constants.TITLE);
    if (title != null && !title.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.TITLE, title);
    }
    String description = (String) messageContext.getProperty(Constants.DESCRIPTION);
    if (description != null && !description.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.DESCRIPTION, description);
    }
    String isCompany = (String) messageContext.getProperty(Constants.IS_COMPANY);
    if (isCompany != null && !isCompany.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.IS_COMPANY, isCompany);
    }
    String companyId = (String) messageContext.getProperty(Constants.COMPANY_ID);
    if (companyId != null && !companyId.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.COMPANY_ID, companyId);
    }
    String email = (String) messageContext.getProperty(Constants.EMAIL);
    if (email != null && !email.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.EMAIL, new JSONArray(email));
    }
    String phones = (String) messageContext.getProperty(Constants.PHONES);
    if (phones != null && !phones.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.PHONES, new JSONArray(phones));
    }
    String website = (String) messageContext.getProperty(Constants.WEBSITE);
    if (website != null && !website.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.WEBSITE, new JSONArray(website));
    }
    String address = (String) messageContext.getProperty(Constants.ADDRESS);
    if (address != null && !address.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.ADDRESS, address);
    }
    String city = (String) messageContext.getProperty(Constants.CITY);
    if (city != null && !city.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.CITY, city);
    }
    String postCode = (String) messageContext.getProperty(Constants.POST_CODE);
    if (postCode != null && !postCode.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.POST_CODE, postCode);
    }
    String country = (String) messageContext.getProperty(Constants.COUNTRY);
    if (country != null && !country.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.COUNTRY, country);
    }
    String socialMediaIds = (String) messageContext.getProperty(Constants.SOCIAL_MEDIA_IDS);
    if (socialMediaIds != null && !socialMediaIds.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.SOCIAL_MEDIA_IDS, new JSONArray(socialMediaIds));
    }
    String customerType = (String) messageContext.getProperty(Constants.CUSTOMER_TYPE);
    if (customerType != null && !customerType.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.CUSTOMER_TYPE, customerType);
    }
    String customFields = (String) messageContext.getProperty(Constants.CUSTOM_FIELDS);
    if (customFields != null && !customFields.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.CUSTOM_FIELD, new JSONObject(customFields));
    }
    String tags = (String) messageContext.getProperty(Constants.TAGS);
    if (tags != null && !tags.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.TAGS, new JSONArray(tags));
    }

    return jsonPayload.toString();
}

From source file:test.java.ecplugins.weblogic.TestUtils.java

public static void setResourceAndWorkspace(String resourceName, String workspaceName, String pluginName)
        throws Exception {

    props = getProperties();//from   w  w  w .j a  v  a2s . co m
    HttpClient httpClient = new DefaultHttpClient();
    JSONObject jo = new JSONObject();
    jo.put("projectName", pluginName);
    jo.put("resourceName", resourceName);
    jo.put("workspaceName", workspaceName);

    HttpPut httpPutRequest = new HttpPut("http://" + props.getProperty(StringConstants.COMMANDER_SERVER)
            + ":8000/rest/v1.0/projects/" + pluginName);

    String encoding = new String(
            org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils
                    .getBytesUtf8(props.getProperty(StringConstants.COMMANDER_USER) + ":"
                            + props.getProperty(StringConstants.COMMANDER_PASSWORD))));
    StringEntity input = new StringEntity(jo.toString());

    input.setContentType("application/json");
    httpPutRequest.setEntity(input);
    httpPutRequest.setHeader("Authorization", "Basic " + encoding);
    HttpResponse httpResponse = httpClient.execute(httpPutRequest);

    if (httpResponse.getStatusLine().getStatusCode() >= 400) {
        throw new RuntimeException("Failed to set resource  " + resourceName + " to project " + pluginName);
    }
    System.out.println("Set the resource as " + resourceName + " and workspace as " + workspaceName
            + " successfully for " + pluginName);
}

From source file:test.java.ecplugins.weblogic.TestUtils.java

/**
 * callRunProcedure/*from  w w  w . j  a v  a2 s .c  o  m*/
 * 
 * @param jo
 * @return the jobId of the job launched by runProcedure
 */
public static String callRunProcedure(JSONObject jo) throws Exception {

    props = getProperties();
    HttpClient httpClient = new DefaultHttpClient();
    JSONObject result = null;

    try {
        String encoding = new String(
                org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils
                        .getBytesUtf8(props.getProperty(StringConstants.COMMANDER_USER) + ":"
                                + props.getProperty(StringConstants.COMMANDER_PASSWORD))));

        HttpPost httpPostRequest = new HttpPost("http://" + props.getProperty(StringConstants.COMMANDER_SERVER)
                + ":8000/rest/v1.0/jobs?request=runProcedure");

        StringEntity input = new StringEntity(jo.toString());

        input.setContentType("application/json");
        httpPostRequest.setEntity(input);
        httpPostRequest.setHeader("Authorization", "Basic " + encoding);
        HttpResponse httpResponse = httpClient.execute(httpPostRequest);

        result = new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
        return result.getString("jobId");

    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:test.java.ecplugins.weblogic.TestUtils.java

/**
 * Creates a new workspace. If the workspace already exists,It continues.
 * //from   w  w  w . j  ava 2 s.  c  o m
 */
static void createCommanderWorkspace(String workspaceName) throws Exception {

    props = getProperties();
    HttpClient httpClient = new DefaultHttpClient();
    JSONObject jo = new JSONObject();

    try {

        String url = "http://" + props.getProperty(StringConstants.COMMANDER_SERVER)
                + ":8000/rest/v1.0/workspaces/";
        String encoding = new String(
                org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils
                        .getBytesUtf8(props.getProperty(StringConstants.COMMANDER_USER) + ":"
                                + props.getProperty(StringConstants.COMMANDER_PASSWORD))));

        HttpPost httpPostRequest = new HttpPost(url);
        jo.put("workspaceName", workspaceName);
        jo.put("description", workspaceName);
        jo.put("agentDrivePath", "C:/Program Files/Electric Cloud/ElectricCommander");
        jo.put("agentUncPath", "C:/Program Files/Electric Cloud/ElectricCommander");
        jo.put("agentUnixPath", "/opt/electriccloud/electriccommander");
        jo.put("local", true);

        StringEntity input = new StringEntity(jo.toString());

        input.setContentType("application/json");
        httpPostRequest.setEntity(input);
        httpPostRequest.setHeader("Authorization", "Basic " + encoding);
        HttpResponse httpResponse = httpClient.execute(httpPostRequest);

        if (httpResponse.getStatusLine().getStatusCode() == 409) {
            System.out.println("Commander workspace already exists.Continuing....");
        } else if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new RuntimeException(
                    "Failed to create commander workspace " + httpResponse.getStatusLine().getStatusCode() + "-"
                            + httpResponse.getStatusLine().getReasonPhrase());
        }
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:test.java.ecplugins.weblogic.TestUtils.java

/**
 * //from   w ww  .  ja  v a2 s.  c  om
 * @return
 */
static void createCommanderResource(String resourceName, String workspaceName, String resourceIP)
        throws Exception {

    props = getProperties();
    HttpClient httpClient = new DefaultHttpClient();
    JSONObject jo = new JSONObject();

    try {
        HttpPost httpPostRequest = new HttpPost(
                "http://" + props.getProperty(StringConstants.COMMANDER_SERVER) + ":8000/rest/v1.0/resources/");
        String encoding = new String(
                org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils
                        .getBytesUtf8(props.getProperty(StringConstants.COMMANDER_USER) + ":"
                                + props.getProperty(StringConstants.COMMANDER_PASSWORD))));

        jo.put("resourceName", resourceName);
        jo.put("description", "Resource created for test automation");
        jo.put("hostName", resourceIP);
        jo.put("port", StringConstants.EC_AGENT_PORT);
        jo.put("workspaceName", workspaceName);
        jo.put("pools", "default");
        jo.put("local", true);

        StringEntity input = new StringEntity(jo.toString());

        input.setContentType("application/json");
        httpPostRequest.setEntity(input);
        httpPostRequest.setHeader("Authorization", "Basic " + encoding);
        HttpResponse httpResponse = httpClient.execute(httpPostRequest);

        if (httpResponse.getStatusLine().getStatusCode() == 409) {
            System.out.println("Commander resource already exists.Continuing....");

        } else if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new RuntimeException(
                    "Failed to create commander workspace " + httpResponse.getStatusLine().getStatusCode() + "-"
                            + httpResponse.getStatusLine().getReasonPhrase());
        }
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}