Search in sources :

Example 16 with Profile

use of com.ibm.watson.personality_insights.v3.model.Profile in project concord by walmartlabs.

the class Run method call.

@Override
public Integer call() throws Exception {
    sourceDir = sourceDir.normalize().toAbsolutePath();
    Path targetDir;
    if (Files.isRegularFile(sourceDir)) {
        Path src = sourceDir.toAbsolutePath();
        System.out.println("Running a single Concord file: " + src);
        targetDir = Files.createTempDirectory("payload");
        Files.copy(src, targetDir.resolve("concord.yml"), StandardCopyOption.REPLACE_EXISTING);
    } else if (Files.isDirectory(sourceDir)) {
        targetDir = sourceDir.resolve("target");
        if (cleanup && Files.exists(targetDir)) {
            if (verbose) {
                System.out.println("Cleaning target directory");
            }
            IOUtils.deleteRecursively(targetDir);
        }
        // copy everything into target except target
        IOUtils.copy(sourceDir, targetDir, "^target$", new CopyNotifier(verbose ? 0 : 100), StandardCopyOption.REPLACE_EXISTING);
    } else {
        throw new IllegalArgumentException("Not a directory or single Concord YAML file: " + sourceDir);
    }
    DependencyManager dependencyManager = initDependencyManager();
    ImportManager importManager = new ImportManagerFactory(dependencyManager, new CliRepositoryExporter(repoCacheDir), Collections.emptySet()).create();
    ProjectLoaderV2.Result loadResult;
    try {
        loadResult = new ProjectLoaderV2(importManager).load(targetDir, new CliImportsNormalizer(importsSource, verbose, defaultVersion), verbose ? new CliImportsListener() : null);
    } catch (ImportProcessingException e) {
        ObjectMapper om = new ObjectMapper();
        System.err.println("Error while processing import " + om.writeValueAsString(e.getImport()) + ": " + e.getMessage());
        return -1;
    } catch (Exception e) {
        System.err.println("Error while loading " + targetDir);
        e.printStackTrace();
        return -1;
    }
    ProcessDefinition processDefinition = loadResult.getProjectDefinition();
    UUID instanceId = UUID.randomUUID();
    if (verbose && !extraVars.isEmpty()) {
        System.out.println("Additional variables: " + extraVars);
    }
    if (verbose && !profiles.isEmpty()) {
        System.out.println("Active profiles: " + profiles);
    }
    ProcessConfiguration cfg = from(processDefinition.configuration()).entryPoint(entryPoint).instanceId(instanceId).build();
    RunnerConfiguration runnerCfg = RunnerConfiguration.builder().dependencies(new DependencyResolver(dependencyManager, verbose).resolveDeps(processDefinition)).debug(cfg.debug()).build();
    Map<String, Object> profileArgs = getProfilesArguments(processDefinition, profiles);
    Map<String, Object> args = ConfigurationUtils.deepMerge(cfg.arguments(), profileArgs, extraVars);
    if (verbose) {
        System.out.println("Process arguments: " + args);
    }
    args.put(Constants.Context.TX_ID_KEY, instanceId.toString());
    args.put(Constants.Context.WORK_DIR_KEY, targetDir.toAbsolutePath().toString());
    if (effectiveYaml) {
        Map<String, List<Step>> flows = new HashMap<>(processDefinition.flows());
        for (String ap : profiles) {
            Profile p = processDefinition.profiles().get(ap);
            if (p != null) {
                flows.putAll(p.flows());
            }
        }
        ProcessDefinition pd = ProcessDefinition.builder().from(processDefinition).configuration(ProcessDefinitionConfiguration.builder().from(processDefinition.configuration()).arguments(args).build()).flows(flows).imports(Imports.builder().build()).profiles(Collections.emptyMap()).build();
        ProjectSerializerV2 serializer = new ProjectSerializerV2();
        serializer.write(pd, System.out);
        return 0;
    }
    System.out.println("Starting...");
    Injector injector = new InjectorFactory(new WorkingDirectory(targetDir), runnerCfg, () -> cfg, new ProcessDependenciesModule(targetDir, runnerCfg.dependencies(), cfg.debug()), new CliServicesModule(secretStoreDir, targetDir, new VaultProvider(vaultDir, vaultId), dependencyManager)).create();
    Runner runner = injector.getInstance(Runner.class);
    if (cfg.debug()) {
        System.out.println("Available tasks: " + injector.getInstance(TaskProviders.class).names());
    }
    try {
        runner.start(cfg, processDefinition, args);
    } catch (Exception e) {
        if (verbose) {
            System.err.print("Error: ");
            e.printStackTrace(System.err);
        } else {
            System.err.println("Error: " + e.getMessage());
        }
        return 1;
    }
    System.out.println("...done!");
    return 0;
}
Also used : ImportManager(com.walmartlabs.concord.imports.ImportManager) Runner(com.walmartlabs.concord.runtime.v2.runner.Runner) DependencyManager(com.walmartlabs.concord.dependencymanager.DependencyManager) ProcessDefinition(com.walmartlabs.concord.runtime.v2.model.ProcessDefinition) Profile(com.walmartlabs.concord.runtime.v2.model.Profile) ProjectSerializerV2(com.walmartlabs.concord.runtime.v2.ProjectSerializerV2) ImmutableProcessConfiguration(com.walmartlabs.concord.runtime.v2.sdk.ImmutableProcessConfiguration) ProcessConfiguration(com.walmartlabs.concord.runtime.v2.sdk.ProcessConfiguration) InjectorFactory(com.walmartlabs.concord.runtime.v2.runner.InjectorFactory) Injector(com.google.inject.Injector) RunnerConfiguration(com.walmartlabs.concord.runtime.common.cfg.RunnerConfiguration) ImportManagerFactory(com.walmartlabs.concord.imports.ImportManagerFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Path(java.nio.file.Path) WorkingDirectory(com.walmartlabs.concord.runtime.v2.sdk.WorkingDirectory) ImportProcessingException(com.walmartlabs.concord.imports.ImportProcessingException) ProcessDependenciesModule(com.walmartlabs.concord.runtime.v2.runner.guice.ProcessDependenciesModule) IOException(java.io.IOException) ImportProcessingException(com.walmartlabs.concord.imports.ImportProcessingException) ProjectLoaderV2(com.walmartlabs.concord.runtime.v2.ProjectLoaderV2) TaskProviders(com.walmartlabs.concord.runtime.v2.runner.tasks.TaskProviders)

Example 17 with Profile

use of com.ibm.watson.personality_insights.v3.model.Profile in project android-sdk-button by getyoti.

the class CallbackIntentService method handleActionRetrieveProfile.

/**
 * Handle action Retrieve profile in the provided background thread with the provided
 * parameters - accepting the Yoti callbackURL, token and fullURL (a combination of token and callback)
 */
private void handleActionRetrieveProfile(String callbackUrl, String token, String fullUrl) {
    byte[] response = new byte[0];
    try {
        // This will be the Url to your backend.
        // If you are already using the callback Url specified in the settings of your
        // application (in dashboard) for your web SDK for example, you will have to define a
        // new endpoint in your backend that deals with json responses.
        URL url = new URL(fullUrl.replace("profile", "profile-json"));
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        response = getBytes(urlConnection);
    } catch (IOException e) {
        Log.e(TAG, "Error when calling our backend manually!", e);
    }
    Gson g = new GsonBuilder().create();
    try {
        Profile profile = g.fromJson(new String(response), Profile.class);
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra(NAME_EXTRA, profile.getGivenNames() + " " + profile.getFamilyName());
        intent.putExtra(EMAIL_EXTRA, profile.getEmailAddress());
        intent.putExtra(IMAGE_EXTRA, profile.getSelfie());
        intent.putExtra(DOB_EXTRA, profile.getDateOfBirth());
        intent.putExtra(ADDRESS_EXTRA, profile.getPostalAddress());
        intent.putExtra(MOBILE_EXTRA, profile.getMobNum());
        intent.putExtra(GENDER_EXTRA, profile.getGender());
        intent.putExtra(PROFILE_EXTRA, true);
        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    } catch (Exception e) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra(BACKEND_DATA_ERROR_EXTRA, true);
        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}
Also used : GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) Intent(android.content.Intent) IOException(java.io.IOException) MainActivity(com.yoti.mobile.android.sampleapp2.MainActivity) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Profile(com.yoti.mobile.android.sampleapp2.model.Profile) IOException(java.io.IOException)

