Example usage for com.squareup.okhttp Response message

List of usage examples for com.squareup.okhttp Response message

Introduction

In this page you can find the example usage for com.squareup.okhttp Response message.

Prototype

String message

To view the source code for com.squareup.okhttp Response message.

Click Source Link

Usage

From source file:org.dataconservancy.cos.packaging.cli.PackageGenerationApp.java

License:Apache License

/**
 * @param args/*from w w  w  .  j a v  a 2 s .  c o m*/
 */
public static void main(final String[] args) {

    final PackageGenerationApp application = new PackageGenerationApp();

    final CmdLineParser parser = new CmdLineParser(application);
    parser.setUsageWidth(80);

    try {
        parser.parseArgument(args);

        /* Handle general options such as help, version */
        if (application.help) {
            parser.printUsage(System.err);
            System.err.println();
            System.exit(0);
        } else if (application.version) {
            System.err.println(PackageGenerationApp.class.getPackage().getImplementationVersion());
            System.exit(0);
        }

        final Properties props = System.getProperties();

        if (confFile.exists() && confFile.isFile()) {
            props.setProperty("osf.client.conf", confFile.toURI().toString());
        } else {
            System.err.println("Supplied OSF Client Configuration File " + confFile.getCanonicalPath()
                    + " does not exist or is not a file.");
            System.exit(1);
        }

        CTX = new ClassPathXmlApplicationContext(
                "classpath*:org/dataconservancy/cos/osf/client/config/applicationContext.xml",
                "classpath*:org/dataconservancy/cos/osf/client/retrofit/applicationContext.xml",
                "classpath:/org/dataconservancy/cos/packaging/config/applicationContext.xml");

        final Response response = CTX.getBean("okHttpClient", OkHttpClient.class)
                .newCall(new Request.Builder().head().url(registrationUrl).build()).execute();

        if (response.code() != 200) {
            System.err.println("There was an error executing '" + registrationUrl + "', response code "
                    + response.code() + " reason: '" + response.message() + "'");
            System.err.print("Please be sure you are using a valid API URL to a node or registration, ");
            System.err.println("and have properly configured authorization credentials, if necessary.");
            System.exit(1);
        }

        if (!response.header("Content-Type").contains("json")) {
            System.err.println("Provided URL '" + registrationUrl + "' does not return JSON (Content-Type was '"
                    + response.header("Content-Type") + "')");
            System.err.println("Please be sure you are using a valid API URL to a node or registration.");
            System.exit(1);
        }

        final String guid = parseGuid(registrationUrl);

        if (packageName == null) {
            packageName = guid;
        } else if (!(packageName.length() > 0)) {
            System.err.println("Bag name must have positive length.");
            System.exit(1);
        }

        if (outputLocation == null) {
            outputLocation = new File(packageName);
        }

        if (outputLocation.exists()) {
            System.err
                    .println("Destination directory " + outputLocation.getCanonicalPath() + " already exists!  "
                            + "Either (re)move the directory, or choose a different output location.");
            System.exit(1);
        }

        FileUtils.forceMkdir(outputLocation);

        if (bagMetadataFile != null && (!bagMetadataFile.exists() || !bagMetadataFile.isFile())) {
            System.err.println("Supplied bag metadata file " + bagMetadataFile.getCanonicalPath()
                    + " does not exist or is not a file.");
            System.exit(1);
        }

        /* Run the package generation application proper */
        application.run();

    } catch (CmdLineException e) {
        /*
         * This is an error in command line args, just print out usage data
         * and description of the error.
         */
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.err.println();
        System.exit(1);
    } catch (Exception e) {
        if (e.getMessage() == null || e.getMessage().equals("null")) {
            System.err.println("There was an unrecoverable error:");
            e.printStackTrace(System.err);
        } else {
            System.err.println("There was an unrecoverable error: " + e.getMessage());
            e.printStackTrace(System.err);
        }

        System.exit(1);
    }
}

From source file:org.eyeseetea.malariacare.network.NetworkUtils.java

License:Open Source License

/**
 * Pushes data to DHIS Server/*from  ww  w . j  a  v  a 2 s  .  c o  m*/
 * @param data
 */
