Test Java API for IBM Watson discovery service
Discovery discovery = new Discovery("2017-09-01");
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();
Should work without throwing any exception.
An exception is thrown on the last statment "discovery.addDocument"; error message is "filename cannot be null when file is not null"
Since you are using documentJson parameter, are you sure that JSON metadata has fileName. If not define a string with variable name fileName.
FYR Add Document to Discovery
Discovery discovery = new Discovery("2017-11-07");
discovery.setEndPoint("https://gateway.watsonplatform.net/discovery/api/");
discovery.setUsernameAndPassword("{username}", "{password}");
String environmentId = "{environment_id}";
String collectionId = "{collection_id}";
String documentId = "{document_id}";
String fileName = "<fileName>";
FYI - You cannot use documentStream and fileName parameter together
Related
I'm trying to send email with inline attachment using MS Graph. I know how to send email without attachment but when I'm trying to send message with attachment I don't know how can I add this attachment to the message.
Here is my code:
// recipients
Recipient recipient = new Recipient();
EmailAddress emailAddress = new EmailAddress();
emailAddress.address = "tom#mail.com";
recipient.emailAddress = emailAddress;
List<Recipient> recipients = List.of(recipient);
// body
ItemBody body = new ItemBody();
body.contentType = BodyType.HTML;
body.content = "<html><body>my image:<br><img src='cid:my_image_CID'></body></html>";
// inline image
Attachment attachment = new Attachment();
attachment.isInline = true;
attachment.contentType = ".png";
attachment.id = "my_image_CID";
//attachment.contentBytes - I DON'T SEE THIS FIELD...
// message
Message message = new Message();
message.subject = "my subject";
message.body = body;
message.toRecipients = recipients;
//message.attachments = ??? - how to create this object?
there are examples in the internet that I can set attachment.contentBytes but I don't see this attribute.
For the message I can set attachments object which is of type
AttachmentCollectionPage
but I don't know how can I create this object.
I'm using the following versions:
Microsoft Graph Java SDK » 5.42.0
Microsoft Graph Java Core SDK » 2.0.14
You need to use FileAttachment which extends Attachment and has property contentBytes.
I'm relying on Confluent's schema registry to store my protobuf schemas.
I posted the following schema in the schema registry:
{
"schema": "syntax = 'proto3'; package com.xyz.message; option java_package = 'com.xyz.message'; option java_outer_classname = 'ActionMessage'; message Action { reserved 7; string id = 1; string version = 2; string action_name = 3; string unique_event_i_d = 4; string rule_i_d = 5; map<string, Value> parameters = 6; string secondary_id = 8; message Value { string value = 1; repeated string values = 2; } }",
"schemaType" : "PROTOBUF"
}
I then query the schema registry REST API from my application to retrieved it
...
JsonElement schemaRegistryResponse = new JsonParser().parse(inputStreamReader);
String schema = schemaRegistryResponse.getAsJsonObject().get("schema").getAsString();
This indeed makes schema variable holding a string containing the protobuf schema. I now want to create a com.google.protobuf.Descriptors.Descriptor instance from it.
I proceed as follows:
byte[] encoded = Base64.getEncoder().encode(schema.getBytes());
FileDescriptorSet set = FileDescriptorSet.parseFrom(encoded);
FileDescriptor f = FileDescriptor.buildFrom(set.getFile(0), new FileDescriptor[] {});
Descriptors.Descriptor descriptor = f.getMessageTypes().get(0);
However, this throws a Protocol message end-group tag did not match expected tag exception when invoking parseFrom(encoded) method.
Any idea what I might be doing wrong?
You're trying to parse a base64-encoded representation of a .proto file. That's not at all what FileDescriptorSet.parseFrom expects. It expects a protobuf binary representation of a FileDescriptorSet message, which is typically created by protoc using the descriptor_set_out option.
I don't believe there's any way of getting the protobuf library to parse the text of a .proto file - you really need to run protoc.
I am using Rally API/Java. I need to attach a screenshot in Rally Testcase when i create it. I am doing it but i am getting an error in my attachment response.
The Response message is get and the error is:
{"CreateResult": {"_rallyAPIMajor": "2", "_rallyAPIMinor": "0", "Errors": ["We're sorry! An unexpected error has occurred.We have recorded this error and will begin to investigate it. In the meantime, if you would like to speak with our Support Team, please reference the information below:java.lang.NullPointerException02/25/2015 05:07:01 PM Asia/Karachi"], "Warnings": ["It is no longer necessary to append \".js\" to WSAPI resources."]}}
I get no message it my request and it creates the request succcessfully.
Need help with this!
My attachement code is as follows:
// File handle for image to attach
RandomAccessFile myImageFileHandle;
String imageFilePath = "c:/Screenshots/";
String imageFileName = "AWSCEUbuntuServerSmall.jpg";
String fullImageFile = imageFilePath + imageFileName;
String imageBase64String;
long attachmentSize;
// Open file
myImageFileHandle = new RandomAccessFile(fullImageFile, "r");
//Add Attachment
// Get and check length
long longLength = myImageFileHandle.length();
long maxLength = 5000000;
if (longLength >= maxLength) throw new IOException("File size >= 5 MB Upper limit for Rally.");
int fileLength = (int) longLength;
// Read file and return data
byte[] fileBytes = new byte[fileLength];
myImageFileHandle.readFully(fileBytes);
imageBase64String = Base64.encodeBase64String(fileBytes);
attachmentSize = fileLength;
// First create AttachmentContent from image string
JsonObject myAttachmentContent = new JsonObject();
myAttachmentContent.addProperty("Content", imageBase64String);
CreateRequest attachmentContentCreateRequest = new CreateRequest("AttachmentContent", myAttachmentContent);
CreateResponse attachmentContentResponse = restApi.create(attachmentContentCreateRequest);
String myAttachmentContentRef = Ref.getRelativeRef(attachmentContentResponse.getObject().get("_ref").getAsString());
System.out.println("Attachment Content created: " + myAttachmentContentRef);
// Now create the Attachment itself
JsonObject myAttachment = new JsonObject();
myAttachment.addProperty("Workspace", workspaceRef);
myAttachment.addProperty("TestCaseResult",ref);
myAttachment.addProperty("Content", myAttachmentContentRef);
myAttachment.addProperty("Name", "AttachmentFromREST.jpg");
myAttachment.addProperty("Description", "Attachment From REST");
myAttachment.addProperty("ContentType","image/jpg");
//myAttachment.addProperty("Size", attachmentSize);
myAttachment.addProperty("User", userRef);
CreateRequest attachmentCreateRequest = new CreateRequest("Attachment", myAttachment);
CreateResponse attachmentResponse = restApi.create(attachmentCreateRequest);
String myAttachmentRef = Ref.getRelativeRef(attachmentResponse.getObject().get("_ref").getAsString());
System.out.println("Attachment created: " + myAttachmentRef);
I submitted this defect yesterday: NullPointerException when posting attachments to a user's non-default workspace.
I'm looking to leverage RackSpace's CloudFiles platform for large object storage (word docs, images, etc). Following some of their guides, I found a useful code snippet, that looks like it should work, but doesn't in my case.
Iterable<Module> modules = ImmutableSet.<Module> of(
new Log4JLoggingModule());
Properties properties = new Properties();
properties.setProperty(LocationConstants.PROPERTY_ZONE, ZONE);
properties.setProperty(LocationConstants.PROPERTY_REGION, "ORD");
CloudFilesClient cloudFilesClient = ContextBuilder.newBuilder(PROVIDER)
.credentials(username, apiKey)
.overrides(properties)
.modules(modules)
.buildApi(CloudFilesClient.class);
The problem is that when this code executes, it tries to log me in the IAD (Virginia) instance of CloudFiles. My organization's goal is to use the ORD (Chicago) instance as primary to be colocated with our cloud and use DFW as a back up environment. The login response results in the IAD instance coming back first, so I'm assuming JClouds is using that. Browsing around, it looks like the ZONE/REGION attributes are ignored for CloudFiles. I was wondering if there is any way to override the code that comes back for authentication to loop through the returned providers and choose which one to login to.
Update:
The accepted answer is mostly good, with some more info available in this snippet:
RestContext<CommonSwiftClient, CommonSwiftAsyncClient> swift = cloudFilesClient.unwrap();
CommonSwiftClient client = swift.getApi();
SwiftObject object = client.newSwiftObject();
object.getInfo().setName(FILENAME + SUFFIX);
object.setPayload("This is my payload."); //input stream.
String id = client.putObject(CONTAINER, object);
System.out.println(id);
SwiftObject obj2 = client.getObject(CONTAINER,FILENAME + SUFFIX);
System.out.println(obj2.getPayload());
We are working on the next version of jclouds (1.7.1) that should include multi-region support for Rackspace Cloud Files and OpenStack Swift. In the meantime you might be able to use this code as a workaround.
private void uploadToRackspaceRegion() {
Iterable<Module> modules = ImmutableSet.<Module> of(new Log4JLoggingModule());
String provider = "swift-keystone"; //Region selection is limited to swift-keystone provider
String identity = "username";
String credential = "password";
String endpoint = "https://identity.api.rackspacecloud.com/v2.0/";
String region = "ORD";
Properties overrides = new Properties();
overrides.setProperty(LocationConstants.PROPERTY_REGION, region);
overrides.setProperty(Constants.PROPERTY_API_VERSION, "2");
BlobStoreContext context = ContextBuilder.newBuilder(provider)
.endpoint(endpoint)
.credentials(identity, credential)
.modules(modules)
.overrides(overrides)
.buildView(BlobStoreContext.class);
RestContext<CommonSwiftClient, CommonSwiftAsyncClient> swift = context.unwrap();
CommonSwiftClient client = swift.getApi();
SwiftObject uploadObject = client.newSwiftObject();
uploadObject.getInfo().setName("test.txt");
uploadObject.setPayload("This is my payload."); //input stream.
String eTag = client.putObject("jclouds", uploadObject);
System.out.println("eTag = " + eTag);
SwiftObject downloadObject = client.getObject("jclouds", "test.txt");
System.out.println("downloadObject = " + downloadObject.getPayload());
context.close();
}
Use swift as you would Cloud Files. Keep in mind that if you need to use Cloud Files CDN stuff, the above won't work for that. Also, know that this way of doing things will eventually be deprecated.
I want to import data from java web application to sugarCRM. I created client stub using AXIS and then I am trying to connect, it seems it is getting connected, since I can get server information. But after login, it gives me error while getting sessionID:
Error is: "faultString: org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it."
Here is my code:
private static final String ENDPOINT_URL = " http://localhost/sugarcrm/service/v3/soap.php";
java.net.URL url = null;
try {
url = new URL(ENDPOINT_URL);
} catch (MalformedURLException e1) {
System.out.println("URL endpoing creation failed. Message: "+e1.getMessage());
e1.printStackTrace();
}
> System.out.println("URL endpoint created successfully!");
Sugarsoap service = new SugarsoapLocator();
SugarsoapPortType port = service.getsugarsoapPort(url);
Get_server_info_result result = port.get_server_info();
System.out.println(result.getGmt_time());
System.out.println(result.getVersion());
//I am getting right answers
User_auth userAuth=new User_auth();
userAuth.setUser_name(USER_NAME);
MessageDigest md =MessageDigest.getInstance("MD5");
String password=convertToHex(md.digest(USER_PASSWORD.getBytes()));
userAuth.setPassword(password);
Name_value nameValueListLogin[] = null;
Entry_value loginResponse = null;
loginResponse=port.login (userAuth, "sugarcrm",nameValueListLogin);
String sessionID = loginResponse.getId(); // <--- Get error on this one
The nameValueListLogin could be be from a different document context (coming from a different source). See if this link helps.
You may need to get more debugging/logging information so we can see what nameValueListLogin consists of and where it is coming from.