Updating multiple fields for an Object - Dynamics CRM 2011 using java - java

Is there any way to update multiple fields for an object in Dynamics CRM 2011 using java. All I am able to do now is to update one field for an object (ContactSet,AccountSet etc..)
URL : https://xxxxxx.xxxx.xx/xxxxxx/XrmServices/2011/OrganizationData.svc/ContactSet(guid'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')
What I have done?
Map<String,Object> update = Maps.newHashMap();
update.put("FirstName","xxxxx");
update.put("LastName","xxxxx");
update.put("Telephone1","xxxxxxxx");
ObjectMapper mMapper = new ObjectMapper();
mEntity = mMapper.writeValueAsString(update);
String mUrl = this.url+"/"+getObject()+"(guid'"+id+"')";
HttpPut httpPut = new HttpPut(mUrl);
httpPut.setHeader("Content-Type", "application/json");
httpPut.setHeader("Accept","application/json");
httpPut.setEntity(new StringEntity(mEntity,"UTF-8"));
HttpResponse response = this.client.execute(httpPut);
The above code always gives a 500 internal server error.
What works?
Map<String,Object> update = Maps.newHashMap();
update.put("FirstName","xxxxx");
mEntity = mMapper.writeValueAsString(update);
String mUrl = this.url+"/"+getObject()+"(guid'"+id+"')"+"/FirstName";
HttpPut httpPut = new HttpPut(mUrl);
httpPut.setHeader("Content-Type", "application/json");
httpPut.setHeader("Accept","application/json");
httpPut.setEntity(new StringEntity(mEntity,"UTF-8"));
HttpResponse response = this.client.execute(httpPut);
I don't see a point in updating just a single field. Can someone please give pointers on how to update multiple fields?

I would recommend you to use javascript and Jquery or if you prefer java try to follow the microsoft code Javascript example.
It is possible to update multiple columns, just check your code syntax.

Related

use docusign api creates envelopes, error: Object moved

I consulted the API documentation and sent it successfully in api explorer-> Envelopes: create. I also got json & request path & token. I used httpclient post in java and received Object moved Object moved to here . Does anyone know what I missed?
`
DocsignDocument docsignDocument = new DocsignDocument();
docsignDocument.setDocumentBase64
docsignDocument.setDocumentId("1");
docsignDocument.setFileExtension("pdf");
docsignDocument.setName("Test.pdf");
list.add(docsignDocument);
Recipients recipients = new Recipients();
Signers signers = new Signers();
signers.setEmail("xxxx");
signers.setName("Qin");
signers.setRecipientId("1");
Signers signers1 = new Signers();
signers1.setEmail("xxx#qq.com");
signers1.setName("OYX");
signers1.setRecipientId("2");
List<Signers> signersList = new ArrayList<>();
signersList.add(signers);
signersList.add(signers1);
recipients.setSigners(signersList);
dataJson.put("documents",list);
dataJson.put("emailSubject","TEST");
dataJson.put("recipients",recipients);
dataJson.put("status","sent");
String data = dataJson.toJSONString();
String results2 = HttpDocusignUtils.httpPostJson("https://account-d.docusign.com/restapi/v2.1/accounts/xxx/envelopes",access_token,data)`
post request:
public static String httpPostJson(String uri, String token, String obj) {
String result = "";
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Content-Type", "application/json"); // 添加请求头
httpPost.addHeader("Authorization","Bearer "+token);
httpPost.addHeader("Accept-Encoding","gzip,deflate,sdch");
httpPost.setEntity(new StringEntity(obj));
System.out.println(httpPost);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
result = convertStreamToString(instreams);
System.out.println(result);
}
} catch (Exception e) {
e.getMessage();
}
return result;
}
https://account-d.docusign.com/restapi/v2.1/accounts/xxx/envelopes is not a valid DocuSign endpoint.
The Account Server (account-d.docusign.com) is used to get a token and make a UserInfo call to determine the correct base URL for a particular account.
Because you're in the Demo environment, your base url will begin with https://demo.docusign.net
Well, one issue is that the the Document model in Java is Document from
import com.docusign.esign.model.Document;
To debug, I suggest using the DocuSign API logging feature. Then update (edit) your question to include the JSON shown in the log.
Were you able to run the code examples for Java? See eg-03-java-auth-code-grant
Also, please tell us (by editing your question) what you are trying to do.
Creates envelopes - Use Base Url in Api Call
https://demo.docusign.net/restapi/v2.1/accounts/
Error Reason is use Wrong url - https://account-d.docusign.com/restapi/v2.1/accounts/
DocuSign Developers Documentation

