Example usage for com.squareup.okhttp Call execute

List of usage examples for com.squareup.okhttp Call execute

Introduction

In this page you can find the example usage for com.squareup.okhttp Call execute.

Prototype

public Response execute() throws IOException 

Source Link

Document

Invokes the request immediately, and blocks until the response can be processed or is in error.

Usage

From source file:net.yatomiya.e4.util.StandardHttpClient.java

License:Open Source License

public Call execute(Request request, Callback callback, boolean isSynchronous) {
    Call call = newCall(request);
    if (isSynchronous) {
        try {//w  w  w . j  a  va 2s  .  co  m
            Response response = call.execute();
            callback.onResponse(response);
        } catch (IOException e) {
            callback.onFailure(request, e);
        }
    } else {
        call.enqueue(callback);
    }
    return call;
}

From source file:net.yatomiya.nicherry.services.bbs.BBSHttpClient.java

License:Open Source License

@Override
public Call execute(Request request, Callback callback, boolean isSynchronous) {
    Call call = newCall(request);
    if (isSynchronous) {
        try {//from   w w w .  ja  v  a  2  s  .c o m
            Response response = call.execute();
            callback.onResponse(response);
        } catch (IOException e) {
            callback.onFailure(request, e);
        }
    } else {
        call.enqueue(callback);
    }
    return call;
}

From source file:org.dataconservancy.cos.osf.client.retrofit.RetrofitOsfServiceFactory.java

License:Apache License

/**
 * Constructs a new RetrofitOsfServiceFactory with the supplied JSON configuration classpath resource.
 * Default implementations of the OSF and Waterbutler configuration services, Jackson {@code ObjectMapper}, and
 * {@code OkHttpClient} will be used.  If the classpath resource is <em>not</em> absolute (beginning with a
 * '{@code /}'), then this constructor will resolve the resource under
 * {@code /org/dataconservancy/cos/osf/client/config/}.  This constructor adds the {@link AuthInterceptor} to the
 * {@code OkHttpClient} if an {@code authHeader} is found in the configuration for the OSF v2 API.  It will
 * scan the classpath under {@code org.dataconservancy.cos.osf.client.model} for classes with the {@link Type}
 * annotation, and add them to the {@link com.github.jasminb.jsonapi.ResourceConverter} used to convert JSON
 * documents to Java objects.  The {@code ResourceConverter} is also configured to resolve urls using the
 * {@code OkHttpClient}.//from  w  w w  . j  a  v a2s. c o  m
 *
 * @param jsonConfigurationResource classpath resource containing the JSON configuration for the OSF and Waterbutler
 *                                  HTTP endpoints
 */
