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.apache.hadoop.hdfs.web.oauth2.CredentialBasedAccessTokenProvider.java

License:Apache License

void refresh() throws IOException {
    try {/*from  w  ww.  j  ava 2s. c  om*/
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
        client.setReadTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);

        String bodyString = Utils.postBody(CLIENT_SECRET, getCredential(), GRANT_TYPE, CLIENT_CREDENTIALS,
                CLIENT_ID, clientId);

        RequestBody body = RequestBody.create(URLENCODED, bodyString);

        Request request = new Request.Builder().url(refreshURL).post(body).build();
        Response responseBody = client.newCall(request).execute();

        if (responseBody.code() != HttpStatus.SC_OK) {
            throw new IllegalArgumentException("Received invalid http response: " + responseBody.code()
                    + ", text = " + responseBody.toString());
        }

        Map<?, ?> response = READER.readValue(responseBody.body().string());

        String newExpiresIn = response.get(EXPIRES_IN).toString();
        timer.setExpiresIn(newExpiresIn);

        accessToken = response.get(ACCESS_TOKEN).toString();

    } catch (Exception e) {
        throw new IOException("Unable to obtain access token from credential", e);
    }
}

From source file:org.apache.nifi.processors.standard.InvokeHTTP.java

License:Apache License

@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    OkHttpClient okHttpClient = okHttpClientAtomicReference.get();

    FlowFile requestFlowFile = session.get();

    // Checking to see if the property to put the body of the response in an attribute was set
    boolean putToAttribute = context.getProperty(PROP_PUT_OUTPUT_IN_ATTRIBUTE).isSet();
    if (requestFlowFile == null) {
        if (context.hasNonLoopConnection()) {
            return;
        }//from   ww  w .j  a  va2 s .c om

        String request = context.getProperty(PROP_METHOD).evaluateAttributeExpressions().getValue()
                .toUpperCase();
        if ("POST".equals(request) || "PUT".equals(request) || "PATCH".equals(request)) {
            return;
        } else if (putToAttribute) {
            requestFlowFile = session.create();
        }
    }

    // Setting some initial variables
    final int maxAttributeSize = context.getProperty(PROP_PUT_ATTRIBUTE_MAX_LENGTH).asInteger();
    final ComponentLog logger = getLogger();

    // Every request/response cycle has a unique transaction id which will be stored as a flowfile attribute.
    final UUID txId = UUID.randomUUID();

    FlowFile responseFlowFile = null;
    try {
        // read the url property from the context
        final String urlstr = trimToEmpty(
                context.getProperty(PROP_URL).evaluateAttributeExpressions(requestFlowFile).getValue());
        final URL url = new URL(urlstr);

        Request httpRequest = configureRequest(context, session, requestFlowFile, url);

        // log request
        logRequest(logger, httpRequest);

        // emit send provenance event if successfully sent to the server
        if (httpRequest.body() != null) {
            session.getProvenanceReporter().send(requestFlowFile, url.toExternalForm(), true);
        }

        final long startNanos = System.nanoTime();
        Response responseHttp = okHttpClient.newCall(httpRequest).execute();

        // output the raw response headers (DEBUG level only)
        logResponse(logger, url, responseHttp);

        // store the status code and message
        int statusCode = responseHttp.code();
        String statusMessage = responseHttp.message();

        if (statusCode == 0) {
            throw new IllegalStateException("Status code unknown, connection hasn't been attempted.");
        }

        // Create a map of the status attributes that are always written to the request and response FlowFiles
        Map<String, String> statusAttributes = new HashMap<>();
        statusAttributes.put(STATUS_CODE, String.valueOf(statusCode));
        statusAttributes.put(STATUS_MESSAGE, statusMessage);
        statusAttributes.put(REQUEST_URL, url.toExternalForm());
        statusAttributes.put(TRANSACTION_ID, txId.toString());

        if (requestFlowFile != null) {
            requestFlowFile = session.putAllAttributes(requestFlowFile, statusAttributes);
        }

        // If the property to add the response headers to the request flowfile is true then add them
        if (context.getProperty(PROP_ADD_HEADERS_TO_REQUEST).asBoolean() && requestFlowFile != null) {
            // write the response headers as attributes
            // this will overwrite any existing flowfile attributes
            requestFlowFile = session.putAllAttributes(requestFlowFile,
                    convertAttributesFromHeaders(url, responseHttp));
        }

        boolean outputBodyToRequestAttribute = (!isSuccess(statusCode) || putToAttribute)
                && requestFlowFile != null;
        boolean outputBodyToResponseContent = (isSuccess(statusCode) && !putToAttribute)
                || context.getProperty(PROP_OUTPUT_RESPONSE_REGARDLESS).asBoolean();
        ResponseBody responseBody = responseHttp.body();
        boolean bodyExists = responseBody != null;

        InputStream responseBodyStream = null;
        SoftLimitBoundedByteArrayOutputStream outputStreamToRequestAttribute = null;
        TeeInputStream teeInputStream = null;
        try {
            responseBodyStream = bodyExists ? responseBody.byteStream() : null;
            if (responseBodyStream != null && outputBodyToRequestAttribute && outputBodyToResponseContent) {
                outputStreamToRequestAttribute = new SoftLimitBoundedByteArrayOutputStream(maxAttributeSize);
                teeInputStream = new TeeInputStream(responseBodyStream, outputStreamToRequestAttribute);
            }

            if (outputBodyToResponseContent) {
                /*
                 * If successful and putting to response flowfile, store the response body as the flowfile payload
                 * we include additional flowfile attributes including the response headers and the status codes.
                 */

                // clone the flowfile to capture the response
                if (requestFlowFile != null) {
                    responseFlowFile = session.create(requestFlowFile);
                } else {
                    responseFlowFile = session.create();
                }

                // write attributes to response flowfile
                responseFlowFile = session.putAllAttributes(responseFlowFile, statusAttributes);

                // write the response headers as attributes
                // this will overwrite any existing flowfile attributes
                responseFlowFile = session.putAllAttributes(responseFlowFile,
                        convertAttributesFromHeaders(url, responseHttp));

                // transfer the message body to the payload
                // can potentially be null in edge cases
                if (bodyExists) {
                    // write content type attribute to response flowfile if it is available
                    if (responseBody.contentType() != null) {
                        responseFlowFile = session.putAttribute(responseFlowFile,
                                CoreAttributes.MIME_TYPE.key(), responseBody.contentType().toString());
                    }
                    if (teeInputStream != null) {
                        responseFlowFile = session.importFrom(teeInputStream, responseFlowFile);
                    } else {
                        responseFlowFile = session.importFrom(responseBodyStream, responseFlowFile);
                    }

                    // emit provenance event
                    final long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
                    if (requestFlowFile != null) {
                        session.getProvenanceReporter().fetch(responseFlowFile, url.toExternalForm(), millis);
                    } else {
                        session.getProvenanceReporter().receive(responseFlowFile, url.toExternalForm(), millis);
                    }
                }
            }

            // if not successful and request flowfile is not null, store the response body into a flowfile attribute
            if (outputBodyToRequestAttribute && bodyExists) {
                String attributeKey = context.getProperty(PROP_PUT_OUTPUT_IN_ATTRIBUTE)
                        .evaluateAttributeExpressions(requestFlowFile).getValue();
                if (attributeKey == null) {
                    attributeKey = RESPONSE_BODY;
                }
                byte[] outputBuffer;
                int size;

                if (outputStreamToRequestAttribute != null) {
                    outputBuffer = outputStreamToRequestAttribute.getBuffer();
                    size = outputStreamToRequestAttribute.size();
                } else {
                    outputBuffer = new byte[maxAttributeSize];
                    size = StreamUtils.fillBuffer(responseBodyStream, outputBuffer, false);
                }
                String bodyString = new String(outputBuffer, 0, size,
                        getCharsetFromMediaType(responseBody.contentType()));
                requestFlowFile = session.putAttribute(requestFlowFile, attributeKey, bodyString);

                final long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
                session.getProvenanceReporter().modifyAttributes(requestFlowFile,
                        "The " + attributeKey
                                + " has been added. The value of which is the body of a http call to "
                                + url.toExternalForm() + ". It took " + millis + "millis,");
            }
        } finally {
            if (outputStreamToRequestAttribute != null) {
                outputStreamToRequestAttribute.close();
                outputStreamToRequestAttribute = null;
            }
            if (teeInputStream != null) {
                teeInputStream.close();
                teeInputStream = null;
            } else if (responseBodyStream != null) {
                responseBodyStream.close();
                responseBodyStream = null;
            }
        }

        route(requestFlowFile, responseFlowFile, session, context, statusCode);
    } catch (final Exception e) {
        // penalize or yield
        if (requestFlowFile != null) {
            logger.error("Routing to {} due to exception: {}", new Object[] { REL_FAILURE.getName(), e }, e);
            requestFlowFile = session.penalize(requestFlowFile);
            requestFlowFile = session.putAttribute(requestFlowFile, EXCEPTION_CLASS, e.getClass().getName());
            requestFlowFile = session.putAttribute(requestFlowFile, EXCEPTION_MESSAGE, e.getMessage());
            // transfer original to failure
            session.transfer(requestFlowFile, REL_FAILURE);
        } else {
            logger.error("Yielding processor due to exception encountered as a source processor: {}", e);
            context.yield();
        }

        // cleanup response flowfile, if applicable
        try {
            if (responseFlowFile != null) {
                session.remove(responseFlowFile);
            }
        } catch (final Exception e1) {
            logger.error("Could not cleanup response flowfile due to exception: {}", new Object[] { e1 }, e1);
        }
    }
}

