Task assign to multiple leads in salesforce using rest api - rest

I am new in Salesforce.Below code working fine,Its created task "Call LeadTest" sucessfully and assignd to only one lead/contact (WhoId). But i wanted to assign same task to multiple leads/contacts.
DefaultHttpClient HttpClient = new DefaultHttpClient();
HttpParams params = HttpClient.getParams();
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("MM/dd/YYYY hh:mm a");
Instant instant = Instant.now();
String dueDate=instant.toString();
JSONObject json = new JSONObject();
json.put("Subject", "Call LeadTest");
json.put("Status", "Not Started");
json.put("Priority", "Low");
json.put("OwnerId", "xxxxxxxxx");
json.put("WhoId", "xxxxxxxxx");
json.put("ActivityDate", dueDate);
json.put("Description", "this is test Task");
String baseUrl = instanceUrl + "/services/data/v49.0/sobjects/Task/";
oAuthHeader = new BasicHeader("Authorization", "OAuth " + accesstoken);
HttpPost schemaHttpGet = new HttpPost(baseUrl);
schemaHttpGet.addHeader(oAuthHeader);
schemaHttpGet.addHeader(printHeader);
StringEntity params2 = new StringEntity(json.toString());
schemaHttpGet.addHeader("content-type", "application/json");
schemaHttpGet.setEntity(params2);
HttpResponse response = HttpClient.execute(schemaHttpGet);
int iStatusCode = response.getStatusLine().getStatusCode();
So please help me to find out, how to assignd created task to multiple leads/contacts.
Thank you for your answer in advance.

You must enable the Shared Activities feature. Once enabled, you will be able to assign either up to 50 Contacts or exactly one Lead to a Task.
With shared activities, users can relate up to 50 contacts (but only 1 lead) to an event or a task.
It is not possible to associate multiple Leads to a Task, or a Lead and a Contact.
You can use the TaskWhoIds field or directly manipulate the TaskRelation junction records between Task and Contact or Lead to control these assignments.

Related

Automate user creation and deletion through external API requests