Convert GetEntity().GetContent() from Java to C#

I need to convert the following code from Java to C# when I'm using restAPI in C#.
In java :
HttpGet statusGet = new HttpGet(fileUrl);
statusGet.setHeader("X-API-TOKEN", API_TOKEN);
HttpResponse response = httpClient.execute(statusGet);
// Extract exported file
ZipInputStream zs = new ZipInputStream(response.getEntity().getContent());
In C# this is what I have:
var client1 = new RestClient(fileUrl);
var request1 = new RestRequest(Method.GET);
request1.AddHeader("X-API-TOKEN", "API_TOKEN");
request1.AddHeader("content-type", "application/json");
request1.AddParameter("application/json", "{\n\t\"format\" : \"csv\",\n\t\"surveyId\" : \"_surveyId\"\n}", ParameterType.RequestBody);
IRestResponse responsedata = client1.Execute(request1);
var download=client1.DownloadData(request1);
MemoryStream stream = new MemoryStream(download);
ZipInputStream zs = new ZipInputStream(stream);
using (ZipFile zip1 = ZipFile.Read(zs))
I have no clue how to implement response.getEntity().getContent(). I believe it is getting the Stream(Containing a zip file?)
Updated: So I get the byte array from client1.DownloadData(request1), looks like it is not right to convert it to stream (has readtimeout exception). and it will not be able to read from zipfile.read
Thank you so much for your help
Are you getting any specific errors? It looks like you are implementing this using RestSharp. Have you followed their examples and read through their documentation?
I have not personally used this third-party solution, but immediately on their front page they have the following example that does exactly what you are trying to do:
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile(path);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
RestResponse<Person> response2 = client.Execute<Person>(request);
var name = response2.Data.Name;
// easy async support
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
// async with deserialization
var asyncHandle = client.ExecuteAsync<Person>(request, response => {
Console.WriteLine(response.Data.Name);
});
// abort the request on demand
asyncHandle.Abort();
It looks like you would want to access the IRestResponse.Content property, or to deserialize using the RestClient.Execute<T>(RestRequest request) function.

Curl equivalent POST in java for SOLR

I just started working with SOLR. I want to index some html pages and got this from the documentation:
curl "http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true" -F "myfile=#/home/binaryplease/workspace/SOLRTest/HTMLPages/hello2.html"
Which works as expected as the query returns the expecteed results.
How would I do this exact POST inside a java application?
I tried this as I dont know how to do it with the HttpClient but it's not working:
String command = "curl \"http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true\" -F \"myfile=#\"" +f.getAbsoluteFile() + "\"";
try {
proc = Runtime.getRuntime().exec(command );
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();
System.out.println("Inputstream " + getStringFromInputStream(in));
System.out.println("Errorstream " + getStringFromInputStream(err));
} catch (IOException e) {
e.printStackTrace();
}
What would be the correct way to index a html file in SOLR and do a query using java?
I would appreciate an example.
EDIT: I got this now which still isn't working:
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("myfile", "#/home/binaryplease/workspace/SOLRTest/HTMLPages/hello3.html"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
System.out.println("Content " + getStringFromInputStream(instream));
} finally {
instream.close();
}
}
}
What am i doing wrong?
You should be using the SolJ client for accessing Solr from Java, which will likely be much easier for you than going the the HTTP interface:
SolrJ is an API that makes it easy for Java applications to talk to
Solr. SolrJ hides a lot of the details of connecting to Solr and
allows your application to interact with Solr with simple high-level
methods.
The center of SolrJ is the org.apache.solr.client.solrj package, which
contains just five main classes. Begin by creating a SolrServer, which
represents the Solr instance you want to use. Then send SolrRequests
or SolrQuerys and get back SolrResponses.
SolrServer is abstract, so to connect to a remote Solr instance,
you'll actually create an instance of HttpSolrServer, which knows how
to use HTTP to talk to Solr.
https://cwiki.apache.org/confluence/display/solr/Using+SolrJ
The setup is pretty easy:
String urlString = "http://localhost:8983/solr";
SolrServer solr = new HttpSolrServer(urlString);
And so are queries:
SolrQuery parameters = new SolrQuery();
parameters.set("q", mQueryString);
QueryResponse response = solr.query(parameters);
SolrDocumentList list = response.getResults();
Same thing with indexing:
String urlString = "http://localhost:8983/solr";
SolrServer solr = new HttpSolrServer(urlString);
SolrInputDocument document = new SolrInputDocument();
document.addField("id", "552199");
document.addField("name", "Gouda cheese wheel");
document.addField("price", "49.99");
UpdateResponse response = solr.add(document);
// Remember to commit your changes!
solr.commit();

