Search in sources :

Example 11 with DocumentStatus

use of com.ibm.watson.language_translator.v3.model.DocumentStatus in project java-sdk by watson-developer-cloud.

the class DiscoveryQueryExample method main.

public static void main(String[] args) {
    Authenticator authenticator = new IamAuthenticator("<iam_api_key>");
    Discovery discovery = new Discovery("2019-04-30", authenticator);
    String environmentId = null;
    String configurationId = null;
    String collectionId = null;
    String documentId = null;
    // See if an environment already exists
    System.out.println("Check if environment exists");
    ListEnvironmentsOptions listOptions = new ListEnvironmentsOptions.Builder().build();
    ListEnvironmentsResponse listResponse = discovery.listEnvironments(listOptions).execute().getResult();
    for (Environment environment : listResponse.getEnvironments()) {
        // look for an existing environment that isn't read only
        if (!environment.isReadOnly()) {
            environmentId = environment.getEnvironmentId();
            System.out.println("Found existing environment ID: " + environmentId);
            break;
        }
    }
    if (environmentId == null) {
        System.out.println("No environment found, creating new one...");
        // no environment found, create a new one (assuming we are a FREE plan)
        String environmentName = "watson_developer_cloud_test_environment";
        CreateEnvironmentOptions createOptions = new CreateEnvironmentOptions.Builder().name(environmentName).size(String.valueOf(0L)).build();
        Environment createResponse = discovery.createEnvironment(createOptions).execute().getResult();
        environmentId = createResponse.getEnvironmentId();
        System.out.println("Created new environment ID: " + environmentId);
        // wait for environment to be ready
        System.out.println("Waiting for environment to be ready...");
        boolean environmentReady = false;
        while (!environmentReady) {
            GetEnvironmentOptions getEnvironmentOptions = new GetEnvironmentOptions.Builder(environmentId).build();
            Environment getEnvironmentResponse = discovery.getEnvironment(getEnvironmentOptions).execute().getResult();
            environmentReady = getEnvironmentResponse.getStatus().equals(Environment.Status.ACTIVE);
            try {
                if (!environmentReady) {
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException("Interrupted", e);
            }
        }
        System.out.println("Environment Ready!");
    }
    // find the default configuration
    System.out.println("Finding the default configuration");
    ListConfigurationsOptions listConfigsOptions = new ListConfigurationsOptions.Builder(environmentId).build();
    ListConfigurationsResponse listConfigsResponse = discovery.listConfigurations(listConfigsOptions).execute().getResult();
    for (Configuration configuration : listConfigsResponse.getConfigurations()) {
        if (configuration.name().equals(DEFAULT_CONFIG_NAME)) {
            configurationId = configuration.configurationId();
            System.out.println("Found default configuration ID: " + configurationId);
            break;
        }
    }
    // create a new collection
    System.out.println("Creating a new collection...");
    String collectionName = "my_watson_developer_cloud_collection";
    CreateCollectionOptions createCollectionOptions = new CreateCollectionOptions.Builder(environmentId, collectionName).configurationId(configurationId).build();
    Collection collection = discovery.createCollection(createCollectionOptions).execute().getResult();
    collectionId = collection.getCollectionId();
    System.out.println("Created a collection ID: " + collectionId);
    // wait for the collection to be "available"
    System.out.println("Waiting for collection to be ready...");
    boolean collectionReady = false;
    while (!collectionReady) {
        GetCollectionOptions getCollectionOptions = new GetCollectionOptions.Builder(environmentId, collectionId).build();
        Collection getCollectionResponse = discovery.getCollection(getCollectionOptions).execute().getResult();
        collectionReady = getCollectionResponse.getStatus().equals(Collection.Status.ACTIVE);
        try {
            if (!collectionReady) {
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted", e);
        }
    }
    System.out.println("Collection Ready!");
    // add a document
    System.out.println("Creating a new document...");
    String documentJson = "{\"field\":\"value\"}";
    InputStream documentStream = new ByteArrayInputStream(documentJson.getBytes());
    AddDocumentOptions.Builder createDocumentBuilder = new AddDocumentOptions.Builder(environmentId, collectionId);
    createDocumentBuilder.file(documentStream).fileContentType(HttpMediaType.APPLICATION_JSON);
    DocumentAccepted createDocumentResponse = discovery.addDocument(createDocumentBuilder.build()).execute().getResult();
    documentId = createDocumentResponse.getDocumentId();
    System.out.println("Created a document ID: " + documentId);
    // wait for document to be ready
    System.out.println("Waiting for document to be ready...");
    boolean documentReady = false;
    while (!documentReady) {
        GetDocumentStatusOptions getDocumentStatusOptions = new GetDocumentStatusOptions.Builder(environmentId, collectionId, documentId).build();
        DocumentStatus getDocumentResponse = discovery.getDocumentStatus(getDocumentStatusOptions).execute().getResult();
        documentReady = !getDocumentResponse.getStatus().equals(DocumentStatus.Status.PROCESSING);
        try {
            if (!documentReady) {
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted");
        }
    }
    System.out.println("Document Ready!");
    // query document
    System.out.println("Querying the collection...");
    QueryOptions.Builder queryBuilder = new QueryOptions.Builder(environmentId, collectionId);
    queryBuilder.query("field:value");
    QueryResponse queryResponse = discovery.query(queryBuilder.build()).execute().getResult();
    // print out the results
    System.out.println("Query Results:");
    System.out.println(queryResponse);
    // cleanup the collection created
    System.out.println("Deleting the collection...");
    DeleteCollectionOptions deleteOptions = new DeleteCollectionOptions.Builder(environmentId, collectionId).build();
    discovery.deleteCollection(deleteOptions).execute();
    System.out.println("Collection deleted!");
    System.out.println("Discovery example finished");
}
Also used : Configuration(com.ibm.watson.discovery.v1.model.Configuration) IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) QueryOptions(com.ibm.watson.discovery.v1.model.QueryOptions) GetEnvironmentOptions(com.ibm.watson.discovery.v1.model.GetEnvironmentOptions) GetCollectionOptions(com.ibm.watson.discovery.v1.model.GetCollectionOptions) IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) Authenticator(com.ibm.cloud.sdk.core.security.Authenticator) DocumentAccepted(com.ibm.watson.discovery.v1.model.DocumentAccepted) ListConfigurationsResponse(com.ibm.watson.discovery.v1.model.ListConfigurationsResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ListConfigurationsOptions(com.ibm.watson.discovery.v1.model.ListConfigurationsOptions) GetDocumentStatusOptions(com.ibm.watson.discovery.v1.model.GetDocumentStatusOptions) DeleteCollectionOptions(com.ibm.watson.discovery.v1.model.DeleteCollectionOptions) ListEnvironmentsResponse(com.ibm.watson.discovery.v1.model.ListEnvironmentsResponse) DocumentStatus(com.ibm.watson.discovery.v1.model.DocumentStatus) ByteArrayInputStream(java.io.ByteArrayInputStream) AddDocumentOptions(com.ibm.watson.discovery.v1.model.AddDocumentOptions) QueryResponse(com.ibm.watson.discovery.v1.model.QueryResponse) CreateEnvironmentOptions(com.ibm.watson.discovery.v1.model.CreateEnvironmentOptions) Environment(com.ibm.watson.discovery.v1.model.Environment) CreateCollectionOptions(com.ibm.watson.discovery.v1.model.CreateCollectionOptions) Collection(com.ibm.watson.discovery.v1.model.Collection) ListEnvironmentsOptions(com.ibm.watson.discovery.v1.model.ListEnvironmentsOptions)

Example 12 with DocumentStatus

use of com.ibm.watson.language_translator.v3.model.DocumentStatus in project java-sdk by watson-developer-cloud.

the class LanguageTranslatorTest method testTranslateDocumentWOptions.

// Test the translateDocument operation with a valid options model parameter
@Test
public void testTranslateDocumentWOptions() throws Throwable {
    // Register a mock response
    String mockResponseBody = "{\"document_id\": \"documentId\", \"filename\": \"filename\", \"status\": \"processing\", \"model_id\": \"modelId\", \"base_model_id\": \"baseModelId\", \"source\": \"source\", \"detected_language_confidence\": 0, \"target\": \"target\", \"created\": \"2019-01-01T12:00:00.000Z\", \"completed\": \"2019-01-01T12:00:00.000Z\", \"word_count\": 9, \"character_count\": 14}";
    String translateDocumentPath = "/v3/documents";
    server.enqueue(new MockResponse().setHeader("Content-type", "application/json").setResponseCode(202).setBody(mockResponseBody));
    // Construct an instance of the TranslateDocumentOptions model
    TranslateDocumentOptions translateDocumentOptionsModel = new TranslateDocumentOptions.Builder().file(TestUtilities.createMockStream("This is a mock file.")).filename("testString").fileContentType("application/powerpoint").modelId("testString").source("testString").target("testString").documentId("testString").build();
    // Invoke translateDocument() with a valid options model and verify the result
    Response<DocumentStatus> response = languageTranslatorService.translateDocument(translateDocumentOptionsModel).execute();
    assertNotNull(response);
    DocumentStatus responseObj = response.getResult();
    assertNotNull(responseObj);
    // Verify the contents of the request sent to the mock server
    RecordedRequest request = server.takeRequest();
    assertNotNull(request);
    assertEquals(request.getMethod(), "POST");
    // Verify request path
    String parsedPath = TestUtilities.parseReqPath(request);
    assertEquals(parsedPath, translateDocumentPath);
    // Verify query params
    Map<String, String> query = TestUtilities.parseQueryString(request);
    assertNotNull(query);
    assertEquals(query.get("version"), "2018-05-01");
}
Also used : DocumentStatus(com.ibm.watson.language_translator.v3.model.DocumentStatus) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) TranslateDocumentOptions(com.ibm.watson.language_translator.v3.model.TranslateDocumentOptions) Test(org.testng.annotations.Test)

Example 13 with DocumentStatus

use of com.ibm.watson.language_translator.v3.model.DocumentStatus in project java-sdk by watson-developer-cloud.

the class LanguageTranslatorTest method testGetDocumentStatusWOptions.

// Test the getDocumentStatus operation with a valid options model parameter
@Test
public void testGetDocumentStatusWOptions() throws Throwable {
    // Register a mock response
    String mockResponseBody = "{\"document_id\": \"documentId\", \"filename\": \"filename\", \"status\": \"processing\", \"model_id\": \"modelId\", \"base_model_id\": \"baseModelId\", \"source\": \"source\", \"detected_language_confidence\": 0, \"target\": \"target\", \"created\": \"2019-01-01T12:00:00.000Z\", \"completed\": \"2019-01-01T12:00:00.000Z\", \"word_count\": 9, \"character_count\": 14}";
    String getDocumentStatusPath = "/v3/documents/testString";
    server.enqueue(new MockResponse().setHeader("Content-type", "application/json").setResponseCode(200).setBody(mockResponseBody));
    // Construct an instance of the GetDocumentStatusOptions model
    GetDocumentStatusOptions getDocumentStatusOptionsModel = new GetDocumentStatusOptions.Builder().documentId("testString").build();
    // Invoke getDocumentStatus() with a valid options model and verify the result
    Response<DocumentStatus> response = languageTranslatorService.getDocumentStatus(getDocumentStatusOptionsModel).execute();
    assertNotNull(response);
    DocumentStatus responseObj = response.getResult();
    assertNotNull(responseObj);
    // Verify the contents of the request sent to the mock server
    RecordedRequest request = server.takeRequest();
    assertNotNull(request);
    assertEquals(request.getMethod(), "GET");
    // Verify request path
    String parsedPath = TestUtilities.parseReqPath(request);
    assertEquals(parsedPath, getDocumentStatusPath);
    // Verify query params
    Map<String, String> query = TestUtilities.parseQueryString(request);
    assertNotNull(query);
    assertEquals(query.get("version"), "2018-05-01");
}
Also used : DocumentStatus(com.ibm.watson.language_translator.v3.model.DocumentStatus) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) GetDocumentStatusOptions(com.ibm.watson.language_translator.v3.model.GetDocumentStatusOptions) Test(org.testng.annotations.Test)