From source file:org.apache.pulsar.functions.runtime.KubernetesRuntime.java

License:Apache License

public void deleteStatefulSet() throws InterruptedException {
    String statefulSetName = createJobName(instanceConfig.getFunctionDetails());
    final V1DeleteOptions options = new V1DeleteOptions();
    options.setGracePeriodSeconds(5L);//w  w  w .j a  v  a  2 s  .  c o  m
    options.setPropagationPolicy("Foreground");

    String fqfn = FunctionDetailsUtils.getFullyQualifiedName(instanceConfig.getFunctionDetails());
    RuntimeUtils.Actions.Action deleteStatefulSet = RuntimeUtils.Actions.Action.builder()
            .actionName(String.format("Deleting statefulset for function %s", fqfn)).numRetries(NUM_RETRIES)
            .sleepBetweenInvocationsMs(SLEEP_BETWEEN_RETRIES_MS).supplier(() -> {
                Response response;
                try {
                    // cannot use deleteNamespacedStatefulSet because of bug in kuberenetes
                    // https://github.com/kubernetes-client/java/issues/86
                    response = appsClient.deleteNamespacedStatefulSetCall(statefulSetName, jobNamespace,
                            options, null, null, null, null, null, null).execute();
                } catch (ApiException e) {
                    // if already deleted
                    if (e.getCode() == HTTP_NOT_FOUND) {
                        log.warn("Statefulset for function {} does not exist", fqfn);
                        return RuntimeUtils.Actions.ActionResult.builder().success(true).build();
                    }

                    String errorMsg = e.getResponseBody() != null ? e.getResponseBody() : e.getMessage();
                    return RuntimeUtils.Actions.ActionResult.builder().success(false).errorMsg(errorMsg)
                            .build();
                } catch (IOException e) {
                    return RuntimeUtils.Actions.ActionResult.builder().success(false).errorMsg(e.getMessage())
                            .build();
                }

                // if already deleted
                if (response.code() == HTTP_NOT_FOUND) {
                    log.warn("Statefulset for function {} does not exist", fqfn);
                    return RuntimeUtils.Actions.ActionResult.builder().success(true).build();
                } else {
                    return RuntimeUtils.Actions.ActionResult.builder().success(response.isSuccessful())
                            .errorMsg(response.message()).build();
                }
            }).build();

    RuntimeUtils.Actions.Action waitForStatefulSetDeletion = RuntimeUtils.Actions.Action.builder()
            .actionName(String.format("Waiting for statefulset for function %s to complete deletion", fqfn))
            // set retry period to be about 2x the graceshutdown time
            .numRetries(NUM_RETRIES * 2).sleepBetweenInvocationsMs(SLEEP_BETWEEN_RETRIES_MS * 2)
            .supplier(() -> {
                V1StatefulSet response;
                try {
                    response = appsClient.readNamespacedStatefulSet(statefulSetName, jobNamespace, null, null,
                            null);
                } catch (ApiException e) {
                    // statefulset is gone
                    if (e.getCode() == HTTP_NOT_FOUND) {
                        return RuntimeUtils.Actions.ActionResult.builder().success(true).build();
                    }

                    String errorMsg = e.getResponseBody() != null ? e.getResponseBody() : e.getMessage();
                    return RuntimeUtils.Actions.ActionResult.builder().success(false).errorMsg(errorMsg)
                            .build();
                }
                return RuntimeUtils.Actions.ActionResult.builder().success(false)
                        .errorMsg(response.getStatus().toString()).build();
            }).build();

    // Need to wait for all pods to die so we can cleanup subscriptions.
    RuntimeUtils.Actions.Action waitForStatefulPodsToTerminate = RuntimeUtils.Actions.Action.builder()
            .actionName(String.format("Waiting for pods for function %s to terminate", fqfn))
            .numRetries(NUM_RETRIES * 2).sleepBetweenInvocationsMs(SLEEP_BETWEEN_RETRIES_MS * 2)
            .supplier(() -> {
                String labels = String.format("tenant=%s,namespace=%s,name=%s",
                        instanceConfig.getFunctionDetails().getTenant(),
                        instanceConfig.getFunctionDetails().getNamespace(),
                        instanceConfig.getFunctionDetails().getName());

                V1PodList response;
                try {
                    response = coreClient.listNamespacedPod(jobNamespace, null, null, null, null, labels, null,
                            null, null, null);
                } catch (ApiException e) {

                    String errorMsg = e.getResponseBody() != null ? e.getResponseBody() : e.getMessage();
                    return RuntimeUtils.Actions.ActionResult.builder().success(false).errorMsg(errorMsg)
                            .build();
                }

                if (response.getItems().size() > 0) {
                    return RuntimeUtils.Actions.ActionResult.builder().success(false)
                            .errorMsg(response.getItems().size() + " pods still alive.").build();
                } else {
                    return RuntimeUtils.Actions.ActionResult.builder().success(true).build();
                }
            }).build();

    AtomicBoolean success = new AtomicBoolean(false);
    RuntimeUtils.Actions.newBuilder().addAction(deleteStatefulSet.toBuilder().continueOn(true).build())
            .addAction(waitForStatefulSetDeletion.toBuilder().continueOn(false)
                    .onSuccess(() -> success.set(true)).build())
            .addAction(deleteStatefulSet.toBuilder().continueOn(true).build())
            .addAction(waitForStatefulSetDeletion.toBuilder().onSuccess(() -> success.set(true)).build()).run();

    if (!success.get()) {
        throw new RuntimeException(String.format("Failed to delete statefulset for function %s", fqfn));
    } else {
        // wait for pods to terminate
        RuntimeUtils.Actions.newBuilder().addAction(waitForStatefulPodsToTerminate).run();
    }
}

