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;
}
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);
}
}
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);
}
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);
}
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);
}
Aggregations