Example 18 with Profile

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

the class PersonalityInsights method profile.

/**
 * Get profile.
 *
 * <p>Generates a personality profile for the author of the input text. The service accepts a
 * maximum of 20 MB of input content, but it requires much less text to produce an accurate
 * profile. The service can analyze text in Arabic, English, Japanese, Korean, or Spanish. It can
 * return its results in a variety of languages.
 *
 * <p>**See also:** * [Requesting a
 * profile](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#input)
 * * [Providing sufficient
 * input](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#sufficient)
 *
 * <p>### Content types
 *
 * <p>You can provide input content as plain text (`text/plain`), HTML (`text/html`), or JSON
 * (`application/json`) by specifying the **Content-Type** parameter. The default is `text/plain`.
 * * Per the JSON specification, the default character encoding for JSON content is effectively
 * always UTF-8. * Per the HTTP specification, the default encoding for plain text and HTML is
 * ISO-8859-1 (effectively, the ASCII character set).
 *
 * <p>When specifying a content type of plain text or HTML, include the `charset` parameter to
 * indicate the character encoding of the input text; for example, `Content-Type:
 * text/plain;charset=utf-8`.
 *
 * <p>**See also:** [Specifying request and response
 * formats](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#formats)
 *
 * <p>### Accept types
 *
 * <p>You must request a response as JSON (`application/json`) or comma-separated values
 * (`text/csv`) by specifying the **Accept** parameter. CSV output includes a fixed number of
 * columns. Set the **csv_headers** parameter to `true` to request optional column headers for CSV
 * output.
 *
 * <p>**See also:** * [Understanding a JSON
 * profile](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-output#output)
 * * [Understanding a CSV
 * profile](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-outputCSV#outputCSV).
 *
 * @param profileOptions the {@link ProfileOptions} containing the options for the call
 * @return a {@link ServiceCall} with a result of type {@link Profile}
 */