From source file:org.apache.pulsar.functions.runtime.KubernetesRuntime.java

License:Apache License

public void deleteService() throws InterruptedException {

    final V1DeleteOptions options = new V1DeleteOptions();
    options.setGracePeriodSeconds(0L);//from  w w  w . jav a2s .co  m
    options.setPropagationPolicy("Foreground");
    String fqfn = FunctionDetailsUtils.getFullyQualifiedName(instanceConfig.getFunctionDetails());
    String serviceName = createJobName(instanceConfig.getFunctionDetails());

    RuntimeUtils.Actions.Action deleteService = RuntimeUtils.Actions.Action.builder()
            .actionName(String.format("Deleting service for function %s", fqfn)).numRetries(NUM_RETRIES)
            .sleepBetweenInvocationsMs(SLEEP_BETWEEN_RETRIES_MS).supplier(() -> {
                final Response response;
                try {
                    // cannot use deleteNamespacedService because of bug in kuberenetes
                    // https://github.com/kubernetes-client/java/issues/86
                    response = coreClient.deleteNamespacedServiceCall(serviceName, jobNamespace, options, null,
                            null, null, null, null, null).execute();
                } catch (ApiException e) {
                    // if already deleted
                    if (e.getCode() == HTTP_NOT_FOUND) {
                        log.warn("Service for function {} does not exist", fqfn);
                        return RuntimeUtils.Actions.ActionResult.builder().success(true).build();
                    }

                    String errorMsg = e.getResponseBody() != null ? e.getResponseBody() : e.getMessage();
                    return RuntimeUtils.Actions.ActionResult.builder().success(false).errorMsg(errorMsg)
                            .build();
                } catch (IOException e) {
                    return RuntimeUtils.Actions.ActionResult.builder().success(false).errorMsg(e.getMessage())
                            .build();
                }

                // if already deleted
                if (response.code() == HTTP_NOT_FOUND) {
                    log.warn("Service for function {} does not exist", fqfn);
                    return RuntimeUtils.Actions.ActionResult.builder().success(true).build();
                } else {
                    return RuntimeUtils.Actions.ActionResult.builder().success(response.isSuccessful())
                            .errorMsg(response.message()).build();
                }
            }).build();

    RuntimeUtils.Actions.Action waitForServiceDeletion = RuntimeUtils.Actions.Action.builder()
            .actionName(String.format("Waiting for statefulset for function %s to complete deletion", fqfn))
            .numRetries(NUM_RETRIES).sleepBetweenInvocationsMs(SLEEP_BETWEEN_RETRIES_MS).supplier(() -> {
                V1Service response;
                try {
                    response = coreClient.readNamespacedService(serviceName, jobNamespace, null, null, null);

                } catch (ApiException e) {
                    // statefulset is gone
                    if (e.getCode() == HTTP_NOT_FOUND) {
                        return RuntimeUtils.Actions.ActionResult.builder().success(true).build();
                    }
                    String errorMsg = e.getResponseBody() != null ? e.getResponseBody() : e.getMessage();
                    return RuntimeUtils.Actions.ActionResult.builder().success(false).errorMsg(errorMsg)
                            .build();
                }
                return RuntimeUtils.Actions.ActionResult.builder().success(false)
                        .errorMsg(response.getStatus().toString()).build();
            }).build();

    AtomicBoolean success = new AtomicBoolean(false);
    RuntimeUtils.Actions.newBuilder().addAction(deleteService.toBuilder().continueOn(true).build())
            .addAction(waitForServiceDeletion.toBuilder().continueOn(false).onSuccess(() -> success.set(true))
                    .build())
            .addAction(deleteService.toBuilder().continueOn(true).build())
            .addAction(waitForServiceDeletion.toBuilder().onSuccess(() -> success.set(true)).build()).run();

    if (!success.get()) {
        throw new RuntimeException(String.format("Failed to delete service for function %s", fqfn));
    }
}

