Guest User

Untitled

a guest
Nov 30th, 2018
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.65 KB | None | 0 0
  1. public class JSON2Apex {
  2. public static void consumeObject(JSONParser parser) {
  3. Integer depth = 0;
  4. do {
  5. JSONToken curr = parser.getCurrentToken();
  6. if (curr == JSONToken.START_OBJECT ||
  7. curr == JSONToken.START_ARRAY) {
  8. depth++;
  9. } else if (curr == JSONToken.END_OBJECT ||
  10. curr == JSONToken.END_ARRAY) {
  11. depth--;
  12. }
  13. } while (depth > 0 && parser.nextToken() != null);
  14. }
  15.  
  16. public class Attributes {
  17. public String type {get;set;}
  18.  
  19. public Attributes(JSONParser parser) {
  20. while (parser.nextToken() != JSONToken.END_OBJECT) {
  21. if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
  22. String text = parser.getText();
  23. if (parser.nextToken() != JSONToken.VALUE_NULL) {
  24. if (text == 'type') {
  25. type = parser.getText();
  26. } else {
  27. System.debug(LoggingLevel.WARN, 'Attributes consuming unrecognized property: '+text);
  28. consumeObject(parser);
  29. }
  30. }
  31. }
  32. }
  33. }
  34. }
  35.  
  36. public class Entities {
  37. public Attributes attributes {get;set;}
  38. public String City {get;set;}
  39. public String Country {get;set;}
  40. public String DunsNumber {get;set;}
  41. public String Name {get;set;}
  42. public String Phone {get;set;}
  43. public String Street {get;set;}
  44. public String Zip {get;set;}
  45.  
  46. public Entities(JSONParser parser) {
  47. while (parser.nextToken() != JSONToken.END_OBJECT) {
  48. if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
  49. String text = parser.getText();
  50. if (parser.nextToken() != JSONToken.VALUE_NULL) {
  51. if (text == 'attributes') {
  52. attributes = new Attributes(parser);
  53. } else if (text == 'City') {
  54. City = parser.getText();
  55. } else if (text == 'Country') {
  56. Country = parser.getText();
  57. } else if (text == 'DunsNumber') {
  58. DunsNumber = parser.getText();
  59. } else if (text == 'Name') {
  60. Name = parser.getText();
  61. } else if (text == 'Phone') {
  62. Phone = parser.getText();
  63. } else if (text == 'Street') {
  64. Street = parser.getText();
  65. } else if (text == 'Zip') {
  66. Zip = parser.getText();
  67. } else {
  68. System.debug(LoggingLevel.WARN, 'Entities consuming unrecognized property: '+text);
  69. consumeObject(parser);
  70. }
  71. }
  72. }
  73. }
  74. }
  75. }
  76.  
  77. public List<Entities> entities {get;set;}
  78. public MatchOptions matchOptions {get;set;}
  79.  
  80. public JSON2Apex(JSONParser parser) {
  81. while (parser.nextToken() != JSONToken.END_OBJECT) {
  82. if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
  83. String text = parser.getText();
  84. if (parser.nextToken() != JSONToken.VALUE_NULL) {
  85. if (text == 'entities') {
  86. entities = new List<Entities>();
  87. while (parser.nextToken() != JSONToken.END_ARRAY) {
  88. entities.add(new Entities(parser));
  89. }
  90. } else if (text == 'matchOptions') {
  91. matchOptions = new MatchOptions(parser);
  92. } else {
  93. System.debug(LoggingLevel.WARN, 'Root consuming unrecognized property: '+text);
  94. consumeObject(parser);
  95. }
  96. }
  97. }
  98. }
  99. }
  100.  
  101. public class MatchOptions {
  102. public String fields {get;set;}
  103.  
  104. public MatchOptions(JSONParser parser) {
  105. while (parser.nextToken() != JSONToken.END_OBJECT) {
  106. if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
  107. String text = parser.getText();
  108. if (parser.nextToken() != JSONToken.VALUE_NULL) {
  109. if (text == 'fields') {
  110. fields = parser.getText();
  111. } else {
  112. System.debug(LoggingLevel.WARN, 'MatchOptions consuming unrecognized property: '+text);
  113. consumeObject(parser);
  114. }
  115. }
  116. }
  117. }
  118. }
  119. }
  120.  
  121. @future (callout=true) // indicates that this is an asynchronous call
  122. public static void postOrder(List<Id> leadIds) {
  123.  
  124. List<Lead> ld = [SELECT Id, Company, Country, phone, street, postalcode FROM Lead where Id IN :leadIds];
  125. for (Lead l : ld) {
  126. // Create a JSON generator object
  127. JSONGenerator gen = JSON.createGenerator(true);
  128. // open the JSON generator
  129. gen.writeStartObject();
  130.  
  131. gen.writeStringField('Name', l.Company);
  132.  
  133. gen.writeEndObject();
  134.  
  135. // close the JSON generator
  136.  
  137. // create a string from the JSON generator
  138. String jsonOrders = gen.getAsString();
  139. // debugging call, which you can check in debug logs
  140. System.debug('jsonOrders: ' + jsonOrders);
  141.  
  142.  
  143.  
  144. // create an HTTPrequest object
  145. HttpRequest req = new HttpRequest();
  146.  
  147. req.setMethod('POST');
  148.  
  149. req.setEndpoint('https://cs15.salesforce.com/services/data/v32.0/match/DunsRightMatchEngine/DatacloudCompany/DunsRightMatchRule');
  150. req.setHeader('Content-Type', 'application/json');
  151. req.setBody(jsonOrders);
  152. // create a new HTTP object
  153. Http http = new Http();
  154. // create a new HTTP response for receiving the remote response
  155. // then use it to send the configured HTTPrequest
  156. HTTPResponse res = http.send(req);
  157.  
  158.  
  159.  
  160.  
  161. {
  162. // Retrieve all of the Lead records
  163. // originally passed into the method call to prep for update.
  164. List<Lead> leads =
  165. [SELECT Id FROM Lead WHERE Id IN :ld];
  166. // Create a list of entities by deserializing the
  167. // JSON data returned by the fulfillment service.
  168. List<Entities> ddcdata =
  169. (List<Entities>)JSON.deserialize(res.getBody(),
  170. List<Entities>.class);
  171. // Create a map of Lead IDs from the retrieved
  172. // invoices list.
  173. Map<Id, Lead> leadMap =
  174. new Map<Id, Lead>(leads);
  175.  
  176. for ( Entities ddc : ddcdata ) {
  177. Lead lead = leadMap.get(ddc.Id);
  178. lead.Company = String.valueOf(ddc.Name);
  179. }
  180. // Update all leads in the database with a bulk update
  181. update leads;
  182. }
  183.  
  184. }
  185. }
  186.  
  187. }
  188.  
  189. trigger LeadDDCAccountMatch on Lead (after insert) {
  190.  
  191. List<Id> leadIds = new List<Id>();
  192.  
  193. for (Lead lead: Trigger.new) {
  194. if (lead.status == 'Cold'){
  195. leadIds.add(lead.Id);
  196. }
  197. }
  198.  
  199. if (leadIds.size() > 0) {
  200. Lead_fromJSON.postOrder(leadIds);
  201. }
  202. }
  203.  
  204. {
  205. "entities": [
  206. {
  207. "attributes": {
  208. "type": "DatacloudCompany"
  209. },
  210. "City": //city from lead
  211. "Country": //country from lead
  212. "DunsNumber": //companydunsnumber from lead
  213. "Name": //company name from lead
  214. "Phone": //phone from lead
  215. "Street": //street from lead
  216. "Zip": //postalcode from lead
  217. }
  218. ],
  219. "matchOptions": {"fields": "City, CompanyId, Country, Description, DunsNumber, Name, Website, YearStarted, Zip"
  220. }
  221. }
  222.  
  223. trigger LeadDDCAccountMatch on Lead (after insert) {
  224.  
  225. List<String> leadIds = new List<String>();
  226.  
  227. for (Lead lead: Trigger.new) {
  228. if (lead.status == 'Cold'){
  229. leadIds.add(lead.company);
  230. }
  231. }
  232.  
  233. if (leadIds.size() > 0) {
  234. Lead_fromJSON.postOrder(leadIds);
  235. }
  236. }
  237.  
  238. public class Lead_fromJSON{
  239.  
  240. public class Entities {
  241. public String Id {get; set;}
  242. public String Name {get; set;}
  243. public String phone {get; set;}
  244. public String city {get; set;}
  245. }
  246.  
  247. @future (callout=true) // indicates that this is an asynchronous call
  248. public static void postOrder(List<String> leadIds) {
  249.  
  250. List<Lead> ld = [SELECT Id, Company, Country, phone, Email_Domain__c FROM Lead where Company IN :leadIds];
  251. for (Lead l : ld) {
  252. // Create a JSON generator object
  253. JSONGenerator gen = JSON.createGenerator(true);
  254. // open the JSON generator
  255. gen.writeStartObject();
  256. gen.writeStringField('Type', 'DatacloudCompany');
  257. gen.writeStringField('Name', l.Company);
  258.  
  259. gen.writeStringField('Country', l.Country);
  260. gen.writeStringField('Website', l.Email_Domain__c);
  261. gen.writeEndObject();
  262.  
  263. // close the JSON generator
  264.  
  265. // create a string from the JSON generator
  266. String jsonOrders = gen.getAsString();
  267. // debugging call, which you can check in debug logs
  268. System.debug('jsonOrders: ' + jsonOrders);
  269.  
  270.  
  271.  
  272. // create an HTTPrequest object
  273. HttpRequest req = new HttpRequest();
  274. // set up the HTTP request with a method, endpoint, header, and body
  275. req.setMethod('POST');
  276. req.setEndpoint('https://cs15.salesforce.com//services/data/v32.0/match/DatacloudMatchEngine/DatacloudCompany/');
  277. req.setHeader('Content-Type', 'application/json');
  278. req.setBody(jsonOrders);
  279. // create a new HTTP object
  280. Http http = new Http();
  281. // create a new HTTP response for receiving the remote response
  282. // then use it to send the configured HTTPrequest
  283. HTTPResponse res = http.send(req);
  284.  
  285.  
  286.  
  287.  
  288. {
  289. // Retrieve all of the Lead records
  290. // originally passed into the method call to prep for update.
  291. List<Lead> leads =
  292. [SELECT Id FROM Lead WHERE Id IN :ld];
  293. // Create a list of entities by deserializing the
  294. // JSON data returned by the fulfillment service.
  295. List<Entities> ddcdata =
  296. (List<Entities>)JSON.deserialize(res.getBody(),
  297. List<Entities>.class);
  298. System.debug('ddcdata: ' + ddcdata);
  299. // Create a map of Lead IDs from the retrieved
  300. // invoices list.
  301. Map<String, Lead> leadMap =
  302. new Map<String, Lead>(leads);
  303.  
  304. for ( Entities ddc : ddcdata ) {
  305. Lead lead = leadMap.get(ddc.Name);
  306. if (ddc.Name != null)
  307. lead.Company = String.valueOf(ddc.Name);
  308. lead.city = String.valueOf(ddc.Name);
  309. }
  310. // Update all leads in the database with a bulk update
  311. update leads;
  312. }
  313.  
  314. }
  315. }
  316. }
  317.  
  318. public String accessToken;
  319. public String instanceUrl;
  320. public Wrapper wrapObj{get;set;}
  321. // Wrapper Class to Store the value from the Json.
  322. public class Wrapper{
  323. String id;
  324. String instance_url;
  325. String access_token;
  326. String issued_at;
  327. String signature;
  328. }
  329. public void postOrder(List<Id> leadIds) {
  330.  
  331. fromJSON frmJson = new fromJSON();
  332. fromJSON.cls_matchOptions mcthOptions = new fromJSON.cls_matchOptions();
  333. fromJSON.cls_entities listAddr = new fromJSON.cls_entities();
  334. fromJSON.cls_attributes attributs = new fromJSON.cls_attributes();
  335. fromJSON.cls_matchOptions matchop= new fromJSON.cls_matchOptions();
  336. List<fromJSON.cls_entities> LstEntities = new List<fromJSON.cls_entities>();
  337.  
  338. // Logic to get access token
  339. String clientId = '3MVG9Oe7T3Ol0ea5zCVJ5_Hf6MeuJM0jpI9UGbszmEX4jIon6mXlnJFvwqOhEIrg0pqBS0BCcuAoQAhm6nxJN';
  340. String clientSecret = '713695559755260947';
  341.  
  342. //We can also store our username password in custom setting.
  343. String username='************';//salesforce username
  344. String password='**passwordwithsecurityToken';//salesforce password
  345. // Generating the Access Token
  346. HttpRequest req = new HttpRequest();
  347. req.setMethod('POST');
  348. req.setEndpoint('yoursalesforceintance/services/oauth2/token');// this is the OAuth endpoint where this request will be hit
  349. req.setBody('grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password);
  350.  
  351. Http http = new Http();
  352. HTTPResponse res = http.send(req);
  353. String str = res.getBody();
  354. wrapObj = (Wrapper)Json.deserialize(str,Wrapper.class);
  355. accessToken = wrapObj.access_token;
  356. instanceUrl = wrapObj.instance_url;
  357. system.debug('######'+accessToken );
  358.  
  359. // Logic ends here
  360. // Request Generation
  361. List<Lead> ld = [SELECT Id, Company,City, Country, phone, State,street, postalcode FROM Lead where Id IN :leadIds];
  362. for (Lead l : ld) {
  363. attributs.type='DatacloudCompany';
  364. listAddr.attributes=attributs;
  365. listAddr.City=l.City;
  366. listAddr.Country=l.Country;
  367. listAddr.Name=l.Company;
  368. listAddr.Phone=l.phone;
  369. listAddr.State=l.state;
  370. listAddr.Street=l.street;
  371. listAddr.Zip=l.PostalCode;
  372. system.debug(''+listAddr);
  373. LstEntities.add(listAddr);
  374. mcthOptions.fields='AnnualRevenue, City, CompanyId, Country, Description, DunsNumber, Fax, Industry, IsInactive, NaicsCode, NaicsDesc, Name, NumberOfEmployees, Ownership, Phone, Sic, SicDesc, Site, State, Street, TickerSymbol, TradeStyle, Website, YearStarted, Zip';
  375. frmJson.matchOptions=mcthOptions;
  376. frmJson.entities=LstEntities;
  377. // Request Call to Data.com API
  378. HttpRequest datareq = new HttpRequest();
  379. datareq .setMethod('POST');
  380. datareq .setEndpoint('https://nacrm--nacedev.cs12.my.salesforce.com/services/data/v43.0/match/DunsRightMatchEngine/DatacloudCompany/DunsRightMatchRule');
  381. datareq .setHeader('Authorization', 'OAuth '+wrapObj.access_token);
  382. datareq .setHeader('Content-Type', 'application/json');
  383. datareq .setBody(Json.serialize(frmJson));
  384. //req1.setBody(json);
  385. Http httpsend = new Http();
  386. HTTPResponse responsefromRequest = httpsend .send(datareq );
  387. system.debug('###REQ####'+datareq+ '###Response####'+responsefromRequest);
  388. String jsonResponse=responsefromRequest.getBody();
  389. system.debug('$$$$$$$$$$$$$'+jsonResponse);
  390. }
  391.  
  392. }
Add Comment
Please, Sign In to add comment