public RetrofitOsfServiceFactory(final String jsonConfigurationResource) {
    try {
        this.osfConfigSvc = new JacksonOsfConfigurationService(jsonConfigurationResource);
    } catch (Exception e) {
        throw new IllegalStateException(String.format(ERR_CONFIGURING_CLASS,
                JacksonOsfConfigurationService.class.getName(), e.getMessage()), e);
    }
    try {
        this.wbConfigSvc = new JacksonWbConfigurationService(jsonConfigurationResource);
    } catch (Exception e) {
        throw new IllegalStateException(String.format(ERR_CONFIGURING_CLASS,
                JacksonWbConfigurationService.class.getName(), e.getMessage()), e);
    }
    this.httpClient = new OkHttpClient();
    if (osfConfigSvc.getConfiguration().getAuthHeader() != null) {
        httpClient.interceptors().add(new AuthInterceptor(osfConfigSvc.getConfiguration().getAuthHeader()));
    }
    if (osfConfigSvc.getConfiguration().getApiVersion() != null) {
        httpClient.interceptors()
                .add(new ApiVersionInterceptor(osfConfigSvc.getConfiguration().getApiVersion()));
    }
    this.httpClient.setConnectTimeout(osfConfigSvc.getConfiguration().getConnect_timeout_ms(), MILLISECONDS);
    this.httpClient.setReadTimeout(osfConfigSvc.getConfiguration().getRead_timeout_ms(), MILLISECONDS);
    this.httpClient.setWriteTimeout(osfConfigSvc.getConfiguration().getWrite_timeout_ms(), MILLISECONDS);

    // ... the JSON-API converter used by Retrofit to map JSON documents to Java objects
    final List<Class<?>> domainClasses = new ArrayList<>();

    new FastClasspathScanner("org.dataconservancy.cos.osf.client.model")
            .matchClassesWithAnnotation(Type.class, domainClasses::add).scan();

    final ResourceConverter resourceConverter = new ResourceConverter(new ObjectMapper(),
            domainClasses.toArray(new Class[] {}));

    resourceConverter.setGlobalResolver(relUrl -> {
        final com.squareup.okhttp.Call req = httpClient.newCall(new Request.Builder().url(relUrl).build());
        try {
            return req.execute().body().bytes();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    });

    try {
        this.jsonApiConverterFactory = new JSONAPIConverterFactory(resourceConverter);
    } catch (Exception e) {
        throw new IllegalStateException(
                String.format(ERR_CONFIGURING_CLASS, JSONAPIConverterFactory.class.getName(), e.getMessage()),
                e);
    }
}

From source file:org.dataconservancy.cos.osf.client.retrofit.TestingOsfServiceFactory.java

License:Apache License

/**
 * Creates a new RetrofitOsfServiceFactory with default implementations for the required collaborators.  Not
 * recommended for production.// ww w .  j  a  va 2 s. c om
 *
 * @param jsonConfigurationResource a classpath resource containing the configuration for the OSF API; must be JSON
 */
public TestingOsfServiceFactory(final String jsonConfigurationResource) {
    // Configure the configuration service.
    osfConfigurationService = new JacksonOsfConfigurationService(jsonConfigurationResource);
    wbConfigurationService = new JacksonWbConfigurationService(jsonConfigurationResource);

    // Wiring for the RetrofitOsfService Factory

    // ... the OK HTTP client used by Retrofit to make calls
    httpClient = new OkHttpClient();
    httpClient.interceptors()
            .add(new AuthInterceptor(osfConfigurationService.getConfiguration().getAuthHeader()));

    // ... the JSON-API converter used by Retrofit to map JSON documents to Java objects
    final List<Class<?>> domainClasses = new ArrayList<>();

    new FastClasspathScanner("org.dataconservancy.cos.osf.client.model")
            .matchClassesWithAnnotation(Type.class, domainClasses::add).scan();

    final ResourceConverter resourceConverter = new ResourceConverter(new ObjectMapper(),
            domainClasses.toArray(new Class[] {}));

    resourceConverter.setGlobalResolver(relUrl -> {
        final com.squareup.okhttp.Call req = httpClient.newCall(new Request.Builder().url(relUrl).build());
        try {
            return req.execute().body().bytes();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    });

    final JSONAPIConverterFactory jsonApiConverterFactory = new PaginatedConverterFactory(httpClient,
            resourceConverter);

    factory = new RetrofitOsfServiceFactory(osfConfigurationService, wbConfigurationService, httpClient,
            jsonApiConverterFactory);
}

From source file:org.dataconservancy.cos.osf.client.service.RetrofitOsfServiceFactory.java

License:Apache License

/**
 * Constructs a new RetrofitOsfServiceFactory with the supplied JSON configuration classpath resource.
 * Default implementations of the OSF and Waterbutler configuration services, Jackson {@code ObjectMapper}, and
 * {@code OkHttpClient} will be used.  If the classpath resource is <em>not</em> absolute (beginning with a
 * '{@code /}'), then this constructor will resolve the resource under
 * {@code /org/dataconservancy/cos/osf/client/config/}.  This constructor adds the {@link AuthInterceptor} to the
 * {@code OkHttpClient} if an {@code authHeader} is found in the configuration for the OSF v2 API.  It will
 * scan the classpath under {@code org.dataconservancy.cos.osf.client.model} for classes with the {@link Type}
 * annotation, and add them to the {@link com.github.jasminb.jsonapi.ResourceConverter} used to convert JSON
 * documents to Java objects.  The {@code ResourceConverter} is also configured to resolve urls using the
 * {@code OkHttpClient}./*  ww w  . j  a v  a2s.  co  m*/
 *
 * @param jsonConfigurationResource classpath resource containing the JSON configuration for the OSF and Waterbutler
 *                                  HTTP endpoints
 */
public RetrofitOsfServiceFactory(String jsonConfigurationResource) {
    try {
        this.osfConfigSvc = new JacksonOsfConfigurationService(jsonConfigurationResource);
    } catch (Exception e) {
        throw new IllegalStateException(String.format(ERR_CONFIGURING_CLASS,
                JacksonOsfConfigurationService.class.getName(), e.getMessage()), e);
    }
    try {
        this.wbConfigSvc = new JacksonWbConfigurationService(jsonConfigurationResource);
    } catch (Exception e) {
        throw new IllegalStateException(String.format(ERR_CONFIGURING_CLASS,
                JacksonWbConfigurationService.class.getName(), e.getMessage()), e);
    }
    this.httpClient = new OkHttpClient();
    if (osfConfigSvc.getConfiguration().getAuthHeader() != null) {
        httpClient.interceptors().add(new AuthInterceptor(osfConfigSvc.getConfiguration().getAuthHeader()));
    }

    // ... the JSON-API converter used by Retrofit to map JSON documents to Java objects
    List<Class<?>> domainClasses = new ArrayList<>();

    new FastClasspathScanner("org.dataconservancy.cos.osf.client.model")
            .matchClassesWithAnnotation(Type.class, domainClasses::add).scan();

    ResourceConverter resourceConverter = new ResourceConverter(new ObjectMapper(),
            domainClasses.toArray(new Class[] {}));

    resourceConverter.setGlobalResolver(relUrl -> {
        com.squareup.okhttp.Call req = httpClient.newCall(new Request.Builder().url(relUrl).build());
        try {
            return req.execute().body().bytes();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    });

    try {
        this.jsonApiConverterFactory = new JSONAPIConverterFactory(resourceConverter);
    } catch (Exception e) {
        throw new IllegalStateException(
                String.format(ERR_CONFIGURING_CLASS, JSONAPIConverterFactory.class.getName(), e.getMessage()),
                e);
    }
}

From source file:org.dataconservancy.cos.osf.client.service.TestingOsfServiceFactory.java

License:Apache License

/**
 * Creates a new RetrofitOsfServiceFactory with default implementations for the required collaborators.  Not
 * recommended for production.//from   w  ww.j a v  a2s . c  om
 *
 * @param jsonConfigurationResource a classpath resource containing the configuration for the OSF API; must be JSON
 */
public TestingOsfServiceFactory(String jsonConfigurationResource) {
    // Configure the configuration service.
    osfConfigurationService = new JacksonOsfConfigurationService(jsonConfigurationResource);
    wbConfigurationService = new JacksonWbConfigurationService(jsonConfigurationResource);

    // Wiring for the RetrofitOsfService Factory

    // ... the OK HTTP client used by Retrofit to make calls
    httpClient = new OkHttpClient();
    httpClient.interceptors()
            .add(new AuthInterceptor(osfConfigurationService.getConfiguration().getAuthHeader()));

    // ... the JSON-API converter used by Retrofit to map JSON documents to Java objects
    List<Class<?>> domainClasses = new ArrayList<>();

    new FastClasspathScanner("org.dataconservancy.cos.osf.client.model")
            .matchClassesWithAnnotation(Type.class, domainClasses::add).scan();

    ResourceConverter resourceConverter = new ResourceConverter(new ObjectMapper(),
            domainClasses.toArray(new Class[] {}));

    resourceConverter.setGlobalResolver(relUrl -> {
        com.squareup.okhttp.Call req = httpClient.newCall(new Request.Builder().url(relUrl).build());
        try {
            return req.execute().body().bytes();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    });

    JSONAPIConverterFactory jsonApiConverterFactory = new JSONAPIConverterFactory(resourceConverter);

    factory = new RetrofitOsfServiceFactory(osfConfigurationService, wbConfigurationService, httpClient,
            jsonApiConverterFactory);
}

From source file:org.dataconservancy.cos.osf.client.support.ResourceConverterGlobalResolver.java

License:Apache License

@Override
public byte[] resolve(final String relationshipURL) {
    final com.squareup.okhttp.Call req = httpClient.newCall(new Request.Builder().url(relationshipURL).build());
    try {//from   ww w  .java2s .  co  m
        return req.execute().body().bytes();
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.dataconservancy.cos.packaging.OsfContentProviderTest.java

License:Apache License

@Test
public void testCreatePackageSimple() throws Exception {
    // Prepare the OSF registration and users information
    factory.interceptors().add(new RecursiveInterceptor(testName, OsfContentProviderTest.class, getBaseUri()));
    final OsfService osfService = factory.getOsfService(OsfService.class);
    final String registrationId = "eq7a4";
    final Registration registration = osfService.registration(registrationId).execute().body();

    final List<User> users = registration.getContributors().stream().map(c -> {
        try {/*w ww.j ava  2s.  c o  m*/
            return osfService.user(c.getId()).execute().body();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }).collect(Collectors.toList());

    // Prepare package graph and print it to StdErr.
    final OsfPackageGraph packageGraph = new OsfPackageGraph(ontologyManager);
    packageGraph.add(registration);
    users.forEach(packageGraph::add);
    packageGraph.serialize(System.err, RDFFormat.TURTLE_PRETTY, packageGraph.OSF_SELECTOR);

    // Prepare content provider using package graph
    OsfContentProvider contentProvider = new OsfContentProvider(packageGraph, (String url) -> {
        Call req = factory.getHttpClient().newCall(new Request.Builder().url(url).build());
        try {
            return req.execute().body().bytes();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    });

    // Read package generation parameters from a resource file.
    InputStream paramStream = OsfContentProvider.class
            .getResourceAsStream("/PackageGenerationParams.properties");

    // Create the package in the default location with the default name.
    // No metatdata is supplied.
    IpmPackager packager = new IpmPackager();
    packager.buildPackage(contentProvider, null, paramStream);
    contentProvider.close();
}

From source file:org.dataconservancy.cos.packaging.OsfContentProviderTest.java

License:Apache License

@Test
public void testCreatePackageWithWiki() throws Exception {
    final OsfPackageGraph packageGraph = new OsfPackageGraph(ontologyManager);
    factory.interceptors().add(new RecursiveInterceptor(testName, OsfContentProviderTest.class, getBaseUri()));
    final OsfService osfService = factory.getOsfService(OsfService.class);
    final String registrationId = "ng9em";

    final PackageGenerationParameters params = new PropertiesConfigurationParametersBuilder().buildParameters(
            OsfContentProviderTest.class.getResourceAsStream("/PackageGenerationParams.properties"));

    params.addParam(GeneralParameterNames.PACKAGE_LOCATION, System.getProperty("java.io.tmpdir"));

    params.addParam(GeneralParameterNames.PACKAGE_NAME, "WikiPackage");
    final Registration registration = osfService.registration(registrationId).execute().body();
    final List<User> users = registration.getContributors().stream().map(c -> {
        try {/* w w w . j  a  v  a  2  s . c  o m*/
            return osfService.user(c.getId()).execute().body();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }).collect(Collectors.toList());

    packageGraph.add(registration);
    users.forEach(packageGraph::add);

    //List<Wiki> wikis = osfService.wikis("http://localhost:8000/v2/registrations/ng9em/wikis/").execute().body();
    packageGraph.serialize(System.err, RDFFormat.TURTLE_PRETTY, packageGraph.OSF_SELECTOR);

    OsfContentProvider contentProvider = new OsfContentProvider(packageGraph, (String url) -> {
        Call req = factory.getHttpClient().newCall(new Request.Builder().url(url).build());
        try {
            return req.execute().body().bytes();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    });

    // Read package generation parameters from a resource file.
    InputStream paramStream = OsfContentProvider.class
            .getResourceAsStream("/PackageGenerationParams.properties");

    IpmPackager packager = new IpmPackager();
    packager.buildPackage(contentProvider, null, paramStream);
    contentProvider.close();
}

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

License:Apache License

private <L> void performResourceSync(
        InventoryStructure<org.hawkular.inventory.api.model.Resource.Blueprint> resourceStructure,
        String tenantIdToUse, int totalResourceCount) {

    if (resourceStructure.getRoot() != null) {
        try {//from  ww  w.  jav a 2s  .c  o m
            SyncConfiguration syncConfig = SyncConfiguration.builder().withAllTypes().build();
            SyncRequest<org.hawkular.inventory.api.model.Resource.Blueprint> sync;
            sync = new SyncRequest<>(syncConfig, resourceStructure);

            StringBuilder url = Util.getContextUrlString(AsyncInventoryStorage.this.config.getUrl(),
                    AsyncInventoryStorage.this.config.getInventoryContext());
            url.append("sync");
            url.append("/f;").append(this.feedId);
            url.append("/r;").append(Util.urlEncode(resourceStructure.getRoot().getId()));
            String jsonPayload = Util.toJson(sync);
            Map<String, String> headers = getTenantHeader(tenantIdToUse);

            log.tracef("Syncing [%d] resources to inventory: headers=[%s] body=[%s]", totalResourceCount,
                    headers, jsonPayload);

            Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), headers, jsonPayload);
            Call call = this.httpClientBuilder.getHttpClient().newCall(request);
            final Timer.Context timer = diagnostics.getInventoryStorageRequestTimer().time();
            Response response = call.execute();

            try {
                final long durationNanos = timer.stop();

                log.tracef("Received sync response from inventory: code [%d]", response.code());

                // HTTP status of 204 means success, anything else is an error
                if (response.code() != 204) {
                    throw new Exception("status-code=[" + response.code() + "], reason=[" + response.message()
                            + "], url=[" + request.urlString() + "]");
                }

                diagnostics.getInventoryRate().mark(totalResourceCount);

                if (log.isDebugEnabled()) {
                    log.debugf("Took [%d]ms to sync [%d] resources to inventory",
                            TimeUnit.MILLISECONDS.convert(durationNanos, TimeUnit.NANOSECONDS),
                            totalResourceCount);
                }
            } 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;
}