public ServiceCall<Profile> profile(ProfileOptions profileOptions) {
    com.ibm.cloud.sdk.core.util.Validator.notNull(profileOptions, "profileOptions cannot be null");
    RequestBuilder builder = RequestBuilder.post(RequestBuilder.resolveRequestUrl(getServiceUrl(), "/v3/profile"));
    Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("personality_insights", "v3", "profile");
    for (Entry<String, String> header : sdkHeaders.entrySet()) {
        builder.header(header.getKey(), header.getValue());
    }
    builder.header("Accept", "application/json");
    if (profileOptions.contentType() != null) {
        builder.header("Content-Type", profileOptions.contentType());
    }
    if (profileOptions.contentLanguage() != null) {
        builder.header("Content-Language", profileOptions.contentLanguage());
    }
    if (profileOptions.acceptLanguage() != null) {
        builder.header("Accept-Language", profileOptions.acceptLanguage());
    }
    builder.query("version", String.valueOf(this.version));
    if (profileOptions.rawScores() != null) {
        builder.query("raw_scores", String.valueOf(profileOptions.rawScores()));
    }
    if (profileOptions.csvHeaders() != null) {
        builder.query("csv_headers", String.valueOf(profileOptions.csvHeaders()));
    }
    if (profileOptions.consumptionPreferences() != null) {
        builder.query("consumption_preferences", String.valueOf(profileOptions.consumptionPreferences()));
    }
    builder.bodyContent(profileOptions.contentType(), profileOptions.content(), null, profileOptions.body());
    ResponseConverter<Profile> responseConverter = ResponseConverterUtils.getValue(new com.google.gson.reflect.TypeToken<Profile>() {
    }.getType());
    return createServiceCall(builder.build(), responseConverter);
}
Also used : RequestBuilder(com.ibm.cloud.sdk.core.http.RequestBuilder) Profile(com.ibm.watson.personality_insights.v3.model.Profile)

