Example usage for com.squareup.okhttp Response code

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

Introduction

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

Prototype

int code

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

Click Source Link

Usage

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

License:Open Source License

/**
 * Pull data from DHIS Server/*www.j a  v a2 s  .  c  o m*/
 * @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//w ww  .ja  v a 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/* w w  w .j  ava  2s .  co 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 ww  w .  j ava  2 s  . c  om*/
 * @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//from w  w  w  . j a  v  a  2  s  .  c  o 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//from  w ww .  j a v a 2  s  . c  o m
 * @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 {// w  ww  . j a  v  a  2 s . c  om
        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  v a  2 s  . c om
 * @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;
    }

}

From source file:org.fs.ghanaian.core.CoreCallback.java

License:Apache License

/***
 *
 * @param response//from   w  ww .  ja v  a  2 s  .co m
 * @throws IOException
 */
@Override
public void onResponse(Response response) throws IOException {
    int httpCode = response.code();
    if (httpCode == 200) {
        if (response != null) {
            ResponseBody body = response.body();
            if (body != null) {
                String raw = body.string();
                if (!StringUtility.isNullOrEmpty(raw)) {
                    T object = parse(raw);
                    result(httpCode, object);
                    return;
                }
            }
        }
    }
    result(httpCode, null);
}

From source file:org.fuse.hawkular.agent.monitor.storage.AsyncInventoryStorage.java

License:Apache License

@Override
public <L> void resourcesRemoved(InventoryEvent<L> event) {
    // due to the way inventory sync works and how we are using it, we only care about explicitly
    // removing root resources. We can't individually sync a root resource (because it doesn't exist!)
    // so we remove it here. Any children resources will be synced via discoveryCompleted so we don't
    // do anything in here.
    List<Resource<L>> removedResources = event.getPayload();
    for (Resource<L> removedResource : removedResources) {
        if (removedResource.getParent() == null) {
            try {
                log.debugf("Removing root resource: %s", removedResource);

                MonitoredEndpoint<EndpointConfiguration> endpoint = event.getSamplingService()
                        .getMonitoredEndpoint();
                String endpointTenantId = endpoint.getEndpointConfiguration().getTenantId();
                String tenantIdToUse = (endpointTenantId != null) ? endpointTenantId : config.getTenantId();

                // The final URL should be in the form: entity/<resource_canonical_path>
                // for example: entity/t;hawkular/f;myfeed/r;resource_id

                CanonicalPath resourceCanonicalPath = CanonicalPath.of().tenant(tenantIdToUse).feed(feedId)
                        .resource(removedResource.getID().getIDString()).get();

                StringBuilder deleteUrl = Util.getContextUrlString(config.getUrl(),
                        config.getInventoryContext());
                deleteUrl.append("entity").append(resourceCanonicalPath.toString());

                Request request = httpClientBuilder.buildJsonDeleteRequest(deleteUrl.toString(),
                        getTenantHeader(tenantIdToUse));

                long start = System.currentTimeMillis(); // we don't store this time in our diagnostics
                Response response = httpClientBuilder.getHttpClient().newCall(request).execute();

                try {
                    final long duration = System.currentTimeMillis() - start;

                    if (response.code() != 204 && response.code() != 404) {
                        // 204 means successfully deleted, 404 means it didn't exist in the first place.
                        // In either case, the resource no longer exists which is what we want;
                        // any other response code means it is an error and we didn't remove the resource.
                        throw new Exception("status-code=[" + response.code() + "], reason=["
                                + response.message() + "], url=[" + request.urlString() + "]");
                    }/*from   ww  w.j  a  v  a 2s . c om*/

                    log.debugf("Took [%d]ms to remove root resource [%s]", duration, removedResource);
                } finally {
                    response.body().close();
                }
            } catch (InterruptedException ie) {
                log.errorFailedToStoreInventoryData(ie);
                Thread.currentThread().interrupt(); // preserve interrupt
            } catch (Exception e) {
                log.errorFailedToStoreInventoryData(e);
                diagnostics.getStorageErrorRate().mark(1);
            }

        }
    }
    return;
}