public JSONObject pushData(JSONObject data) throws Exception {
    Response response = null;

    final String DHIS_URL = getDhisURL() + DHIS_PUSH_API;

    OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();
    client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout
    client.setReadTimeout(30, TimeUnit.SECONDS); // socket timeout
    client.setWriteTimeout(30, TimeUnit.SECONDS); // write timeout
    client.setRetryOnConnectionFailure(false); // Cancel retry on failure
    BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
    client.setAuthenticator(basicAuthenticator);

    Log.d(TAG, "Url" + DHIS_URL + "");
    RequestBody body = RequestBody.create(JSON, data.toString());
    Request request = new Request.Builder()
            .header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL)
            .post(body).build();

    response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        Log.e(TAG, "pushData (" + response.code() + "): " + response.body().string());
        throw new IOException(response.message());
    }
    return parseResponse(response.body().string());
}

From source file:org.eyeseetea.malariacare.network.NetworkUtils.java

License:Open Source License

/**
 * Pull data from DHIS Server/*from w  ww  .jav a  2  s .  com*/
 * @param data
 */
public JSONObject getData(String data) throws Exception {
    Response response = null;

    final String DHIS_URL = getDhisURL() + DHIS_PULL_API + data;

    OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();

    BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
    client.setAuthenticator(basicAuthenticator);

    Log.d(TAG, "Url" + DHIS_URL + "");
    Request request = new Request.Builder()
            .header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL)
            .get().build();

    response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        Log.e(TAG, "getData (" + response.code() + "): " + response.body().string());
        throw new IOException(response.message());
    }
    return parseResponse(response.body().string());
}

From source file:org.eyeseetea.malariacare.network.PushClient.java

License:Open Source License

/**
 * Pushes data to DHIS Server//from   ww w .  j  a va  2 s  .  com
 * @param data
 */
private JSONObject pushData(JSONObject data) throws Exception {
    Response response = null;

    final String DHIS_URL = getDhisURL();

    OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();

    BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
    client.setAuthenticator(basicAuthenticator);

    RequestBody body = RequestBody.create(JSON, data.toString());
    Request request = new Request.Builder()
            .header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL)
            .post(body).build();

    response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        Log.e(TAG, "pushData (" + response.code() + "): " + response.body().string());
        throw new IOException(response.message());
    }
    return parseResponse(response.body().string());
}

From source file:org.eyeseetea.malariacare.network.ServerAPIController.java

License:Open Source License

/**
 * Returns the version of the given server.
 * Null if something went wrong//from  w w w  .j a v a 2 s . c o m
 * @param url
 * @return
 */
public static String getServerVersion(String url) {
    String serverVersion;
    try {
        String urlServerInfo = url + DHIS_SERVER_INFO;
        Response response = executeCall(null, urlServerInfo, "GET");

        //Error -> null
        if (!response.isSuccessful()) {
            Log.e(TAG, "getServerVersion (" + response.code() + "): " + response.body().string());
            throw new IOException(response.message());
        }
        JSONObject data = parseResponse(response.body().string());
        serverVersion = data.getString(TAG_VERSION);
    } catch (Exception ex) {
        Log.e(TAG, "getServerVersion: " + ex.toString());
        serverVersion = "";
    }
    Log.i(TAG, String.format("getServerVersion(%s) -> %s", url, serverVersion));
    return serverVersion;
}

From source file:org.eyeseetea.malariacare.network.ServerAPIController.java

License:Open Source License

/**
 * Returns if the given url contains the current program
 * @param url/*from w  w w.ja  v  a 2s  .  c  o  m*/
 * @return
 */
public static boolean isValidProgram(String url) {
    Log.d(TAG, String.format("isValidProgram(%s) ...", url));
    String programUIDInServer;
    try {
        String urlValidProgram = getIsValidProgramUrl(url);
        Response response = executeCall(null, urlValidProgram, "GET");

        //Error -> null
        if (!response.isSuccessful()) {
            Log.e(TAG, "isValidProgram (" + response.code() + "): " + response.body().string());
            throw new IOException(response.message());
        }

        JSONObject data = parseResponse(response.body().string());
        programUIDInServer = String.valueOf(data.get(TAG_ID));
    } catch (Exception ex) {
        Log.e(TAG, "isValidProgram: " + ex.toString());
        return false;
    }
    boolean valid = getProgramUID() != null && getProgramUID().equals(programUIDInServer);
    Log.d(TAG, String.format("isValidProgram(%s) -> %b", url, valid));
    return valid;
}

From source file:org.eyeseetea.malariacare.network.ServerAPIController.java

License:Open Source License

/**
 * This method returns a String[] whit the Organitation codes
 * @throws Exception//  ww w  .  j  a v a 2 s . co  m
 */