From source file:org.bitcoinj_extra.net.discovery.HttpDiscovery.java

License:Apache License

@Override
public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit)
        throws PeerDiscoveryException {
    try {//from w w  w .j av  a  2s. co  m
        HttpUrl.Builder url = HttpUrl.get(details.uri).newBuilder();
        if (services != 0)
            url.addQueryParameter("srvmask", Long.toString(services));
        Request.Builder request = new Request.Builder();
        request.url(url.build());
        request.addHeader("User-Agent", VersionMessage.LIBRARY_SUBVER); // TODO Add main version.
        log.info("Requesting seeds from {}", url);
        Response response = client.newCall(request.build()).execute();
        if (!response.isSuccessful())
            throw new PeerDiscoveryException(
                    "HTTP request failed: " + response.code() + " " + response.message());
        InputStream stream = response.body().byteStream();
        GZIPInputStream zip = new GZIPInputStream(stream);
        PeerSeedProtos.SignedPeerSeeds proto = PeerSeedProtos.SignedPeerSeeds.parseDelimitedFrom(zip);
        stream.close();
        return protoToAddrs(proto);
    } catch (PeerDiscoveryException e1) {
        throw e1;
    } catch (Exception e) {
        throw new PeerDiscoveryException(e);
    }
}

From source file:org.catrobat.catroid.web.ServerCalls.java