I have 0 experience in coding in APEX so I would greatly appreciate your help and support with this question!
I would like to figure out a way to automate the deletion of an Aircall User if an SF user is deleted. Let us assume that every SF user has an Aircall ID that is present in their User profiles, stored in a field called 'Aircall ID'. This is what I will need to form the delete request.
I want that when a user is deleted on Salesforce, it triggers a delete request to Aircall sending the value that was previously stored in the Aircall ID field to the specific endpoint in question.
I need help figuring out how to write an APEX trigger that sends the Aircall ID to the class (to be triggered after the user is deleted) and finally how to automatically trigger the execution of this class after the ID has been received in order to complete the User deletion on Aircall's platform.
public class deleteAirCallUser {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setMethod('DELETE');
string encodedCredentials = 'apikey';
String authorizationHeader = 'Basic ' + encodedCredentials;
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
request.setHeader('Authorization', authorizationHeader);
string AircallUserId = //should be the Aircall userID from the deleted profile
request.setBody(AircallUserId);
request.setEndpoint('https://api.aircall.io/v1/users/'+ Aircall userID);
HttpResponse response = http.send(request);
if (response.getStatusCode() == 200) {
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
System.debug(results);}
else{
Map<String, Object> results_2 = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
System.debug(results_2);
}
}
Thank you for your help!
https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_user.htm
"You can’t delete a user in the user interface or the API. You can deactivate a user in the user interface; and you can deactivate or disable a Customer Portal or partner portal user in the user interface or the API. Because users can never be deleted, we recommend that you exercise caution when creating them."
For deactivations you'll need something like this. (It's not written to best practices, ideally the trigger would be "thin" and actual processing offloaded to helper class. Also it assumes you mass update max 10 users at a time because that's the limit of callouts.
trigger UserTrigger on User (after update){
Set<String> toSend = new Set<String>();
for(User u : trigger.new){
User oldUser = trigger.oldMap.get(u.Id);
// have we deactivated them?
if(!u.isActive && oldUser.isActive && String.isNotBlank(u.AirCallId__c)){
toSend.add(u.AirCallId__c);
}
}
if(!toSend.isEmpty()){
sendAirCallDeletes(toSend);
}
// This should be in a helper class, it looks bizarre to have functions defined in trigger's body
#future
static void sendAirCallDeletes(Set<String> toSend){
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setMethod('DELETE');
String encodedCredentials = 'apikey';
String authorizationHeader = 'Basic ' + encodedCredentials;
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
request.setHeader('Authorization', authorizationHeader);
for(String airCallId : toSend){
request.setBody(airCallId);
request.setEndpoint('https://api.aircall.io/v1/users/'+ airCallId);
try{
HttpResponse response = http.send(request);
System.debug(response.getStatusCode());
System.debug(response.getBody());
System.debug((Map<String, Object>) JSON.deserializeUntyped(response.getBody());
} catch(Exception e){
System.debug(e);
}
}
}
}
You might want to read up about "named credentials" (don't store the api keys etc in code), why we need "#future" trick when we want to make callout from a trigger, how to check for limit of calls you can make in single transaction... But should be a start?

Can any body share me java code to make a one Rest api call to IBM BPM Cloud

Can any body share a java client code which makes a Rest calls to IBM Cloud BPM. Basically I want to know how to authenticate IBM Cloud BPM.
I tried the following code but it is not working
String user_info_url="https://ustrial01.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/user/current?includeInternalMemberships=true&parts=all";
logger.info("user_info_url :" + user_info_url);
HttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(user_info_url);
String authData = "rajesh.kohir123#gmail.com" + ":" + "password";
String encoded = new sun.misc.BASE64Encoder().encode(authData .getBytes());
get.setHeader("Content-Type", "application/json");
get.setHeader("Accept", "application/json");
get.setHeader("Authorization", "Basic " + encoded);
HttpResponse cgResponse = client.execute(get);
if(cgResponse.getStatusLine().getStatusCode() != 200) {
logger.info("IBM Rest call failed");
}
if(cgResponse.getStatusLine().getStatusCode() == 200) {
logger.info("IBM Rest call Succeded");
String content = EntityUtils.toString(cgResponse.getEntity());
logger.info(content);
}
Any help is greatly appreciated
I ran your code and just made the changes in URL. It worked. I hope this helps you.
Following is the URL I used to execute an exposed service :
https://vhost031.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/service/OMS#Greetings
I used the following code to add the parameters :
String parameters = "{'name':'pramod'}";
URIBuilder builder = new URIBuilder("https://vhost031.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/service/OMS#Greetings");
List nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("action", "start"));
nameValuePairs.add(new BasicNameValuePair("params", parameters));
nameValuePairs.add(new BasicNameValuePair("createTask", "false"));
nameValuePairs.add(new BasicNameValuePair("parts", "all"));
builder.setParameters(nameValuePairs);
HttpGet get = new HttpGet(builder.build());
Download the download.zip form the post.
Look at the SampleBPDProcessTests.java - Line no 103
JSONObject results = bpmClient.runBPD(BPD_ID, PROCESS_APP_ID, bpdArgs);
The actual Java Code for Rest call is available as part of "bpm-rest-client.jar"
Try this concept.
Sample Java code to start a process:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://ustrial03.bpm.ibmcloud.com:443/bpm/dev/rest/bpm/wle/v1/process?
processAppId=3u092jr02j-djaodaj.u092302c166c1&bpdId=25.jklaklaa-539a-4150-
b63e-9ef94e96e521&action=start")
.put(null)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("Accept", "application/json")
.addHeader("Connection", "keep-alive")
.addHeader("Authorization", "Basic YXJrYX24223232hQGRlbG9pdHRlLmNvbTpkZWZjb240QA==")
.addHeader("Cache-Control", "no-cache")
.addHeader("Postman-Token", "f46c1525-7a75-954c-9265-bb2b21a57f16")
.build();
Response response = client.newCall(request).execute();
A full explanation of REST integration with BPM Cloud can be found in my answer at:
How to run IBM BPM Rest api call from Post man client

Error 400 on SOQL Query via REST

I'm trying to do a "select * from accounts" query on salesforce via their rest API and I'm getting an ERROR 400 Bad Request. All of my rest calls seem to be working but I can't introduce a query. Can someone take a look at the code and let me know what they think?
The value that getSOQLQuery() is returning is:
url/services/data/v28.0/query?q=select+*+from+Account
HttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(getSOQLQuery());
System.out.println(getSOQLQuery());
get.setHeader("Authorization", "OAuth " + auth.getAuthToken());
get.setHeader("content-type", "application/json");
HttpResponse result = httpclient.execute(get);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
Object obj = resultObject.toString();
if(result.getStatusLine().getStatusCode() == 200) {
resultSet = obj;
System.out.println("DONE");
}else{
System.out.println("Error!");
System.out.println(result);
}
Thanks!
SOQL doesn't support select * you have to explicitly name the fields you want to query, e.g. select id,name from account. You can use the describe resource to find all the field names if you want to dynamically build the select list.
Also if you examine the response body of the 400 response, there'll be a detailed error message.

I'm using the twitter4j library to access the public twitter stream

I'm using the twitter4j library to access the public twitter stream. I'm trying to make a project involving geotagged tweets, and I need to collect a large number of them for testing.
Right now I am getting the unfiltered stream from twitter and only saving tweets with geotags. This is slow though because the VAST majority of tweets don't have geo tags. I want the twitter stream to send me only tweets with geotags.
I have tried using the method mentioned in [this question][1], where you filter with a bounding box of size 360* by 180* but that's not working for me. I'm not getting any errors when using that filter, but I'm still getting 99% of tweets with no geotags. Here is how I'm doing it:
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
HttpGet httpget = new HttpGet("https://developers.facebook.com/docs/reference/api/examples/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
entity.consumeContent();
}
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
HttpPost httpost = new HttpPost(
"https://www.facebook.com/login.php?login_attempt=1");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("email", "xxxxxxxxxxxxxx"));
nvps.add(new BasicNameValuePair("pass", "ssssssss"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
if (entity != null) {
entity.consumeContent();
}
CookieStore cookiestrore = httpclient.getCookieStore();
//cookies = httpclient.getCookieStore().getCookies();
//httpclient.getConnectionManager().shutdown();
return cookiestrore;
Any this is not getting any error but i am not getting any results.
When you track keyword it is separate job from tracking locations. These are logical ORs

Cannot access google trends using HttpClient

I'm kind of newbie to this...Basicly I need to run a script to download .csv files from google trends. I wrote the following code according to this reference , the code is like:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>;
nameValuePairs.add(new BasicNameValuePair("Email", "myEmail"));
nameValuePairs
.add(new BasicNameValuePair("Passwd", "myPasswd"));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source",
"Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "xapi"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
if (line.startsWith("SID=")) {
String key = line.substring(4);
// Do something with the key
} catch (Exception e) {
}
I got the information about SID, LSID, Auth, but don't know how to use these information. I guess I should add these cookies in my following request, but don't know exactly how. I wrote another piece of code to connect to the certain URL, but I keep getting this message "You must be signed in to export data from Google Trends." The code is here if it helps:
URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(true);
conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.addRequestProperty("Authorization", "SID"+key);
conn.addRequestProperty("Email", "myEmail");
conn.addRequestProperty("Passwd", "myPasswd");
conn.setReadTimeout(5000);
conn.connect();
I searched around and found few useful information, anyone could help?
Does it have to be in Java? In python, it's as simple as this:
from pyGTrends import pyGTrends
connector = pyGTrends('google username','google password')
connector.download_report(('keyword1', 'keyword2'))
print connector.csv()
You'll need the google trends api library.
If it has to be Java, you may want to look at the HttpClient examples from Apache. "Form based logon" and "client authentication" may both be relevant.
I have just coded this:
https://github.com/elibus/j-google-trends-api
It is an unofficial Java implementation of Google Trends API. You could use it to easily access Google Trends or you might want to have a look at the code to see it works.
Anyway the authentication flow works as follows (all the steps are required):
Fetch https://accounts.google.com/ServiceLoginAuth and parse the GALX id
Post username/password + GALX
Get http://www.google.com
Then you can access Google Trend with relaxed QoS policies for authenticated users.