public static String[] pullOrgUnitsCodes(String url) {

    try {
        String orgUnitsURL = getDhisOrgUnitsURL(url);
        Response response = executeCall(null, orgUnitsURL, "GET");

        //Error -> null
        if (!response.isSuccessful()) {
            Log.e(TAG, "pullOrgUnitsCodes (" + response.code() + "): " + response.body().string());
            throw new IOException(response.message());
        }

        //{"organisationUnits":[{}]}
        JSONObject jsonResponse = parseResponse(response.body().string());
        JSONArray orgUnitsArray = (JSONArray) jsonResponse.get(TAG_ORGANISATIONUNITS);

        //0 matches -> Error
        if (orgUnitsArray.length() == 0) {
            throw new Exception("Found 0 matches");
        }
        return Utils.jsonArrayToStringArray(orgUnitsArray, TAG_CODE);

    } catch (Exception ex) {
        Log.e(TAG, String.format("pullOrgUnitsCodes(%url): %s", url, ex.getMessage()));
        String[] value = new String[1];
        value[0] = "";
        return value;
    }

}

From source file:org.eyeseetea.malariacare.network.ServerAPIController.java

License:Open Source License

/**
 * Updates the orgUnit adding a closedDate
 * @param url/*ww w .  ja  v  a2s . c om*/
 * @param orgUnitUID
 */
static void patchClosedDate(String url, String orgUnitUID) {
    //https://malariacare.psi.org/api/organisationUnits/u5jlxuod8xQ/closedDate
    try {
        String urlPathClosedDate = getPatchClosedDateUrl(url, orgUnitUID);
        JSONObject data = prepareTodayDateValue();
        Response response = executeCall(data, urlPathClosedDate, "PATCH");
        if (!response.isSuccessful()) {
            Log.e(TAG, "closingDatePatch (" + response.code() + "): " + response.body().string());
            throw new IOException(response.message());
        }
    } catch (Exception e) {
        Log.e(TAG, String.format("patchClosedDate(%s,%s): %s", url, orgUnitUID, e.getMessage()));
    }
}

From source file:org.eyeseetea.malariacare.network.ServerAPIController.java

License:Open Source License

static void patchDescriptionClosedDate(String url, String orgUnitUID, String orgUnitDescription) {
    //https://malariacare.psi.org/api/organisationUnits/u5jlxuod8xQ/closedDate
    try {/*from w  w  w  . j a  v  a2  s .  co m*/
        String urlPathClosedDescription = getPatchClosedDescriptionUrl(url, orgUnitUID);
        JSONObject data = prepareClosingDescriptionValue(orgUnitDescription);
        Response response = executeCall(data, urlPathClosedDescription, "PATCH");
        if (!response.isSuccessful()) {
            Log.e(TAG, "patchDescriptionClosedDate (" + response.code() + "): " + response.body().string());
            throw new IOException(response.message());
        }
    } catch (Exception e) {
        Log.e(TAG, String.format("patchDescriptionClosedDate(%s,%s): %s", url, orgUnitUID, e.getMessage()));
    }
}

From source file:org.eyeseetea.malariacare.network.ServerAPIController.java

License:Open Source License

/**
 * Returns the orgunit data from the given server according to its current version
 * @param url/*from  www  .  j  a va  2 s .c o m*/
 * @param orgUnitNameOrCode
 * @return
 */
static JSONObject getOrgUnitData(String url, String orgUnitNameOrCode) {
    //Version is required to choose which field to match
    String serverVersion = getServerVersion(url);

    //No version -> No data
    if (serverVersion == null) {
        return null;
    }

    try {
        String urlOrgUnitData = getOrgUnitDataUrl(url, serverVersion, orgUnitNameOrCode);
        Response response = executeCall(null, urlOrgUnitData, "GET");

        //Error -> null
        if (!response.isSuccessful()) {
            Log.e(TAG, "getOrgUnitData (" + response.code() + "): " + response.body().string());
            throw new IOException(response.message());
        }

        //{"organisationUnits":[{}]}
        JSONObject jsonResponse = parseResponse(response.body().string());
        JSONArray orgUnitsArray = (JSONArray) jsonResponse.get(TAG_ORGANISATIONUNITS);

        //0| >1 matches -> Error
        if (orgUnitsArray.length() == 0 || orgUnitsArray.length() > 1) {
            Log.e(TAG, String.format("getOrgUnitData(%s,%s) -> Found %d matches", url, orgUnitNameOrCode,
                    orgUnitsArray.length()));
            return null;
        }
        return (JSONObject) orgUnitsArray.get(0);

    } catch (Exception ex) {
        Log.e(TAG, String.format("getOrgUnitData(%s,%s): %s", url, orgUnitNameOrCode, ex.toString()));
        return null;
    }

}