License:Open Source License

public void uploadProject(String projectName, String projectDescription, String zipFileString, String userEmail,
        String language, String token, String username, ResultReceiver receiver, Integer notificationId,
        Context context) throws WebconnectionException {

    Preconditions.checkNotNull(context, "Context cannot be null!");

    userEmail = emailForUiTests == null ? userEmail : emailForUiTests;
    userEmail = userEmail == null ? "" : userEmail;

    try {//w w w .j av  a 2 s  .  co m
        String md5Checksum = Utils.md5Checksum(new File(zipFileString));

        final String serverUrl = useTestUrl ? TEST_FILE_UPLOAD_URL_HTTP : FILE_UPLOAD_URL;

        Log.v(TAG, "Url to upload: " + serverUrl);

        File file = new File(zipFileString);
        RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                .addFormDataPart(FILE_UPLOAD_TAG, ProjectUploadService.UPLOAD_FILE_NAME,
                        RequestBody.create(MEDIA_TYPE_ZIPFILE, file))
                .addFormDataPart(PROJECT_NAME_TAG, projectName)
                .addFormDataPart(PROJECT_DESCRIPTION_TAG, projectDescription)
                .addFormDataPart(USER_EMAIL, userEmail).addFormDataPart(PROJECT_CHECKSUM_TAG, md5Checksum)
                .addFormDataPart(Constants.TOKEN, token).addFormDataPart(Constants.USERNAME, username)
                .addFormDataPart(DEVICE_LANGUAGE, language).build();

        Request request = new Request.Builder().url(serverUrl).post(requestBody).build();

        Response response = okHttpClient.newCall(request).execute();

        if (response.isSuccessful()) {
            Log.v(TAG, "Upload successful");
            StatusBarNotificationManager.getInstance().showOrUpdateNotification(notificationId, 100);
        } else {
            Log.v(TAG, "Upload not successful");
            throw new WebconnectionException(response.code(),
                    "Upload failed! HTTP Status code was " + response.code());
        }

        UploadResponse uploadResponse = gson.fromJson(response.body().string(), UploadResponse.class);

        String newToken = uploadResponse.token;
        String answer = uploadResponse.answer;
        int status = uploadResponse.statusCode;
        projectId = uploadResponse.projectId;

        if (status != SERVER_RESPONSE_TOKEN_OK) {
            throw new WebconnectionException(status, "Upload failed! JSON Response was " + status);
        }

        if (token.length() != TOKEN_LENGTH || token.isEmpty() || token.equals(TOKEN_CODE_INVALID)) {
            throw new WebconnectionException(status, answer);
        }
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        sharedPreferences.edit().putString(Constants.TOKEN, newToken).commit();
        sharedPreferences.edit().putString(Constants.USERNAME, username).commit();
    } catch (JsonSyntaxException jsonSyntaxException) {
        Log.e(TAG, Log.getStackTraceString(jsonSyntaxException));
        throw new WebconnectionException(WebconnectionException.ERROR_JSON, "JsonSyntaxException");
    } catch (IOException ioException) {
        Log.e(TAG, Log.getStackTraceString(ioException));
        throw new WebconnectionException(WebconnectionException.ERROR_NETWORK, "I/O Exception");
    }
}