Posting JSON object to HTTP server

So I'm developing an Android app (Java) that posts a JSON object to a web server. I've achieved this, but I'm battling to get the string value to display properly.
Instead of the server receiving "6666666666666", it receives "Ljava.lang.String;#41108be0]". How on earth do I go about fixing this? Here's my code:
protected Boolean doInBackground(String... ID) {
HttpClient httpClient = new DefaultHttpClient();
Date dateTime = new Date();
string deviceID=null;
try {
HttpPost request = new HttpPost("http://192.168.1.89:80/");
JSONObject json = new JSONObject();
json.put("IDNo", ID.toString());
json.put("DTSent", dateTime);
json.put("DeviceID", deviceID);
StringEntity se = new StringEntity(json.toString(), "UTF-8");
se.setContentType("application/json; charset=UTF-8");
request.setEntity(se);
request.setHeader( "Content-Type", "application/json");
}
Please help.
ID is a String-Array not just a string. the ... makes it an array. so either use ID[0] or remove the ... from the function declaration
You are passing in an array of strings (see the three dots?). Try using ID[0] instead.
Here is a useful post:

Using the Jersey client to do a POST operation

In a Java method, I'd like to use a Jersey client object to do a POST operation on a RESTful web service (also written using Jersey) but am not sure how to use the client to send the values that will be used as FormParam's on the server. I'm able to send query params just fine.
Not done this yet myself, but a quick bit of Google-Fu reveals a tech tip on blogs.oracle.com with examples of exactly what you ask for.
Example taken from the blog post:
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, formData);
That any help?
Starting from Jersey 2.x, the MultivaluedMapImpl class is replaced by MultivaluedHashMap. You can use it to add form data and send it to the server:
WebTarget webTarget = client.target("http://www.example.com/some/resource");
MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
formData.add("key1", "value1");
formData.add("key2", "value2");
Response response = webTarget.request().post(Entity.form(formData));
Note that the form entity is sent in the format of "application/x-www-form-urlencoded".
It is now the first example in the Jersey Client documentation
Example 5.1. POST request with form parameters
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9998").path("resource");
Form form = new Form();
form.param("x", "foo");
form.param("y", "bar");
MyJAXBBean bean =
target.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
MyJAXBBean.class);
If you need to do a file upload, you'll need to use MediaType.MULTIPART_FORM_DATA_TYPE.
Looks like MultivaluedMap cannot be used with that so here's a solution with FormDataMultiPart.
InputStream stream = getClass().getClassLoader().getResourceAsStream(fileNameToUpload);
FormDataMultiPart part = new FormDataMultiPart();
part.field("String_key", "String_value");
part.field("fileToUpload", stream, MediaType.TEXT_PLAIN_TYPE);
String response = WebResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part);
Simplest:
Form form = new Form();
form.add("id", "1");
form.add("name", "supercobra");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, form);
Also you can try this:
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
webResource.path("yourJerseysPathPost").queryParams(formData).post();

Categories

Resources