Example 19 with Profile

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

the class PersonalityInsightsIT method getProfileWithTextAsCSVWithHeaders.

/**
 * Gets the profile with text as a CSV string with headers.
 *
 * @throws Exception the exception
 */
@Test
public void getProfileWithTextAsCSVWithHeaders() throws Exception {
    File file = new File(RESOURCE + "en.txt");
    String englishText = getStringFromInputStream(new FileInputStream(file));
    ProfileOptions options = new ProfileOptions.Builder().text(englishText).csvHeaders(true).build();
    InputStream result = service.profileAsCsv(options).execute().getResult();
    String profileString = CharStreams.toString(new InputStreamReader(result, "UTF-8"));
    Assert.assertNotNull(profileString);
    Assert.assertTrue(profileString.split("\n").length == 2);
}
Also used : ProfileOptions(com.ibm.watson.personality_insights.v3.model.ProfileOptions) InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) File(java.io.File) FileInputStream(java.io.FileInputStream) WatsonServiceTest(com.ibm.watson.common.WatsonServiceTest) Test(org.junit.Test)

Example 20 with Profile

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

the class PersonalityInsightsIT method getProfileWithASingleSpanishContentItem.

/**
 * Gets the profile from a single content item in Spanish.
 *
 * @throws Exception the exception
 */
@Test
public void getProfileWithASingleSpanishContentItem() throws Exception {
    File file = new File(RESOURCE + "es.txt");
    String englishText = getStringFromInputStream(new FileInputStream(file));
    ContentItem cItem = new ContentItem.Builder(englishText).language(ContentItem.Language.ES).build();
    Content content = new Content.Builder().contentItems(Collections.singletonList(cItem)).build();
    ProfileOptions options = new ProfileOptions.Builder().content(content).consumptionPreferences(true).rawScores(true).build();
    Profile profile = service.profile(options).execute().getResult();
    assertProfile(profile);
}
Also used : ProfileOptions(com.ibm.watson.personality_insights.v3.model.ProfileOptions) Content(com.ibm.watson.personality_insights.v3.model.Content) File(java.io.File) FileInputStream(java.io.FileInputStream) ContentItem(com.ibm.watson.personality_insights.v3.model.ContentItem) Profile(com.ibm.watson.personality_insights.v3.model.Profile) WatsonServiceTest(com.ibm.watson.common.WatsonServiceTest) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)15 Profile (com.ibm.watson.developer_cloud.personality_insights.v3.model.Profile)10 ProfileOptions (com.ibm.watson.developer_cloud.personality_insights.v3.model.ProfileOptions)9 ProfileOptions (com.ibm.watson.personality_insights.v3.model.ProfileOptions)9 File (java.io.File)8 FileInputStream (java.io.FileInputStream)8 WatsonServiceTest (com.ibm.watson.common.WatsonServiceTest)7 Profile (com.ibm.watson.personality_insights.v3.model.Profile)7 WatsonServiceTest (com.ibm.watson.developer_cloud.WatsonServiceTest)5 Content (com.ibm.watson.personality_insights.v3.model.Content)5 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)5 Content (com.ibm.watson.developer_cloud.personality_insights.v3.model.Content)4 ContentItem (com.ibm.watson.personality_insights.v3.model.ContentItem)4 WatsonServiceUnitTest (com.ibm.watson.developer_cloud.WatsonServiceUnitTest)3 InputStream (java.io.InputStream)3 ContentItem (com.ibm.watson.developer_cloud.personality_insights.v3.model.ContentItem)2 IOException (java.io.IOException)2 Intent (android.content.Intent)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Gson (com.google.gson.Gson)1