From source file:org.chromium.cronet_sample_apk.CronetSampleActivity.java

License:Open Source License

private void makeRequest(Request request) {
    final Request mRequest = request;
    if (OkHttpSynchronousFlag) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    Response response = mOKHttpClient.newCall(mRequest).execute();
                    final String receivedData = response.body().string();
                    final String url = mRequest.urlString();
                    final String text = "Completed " + url + " (" + response.code() + ")";
                    CronetSampleActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            mOkhttpResultText.setText(text);
                            mOkhttpReceiveDataText.setText(receivedData);

                        }/* w w w.  ja v a2  s  . c o  m*/
                    });
                    if (!OKHttpFinishFlag) {
                        OKHttpFinishFlag = true;
                        Log.d(TAG, "set okhttp finish flag to true");
                    }
                } catch (IOException e) {
                    final String url = mRequest.urlString();
                    final String text = "Failed " + url + " (" + e.getMessage() + ")";
                    CronetSampleActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            mOkhttpResultText.setText(text);

                        }
                    });
                    if (!OKHttpFinishFlag) {
                        OKHttpFinishFlag = true;
                        Log.d(TAG, "set okhttp finish flag to true");
                    }
                }
            }
        }).start();
    } else {
        mOKHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                final String url = mUrl;
                final String text = "Failed " + url + " (" + e.getMessage() + ")";
                CronetSampleActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        mOkhttpResultText.setText(text);

                    }
                });
                if (!OKHttpFinishFlag) {
                    OKHttpFinishFlag = true;
                    Log.d(TAG, "set okhttp finish flag to true");
                }

            }

            @Override
            public void onResponse(Response response) throws IOException {

                final String receivedData = response.body().string();
                Log.d(TAG, receivedData);
                final String url = mUrl;
                final String text = "Completed " + url + " (" + response.code() + ")";
                CronetSampleActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        mOkhttpResultText.setText(text);
                        mOkhttpReceiveDataText.setText(receivedData);
                    }
                });
                if (!OKHttpFinishFlag) {
                    OKHttpFinishFlag = true;
                    Log.d(TAG, "set okhttp finish flag to true");
                }

            }
        });
    }
}

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

License:Apache License

/**
 * @param args/*  w w w . j  a v a  2 s  .co  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.dkf.jed2k.util.http.OKHTTPClient.java

License:Open Source License

private String getPostSyncResponse(Request.Builder builder) throws IOException {
    String result = null;/*ww w. ja  v a2 s.c o m*/
    final OkHttpClient okHttpClient = newOkHttpClient();
    final Response response = this.getSyncResponse(okHttpClient, builder);
    int httpResponseCode = response.code();

    if ((httpResponseCode != HttpURLConnection.HTTP_OK)
            && (httpResponseCode != HttpURLConnection.HTTP_PARTIAL)) {
        throw new ResponseCodeNotSupportedException(httpResponseCode);
    }

    if (canceled) {
        onCancel();
    } else {
        result = response.body().string();
        onComplete();
    }
    closeQuietly(response.body());
    return result;
}

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

License:Open Source License

/**
 * Pushes data to DHIS Server/*  w  w  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());
}