Example 14 with DocumentStatus

use of com.ibm.watson.language_translator.v3.model.DocumentStatus in project java-sdk by watson-developer-cloud.

the class DiscoveryServiceTest method getDocumentIsSuccessful.

/**
 * Gets the document is successful.
 *
 * @throws InterruptedException the interrupted exception
 */
@Test
public void getDocumentIsSuccessful() throws InterruptedException {
    server.enqueue(jsonResponse(getDocResp));
    GetDocumentStatusOptions getRequest = new GetDocumentStatusOptions.Builder(environmentId, collectionId, documentId).build();
    DocumentStatus response = discoveryService.getDocumentStatus(getRequest).execute().getResult();
    RecordedRequest request = server.takeRequest();
    assertEquals(DOCS2_PATH, request.getPath());
    assertEquals(GET, request.getMethod());
    assertEquals(getDocResp, response);
}
Also used : DocumentStatus(com.ibm.watson.discovery.v1.model.DocumentStatus) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) GetDocumentStatusOptions(com.ibm.watson.discovery.v1.model.GetDocumentStatusOptions) WatsonServiceUnitTest(com.ibm.watson.common.WatsonServiceUnitTest)

Aggregations

DocumentStatus (com.ibm.watson.developer_cloud.discovery.v1.model.DocumentStatus)6 GetDocumentStatusOptions (com.ibm.watson.developer_cloud.discovery.v1.model.GetDocumentStatusOptions)5 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)5 Test (org.junit.Test)5 WatsonServiceTest (com.ibm.watson.developer_cloud.WatsonServiceTest)4 Collection (com.ibm.watson.developer_cloud.discovery.v1.model.Collection)4 DocumentAccepted (com.ibm.watson.developer_cloud.discovery.v1.model.DocumentAccepted)4 DocumentStatus (com.ibm.watson.discovery.v1.model.DocumentStatus)4 DocumentStatus (com.ibm.watson.language_translator.v3.model.DocumentStatus)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 InputStream (java.io.InputStream)4 RequestBuilder (com.ibm.cloud.sdk.core.http.RequestBuilder)3 GetDocumentStatusOptions (com.ibm.watson.discovery.v1.model.GetDocumentStatusOptions)3 MockResponse (okhttp3.mockwebserver.MockResponse)3 Test (org.testng.annotations.Test)3 AddDocumentOptions (com.ibm.watson.developer_cloud.discovery.v1.model.AddDocumentOptions)2 Configuration (com.ibm.watson.developer_cloud.discovery.v1.model.Configuration)2 UpdateDocumentOptions (com.ibm.watson.developer_cloud.discovery.v1.model.UpdateDocumentOptions)2 FileInputStream (java.io.FileInputStream)2 HashMap (java.util.HashMap)2