PageRenderTime 55ms CodeModel.GetById 8ms RepoModel.GetById 1ms app.codeStats 0ms

/core/infinit.e.data_model/src/com/ikanow/infinit/e/data_model/driver/InfiniteDriver.java

https://github.com/IKANOW/Infinit.e
Java | 2003 lines | 1533 code | 303 blank | 167 comment | 203 complexity | 5011e75b75ce4294677c3e512dde81d2 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. /*******************************************************************************
  2. * Copyright 2012 The Infinit.e Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. ******************************************************************************/
  16. package com.ikanow.infinit.e.data_model.driver;
  17. import java.io.BufferedReader;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.InputStreamReader;
  21. import java.io.OutputStream;
  22. import java.io.UnsupportedEncodingException;
  23. import java.net.HttpURLConnection;
  24. import java.net.MalformedURLException;
  25. import java.net.URL;
  26. import java.net.URLConnection;
  27. import java.net.URLEncoder;
  28. import java.security.MessageDigest;
  29. import java.security.NoSuchAlgorithmException;
  30. import java.text.SimpleDateFormat;
  31. import java.util.ArrayList;
  32. import java.util.Collection;
  33. import java.util.Date;
  34. import java.util.HashMap;
  35. import java.util.HashSet;
  36. import java.util.LinkedList;
  37. import java.util.List;
  38. import java.util.Map;
  39. import java.util.Set;
  40. import org.apache.commons.codec.binary.Base64;
  41. import org.apache.commons.io.IOUtils;
  42. import org.bson.types.ObjectId;
  43. import com.google.common.collect.HashMultimap;
  44. import com.google.gson.Gson;
  45. import com.google.gson.JsonElement;
  46. import com.google.gson.JsonPrimitive;
  47. import com.ikanow.infinit.e.data_model.InfiniteEnums.HarvestEnum;
  48. import com.ikanow.infinit.e.data_model.api.ApiManager;
  49. import com.ikanow.infinit.e.data_model.api.ResponsePojo;
  50. import com.ikanow.infinit.e.data_model.api.ResponsePojo.ResponseObject;
  51. import com.ikanow.infinit.e.data_model.api.authentication.WordPressAuthPojo;
  52. import com.ikanow.infinit.e.data_model.api.authentication.WordPressSetupPojo;
  53. import com.ikanow.infinit.e.data_model.api.authentication.WordPressUserPojo;
  54. import com.ikanow.infinit.e.data_model.api.config.SourcePojoApiMap;
  55. import com.ikanow.infinit.e.data_model.api.custom.mapreduce.CustomMapReduceResultPojo;
  56. import com.ikanow.infinit.e.data_model.api.custom.mapreduce.CustomMapReduceResultPojoApiMap;
  57. import com.ikanow.infinit.e.data_model.api.knowledge.AdvancedQueryPojo;
  58. import com.ikanow.infinit.e.data_model.api.knowledge.DimensionListPojo;
  59. import com.ikanow.infinit.e.data_model.api.knowledge.DocumentPojoApiMap;
  60. import com.ikanow.infinit.e.data_model.api.knowledge.SearchSuggestPojo;
  61. import com.ikanow.infinit.e.data_model.api.social.community.CommunityPojoApiMap;
  62. import com.ikanow.infinit.e.data_model.api.social.person.PersonPojoApiMap;
  63. import com.ikanow.infinit.e.data_model.api.social.sharing.SharePojoApiMap;
  64. import com.ikanow.infinit.e.data_model.store.config.source.SourcePojo;
  65. import com.ikanow.infinit.e.data_model.store.custom.mapreduce.CustomMapReduceJobPojo;
  66. import com.ikanow.infinit.e.data_model.store.document.DocumentPojo;
  67. import com.ikanow.infinit.e.data_model.store.feature.entity.EntityFeaturePojo;
  68. import com.ikanow.infinit.e.data_model.store.social.community.CommunityPojo;
  69. import com.ikanow.infinit.e.data_model.store.social.person.PersonPojo;
  70. import com.ikanow.infinit.e.data_model.store.social.sharing.SharePojo;
  71. import com.ikanow.infinit.e.data_model.store.social.sharing.SharePojo.ShareCommunityPojo;
  72. import com.ikanow.infinit.e.data_model.utils.TrustManagerManipulator;
  73. import com.mongodb.BasicDBObject;
  74. import com.mongodb.DBObject;
  75. import com.mongodb.util.JSON;
  76. public class InfiniteDriver
  77. {
  78. private static String DEFAULT_API_ROOT = null;
  79. private static String DEFAULT_USER = null;
  80. private static String DEFAULT_PASSWORD = null;
  81. private String apiRoot;
  82. private String user;
  83. private String password;
  84. private String apiKey = null;
  85. private String cookie = null;
  86. public InfiniteDriver()
  87. {
  88. apiRoot = DEFAULT_API_ROOT;
  89. user = DEFAULT_USER;
  90. password = DEFAULT_PASSWORD;
  91. }
  92. public InfiniteDriver(String apiRootUrl)
  93. {
  94. if (apiRootUrl == null)
  95. apiRoot = DEFAULT_API_ROOT;
  96. else
  97. apiRoot = apiRootUrl;
  98. user = DEFAULT_USER;
  99. password = DEFAULT_PASSWORD;
  100. }
  101. public InfiniteDriver(String apiRootUrl, String apiKey)
  102. {
  103. if (apiRootUrl == null)
  104. apiRoot = DEFAULT_API_ROOT;
  105. else
  106. apiRoot = apiRootUrl;
  107. this.apiKey = "infinitecookie=api:" + apiKey + ";"; // (use it like a cookie to avoid localhost dev issues)
  108. // (unused)
  109. user = DEFAULT_USER;
  110. password = DEFAULT_PASSWORD;
  111. }
  112. public InfiniteDriver(String apiRootUrl, String username, String unencryptedPassword)
  113. {
  114. if (apiRootUrl == null)
  115. apiRoot = DEFAULT_API_ROOT;
  116. else
  117. apiRoot = apiRootUrl;
  118. if (username == null || unencryptedPassword == null)
  119. {
  120. user = DEFAULT_USER;
  121. password = DEFAULT_PASSWORD;
  122. }
  123. else
  124. {
  125. user = username;
  126. password = unencryptedPassword;
  127. }
  128. }
  129. static public void setDefaultUser(String username)
  130. {
  131. DEFAULT_USER = username;
  132. }
  133. static public void setDefaultPassword(String unencryptedPassword)
  134. {
  135. DEFAULT_PASSWORD = unencryptedPassword;
  136. }
  137. static public void setDefaultApiRoot(String rootUrl)
  138. {
  139. DEFAULT_API_ROOT = rootUrl;
  140. }
  141. //////////////////////////////////////////////////////////////////////////////////////////////
  142. // AUTHENTICATION
  143. // If you already have a valid cookie, then use that:
  144. public void useExistingCookie(String existingCookie) {
  145. cookie = "infinitecookie=" + existingCookie + "; Path=/; HttpOnly";
  146. }
  147. /**
  148. * Returns the currently set cookie, can be used to
  149. * get the cookie after you login.
  150. *
  151. * @return
  152. */
  153. public String getCookie()
  154. {
  155. return cookie;
  156. }
  157. /**
  158. * Logs the user in specified by setUser() using the password
  159. * specified by setPassword().
  160. * @return true if the user was logged in successfully.
  161. */
  162. public Boolean login()
  163. {
  164. return login(new ResponseObject());
  165. }
  166. public Boolean adminLogin()
  167. {
  168. return adminLogin(new ResponseObject());
  169. }
  170. /**
  171. * Logs the user in specified by setUser() using the password
  172. * specified by setPassword().
  173. * @param responseObject this object will be said from the response of the API call
  174. * @return true if the user was logged in successfully.
  175. */
  176. public Boolean login(ResponseObject responseObject)
  177. {
  178. return login (user, password, responseObject);
  179. }
  180. public Boolean adminLogin(ResponseObject responseObject)
  181. {
  182. return adminLogin (user, password, responseObject);
  183. }
  184. /**
  185. * Logs the user in with the specified username and password.
  186. * This overrides the setUser and setPassword commands
  187. * @param username The username to log in
  188. * @param password the unencrypted password for the username
  189. * @param responseObject this object will be said from the response of the API call
  190. * @return true if the user was logged in successfully.
  191. */
  192. public Boolean login(String username, String password, ResponseObject responseObject)
  193. {
  194. try
  195. {
  196. return doLogin(username, encryptWithoutEncode(password), responseObject);
  197. }
  198. catch (Exception ex)
  199. {
  200. ex.printStackTrace();
  201. }
  202. return null;
  203. }
  204. public Boolean login_encrypted(String username, String encrypted_password, ResponseObject responseObject)
  205. {
  206. return doLogin(username, encrypted_password, responseObject);
  207. }
  208. private Boolean doLogin(String username, String password, ResponseObject responseObject)
  209. {
  210. if (null != apiKey) { // Have an API key, don't need to login....
  211. return true;
  212. }
  213. cookie = null;
  214. try
  215. {
  216. String address = apiRoot + "auth/login/" + username + "/" + URLEncoder.encode(password, "UTF-8");
  217. String loginResult;
  218. loginResult = sendRequest(address, null);
  219. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(loginResult, ResponsePojo.class);
  220. ResponseObject internal_ro = internal_responsePojo.getResponse();
  221. responseObject = shallowCopy(responseObject, internal_ro);
  222. return responseObject.isSuccess();
  223. }
  224. catch (Exception e)
  225. {
  226. e.printStackTrace();
  227. }
  228. return null;
  229. }
  230. public Boolean adminLogin(String username, String password, ResponseObject responseObject)
  231. {
  232. // Allow this even if have an API key because it's currently the only way of knowing if you're an admin
  233. cookie = null;
  234. try {
  235. String address = apiRoot + "auth/login/admin/" + username + "/" + encryptEncodePassword(password);
  236. String loginResult;
  237. loginResult = sendRequest(address, null);
  238. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(loginResult, ResponsePojo.class);
  239. ResponseObject internal_ro = internal_responsePojo.getResponse();
  240. responseObject = shallowCopy(responseObject, internal_ro);
  241. return responseObject.isSuccess();
  242. }
  243. catch (Exception e)
  244. {
  245. e.printStackTrace();
  246. }
  247. return null;
  248. }
  249. /**
  250. * Logs the current logged in user out.
  251. * @return true if logout was successful.
  252. */
  253. public Boolean logout()
  254. {
  255. if (null == cookie) { // not logged in, eg have an API key
  256. return true;
  257. }
  258. try {
  259. String address = apiRoot + "auth/logout/";
  260. String logoutResult;
  261. logoutResult = sendRequest(address, null);
  262. ResponsePojo response = ResponsePojo.fromApi(logoutResult, ResponsePojo.class);
  263. //cookie set to null so that new cookie will be grabbed on next login
  264. cookie = null;
  265. return response.getResponse().isSuccess();
  266. }
  267. catch (Exception e)
  268. {
  269. cookie = null;
  270. return false;
  271. }
  272. }
  273. /**
  274. * Sends a keepalive message
  275. * @return true if user is currently logged in
  276. */
  277. public Boolean sendKeepalive() {
  278. return sendKeepalive(false);
  279. }
  280. public Boolean sendKeepalive(boolean bAdminOnly) {
  281. try {
  282. String address = apiRoot + "auth/keepalive";
  283. if (bAdminOnly) {
  284. address += "/admin";
  285. }
  286. String logoutResult;
  287. logoutResult = sendRequest(address, null);
  288. ResponsePojo response = ResponsePojo.fromApi(logoutResult, ResponsePojo.class);
  289. return response.getResponse().isSuccess();
  290. }
  291. catch (Exception e)
  292. {
  293. return false;
  294. }
  295. }
  296. public Boolean deactivateUser(String username)
  297. {
  298. try
  299. {
  300. String deactivateAddress = apiRoot + "auth/deactivate?username=" + URLEncoder.encode(username,"UTF-8");
  301. String deactivateResult = sendRequest(deactivateAddress, null);
  302. ResponsePojo response = ResponsePojo.fromApi(deactivateResult, ResponsePojo.class);
  303. return response.getResponse().isSuccess();
  304. }
  305. catch (Exception e)
  306. {
  307. e.printStackTrace();
  308. }
  309. return false;
  310. }
  311. //////////////////////////////////////////////////////////////////////////////////////////////
  312. // SOCIAL - COMMUNITIES
  313. /**
  314. * createCommunity
  315. * @param communityName
  316. * @param communityDesc
  317. * @param communityTag
  318. * @param responsePojo
  319. * @return CommunityPojo
  320. */
  321. public CommunityPojo createCommunity(String communityName, String communityDesc, String communityTags,String parentid, ResponseObject responseObject )
  322. {
  323. try{
  324. String createCommunityAddress = apiRoot + "social/community/add/" + URLEncoder.encode(communityName,"UTF-8") + "/" +
  325. URLEncoder.encode(communityDesc,"UTF-8") + "/" + URLEncoder.encode(communityTags,"UTF-8");
  326. if (null != parentid)
  327. createCommunityAddress += "/" + URLEncoder.encode(parentid,"UTF-8");
  328. String communityresult = sendRequest(createCommunityAddress, null);
  329. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(communityresult, ResponsePojo.class, CommunityPojo.class, new CommunityPojoApiMap());
  330. ResponseObject internal_ro = internal_responsePojo.getResponse();
  331. responseObject = shallowCopy(responseObject, internal_ro);
  332. return (CommunityPojo)internal_responsePojo.getData();
  333. }
  334. catch (Exception e)
  335. {
  336. e.printStackTrace();
  337. }
  338. return null;
  339. }
  340. public String addToCommunity(String communityId, String personId, ResponseObject responseObject )
  341. {
  342. try
  343. {
  344. String addToCommunityAddress = apiRoot + "social/community/member/invite/" + URLEncoder.encode(communityId,"UTF-8") + "/" +
  345. URLEncoder.encode(personId,"UTF-8") + "/";
  346. String inviteresult = sendRequest(addToCommunityAddress, null);
  347. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(inviteresult, ResponsePojo.class, CommunityPojo.class, new CommunityPojoApiMap());
  348. ResponseObject internal_ro = internal_responsePojo.getResponse();
  349. responseObject = shallowCopy(responseObject, internal_ro);
  350. return responseObject.getMessage();
  351. }
  352. catch (Exception e)
  353. {
  354. e.printStackTrace();
  355. }
  356. return null;
  357. }
  358. public String joinCommunity(String communityId, ResponseObject responseObject )
  359. {
  360. try
  361. {
  362. String addToCommunityAddress = apiRoot + "social/community/member/join/" + URLEncoder.encode(communityId,"UTF-8");
  363. String inviteresult = sendRequest(addToCommunityAddress, null);
  364. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(inviteresult, ResponsePojo.class, CommunityPojo.class, new CommunityPojoApiMap());
  365. ResponseObject internal_ro = internal_responsePojo.getResponse();
  366. responseObject = shallowCopy(responseObject, internal_ro);
  367. return responseObject.getMessage();
  368. }
  369. catch (Exception e)
  370. {
  371. e.printStackTrace();
  372. }
  373. return null;
  374. }
  375. public String forcefullyAddToCommunity(String communityId, String personId, ResponseObject responseObject )
  376. {
  377. try
  378. {
  379. String addToCommunityAddress = apiRoot + "social/community/member/invite/" + URLEncoder.encode(communityId,"UTF-8") + "/" +
  380. URLEncoder.encode(personId,"UTF-8") + "/?skipinvitation=true";
  381. String inviteresult = sendRequest(addToCommunityAddress, null);
  382. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(inviteresult, ResponsePojo.class, CommunityPojo.class, new CommunityPojoApiMap());
  383. ResponseObject internal_ro = internal_responsePojo.getResponse();
  384. responseObject = shallowCopy(responseObject, internal_ro);
  385. return responseObject.getMessage();
  386. }
  387. catch (Exception e)
  388. {
  389. e.printStackTrace();
  390. }
  391. return null;
  392. }
  393. public CommunityPojo getCommunity(String communityIdentifier, ResponseObject responseObject )
  394. {
  395. try
  396. {
  397. String getCommunityAddress = apiRoot + "social/community/get/" + URLEncoder.encode(communityIdentifier,"UTF-8") + "";
  398. String getResult = sendRequest(getCommunityAddress, null);
  399. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(getResult, ResponsePojo.class, CommunityPojo.class, new CommunityPojoApiMap());
  400. ResponseObject internal_ro = internal_responsePojo.getResponse();
  401. responseObject = shallowCopy(responseObject, internal_ro);
  402. return (CommunityPojo)internal_responsePojo.getData();
  403. }
  404. catch (Exception e)
  405. {
  406. e.printStackTrace();
  407. }
  408. return null;
  409. }
  410. public List<CommunityPojo> getPublicCommunities(ResponseObject responseObject)
  411. {
  412. try
  413. {
  414. String getCommunityAddress = apiRoot + "social/community/getpublic";
  415. String getResult = sendRequest(getCommunityAddress, null);
  416. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(getResult, ResponsePojo.class);
  417. ResponseObject internal_ro = internal_responsePojo.getResponse();
  418. responseObject = shallowCopy(responseObject, internal_ro);
  419. List<CommunityPojo> communities = null;
  420. communities = ApiManager.mapListFromApi((JsonElement)internal_responsePojo.getData(),
  421. CommunityPojo.listType(), null);
  422. return communities;
  423. }
  424. catch (Exception e)
  425. {
  426. responseObject.setSuccess(false);
  427. responseObject.setMessage(e.getMessage());
  428. }
  429. return null;
  430. }
  431. public List<CommunityPojo> getAllCommunity(ResponseObject responseObject)
  432. {
  433. try
  434. {
  435. String getCommunityAddress = apiRoot + "social/community/getall";
  436. String getResult = sendRequest(getCommunityAddress, null);
  437. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(getResult, ResponsePojo.class);
  438. ResponseObject internal_ro = internal_responsePojo.getResponse();
  439. responseObject = shallowCopy(responseObject, internal_ro);
  440. List<CommunityPojo> communities = null;
  441. communities = ApiManager.mapListFromApi((JsonElement)internal_responsePojo.getData(),
  442. CommunityPojo.listType(), null);
  443. return communities;
  444. }
  445. catch (Exception e)
  446. {
  447. responseObject.setSuccess(false);
  448. responseObject.setMessage(e.getMessage());
  449. }
  450. return null;
  451. }
  452. public Boolean deleteCommunity(String communityId, ResponseObject responseObject)
  453. {
  454. try
  455. {
  456. String addToCommunityAddress = apiRoot + "social/community/remove/" + URLEncoder.encode(communityId,"UTF-8");
  457. String inviteresult = sendRequest(addToCommunityAddress, null);
  458. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(inviteresult, ResponsePojo.class);
  459. ResponseObject internal_ro = internal_responsePojo.getResponse();
  460. responseObject = shallowCopy(responseObject, internal_ro);
  461. return responseObject.isSuccess();
  462. }
  463. catch (Exception e)
  464. {
  465. e.printStackTrace();
  466. }
  467. return null;
  468. }
  469. public Boolean updateCommunity(String communityId, CommunityPojo communityPojo, ResponseObject responseObject)
  470. {
  471. try{
  472. String addToCommunityAddress = apiRoot + "social/community/update/" + URLEncoder.encode(communityId,"UTF-8");
  473. String updateResult = sendRequest(addToCommunityAddress, new Gson().toJson(communityPojo));
  474. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(updateResult, ResponsePojo.class);
  475. ResponseObject internal_ro = internal_responsePojo.getResponse();
  476. responseObject = shallowCopy(responseObject, internal_ro);
  477. return responseObject.isSuccess();
  478. }
  479. catch (Exception e)
  480. {
  481. e.printStackTrace();
  482. }
  483. return false;
  484. }
  485. public Boolean updateCommunityMemberType(String communityId, String personId, String userType, ResponseObject responseObject)
  486. {
  487. try
  488. {
  489. String updateCommunityMemberUrl = apiRoot + "social/community/member/update/type/" + URLEncoder.encode(communityId,"UTF-8") +
  490. "/" + URLEncoder.encode(personId,"UTF-8") + "/" + URLEncoder.encode(userType,"UTF-8");
  491. String updateResult = sendRequest(updateCommunityMemberUrl, null);
  492. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(updateResult, ResponsePojo.class);
  493. ResponseObject internal_ro = internal_responsePojo.getResponse();
  494. responseObject = shallowCopy(responseObject, internal_ro);
  495. return responseObject.isSuccess();
  496. }
  497. catch (Exception e)
  498. {
  499. e.printStackTrace();
  500. }
  501. return false;
  502. }
  503. public Boolean updateCommunityMemberStatus(String communityId, String personId, String userStatus, ResponseObject responseObject)
  504. {
  505. try
  506. {
  507. String updateCommunityMemberUrl = apiRoot + "social/community/member/update/status/" + URLEncoder.encode(communityId,"UTF-8") +
  508. "/" + URLEncoder.encode(personId,"UTF-8") + "/" + URLEncoder.encode(userStatus,"UTF-8");
  509. String updateResult = sendRequest(updateCommunityMemberUrl, null);
  510. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(updateResult, ResponsePojo.class);
  511. ResponseObject internal_ro = internal_responsePojo.getResponse();
  512. responseObject = shallowCopy(responseObject, internal_ro);
  513. return responseObject.isSuccess();
  514. }
  515. catch (Exception e)
  516. {
  517. e.printStackTrace();
  518. }
  519. return false;
  520. }
  521. //////////////////////////////////////////////////////////////////////////////////////////////
  522. // SOCIAL - SHARES
  523. public List<SharePojo> searchShares(String searchCriteria, String searchString, String typeFilter, ResponseObject responseObject)
  524. {
  525. return searchShares(searchCriteria,searchString,typeFilter,false,responseObject);
  526. }
  527. //TESTED
  528. public List<SharePojo> searchShares(String searchCriteria, String searchString, String typeFilter, Boolean searchParent, ResponseObject responseObject)
  529. {
  530. try {
  531. StringBuffer url = new StringBuffer(apiRoot).append("social/share/search/");
  532. if (null != searchCriteria) {
  533. url.append("?searchby=").append(searchCriteria).append("&id=").append(URLEncoder.encode(searchString, "UTF-8"));
  534. }
  535. if (null != typeFilter) {
  536. if (null != searchCriteria) {
  537. url.append("&");
  538. }
  539. else {
  540. url.append("?");
  541. }
  542. url.append("type=").append(typeFilter);
  543. }
  544. if ( searchParent )
  545. {
  546. if ( null != searchCriteria && null != typeFilter)
  547. url.append("&");
  548. else
  549. url.append("?");
  550. url.append("searchParent=true");
  551. }
  552. String deleteResult = sendRequest(url.toString(), null);
  553. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(deleteResult, ResponsePojo.class);
  554. ResponseObject internal_ro = internal_responsePojo.getResponse();
  555. responseObject = shallowCopy(responseObject, internal_ro);
  556. List<SharePojo> shares = null;
  557. shares = ApiManager.mapListFromApi((JsonElement)internal_responsePojo.getData(),
  558. SharePojo.listType(), null);
  559. return shares;
  560. }
  561. catch (Exception e) {
  562. responseObject.setSuccess(false);
  563. responseObject.setMessage(e.getMessage());
  564. }
  565. return null;
  566. }
  567. public SharePojo getShare(String shareId, ResponseObject responseObject)
  568. {
  569. try{
  570. String getShareAddress = apiRoot + "social/share/get/" + URLEncoder.encode(shareId,"UTF-8");
  571. String getResult = sendRequest(getShareAddress, null);
  572. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(getResult, ResponsePojo.class, SharePojo.class, new SharePojoApiMap(null));
  573. ResponseObject internal_ro = internal_responsePojo.getResponse();
  574. responseObject = shallowCopy(responseObject, internal_ro);
  575. return (SharePojo)internal_responsePojo.getData();
  576. }
  577. catch (Exception e)
  578. {
  579. e.printStackTrace();
  580. }
  581. return null;
  582. }
  583. public SharePojo addShareJSON(String title, String description, String type, String jsonString , ResponseObject responseObject)
  584. {
  585. try
  586. {
  587. String addShareAddress = apiRoot + "social/share/add/json/" + URLEncoder.encode(type, "UTF-8") + "/" + URLEncoder.encode(title,"UTF-8") + "/" + URLEncoder.encode(description,"UTF-8");
  588. String addResult = sendRequest(addShareAddress, jsonString);
  589. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(addResult, ResponsePojo.class, SharePojo.class, new SharePojoApiMap(null));
  590. ResponseObject internal_ro = internal_responsePojo.getResponse();
  591. responseObject = shallowCopy(responseObject, internal_ro);
  592. return (SharePojo)internal_responsePojo.getData();
  593. }
  594. catch (Exception e)
  595. {
  596. e.printStackTrace();
  597. }
  598. return null;
  599. }
  600. public Boolean updateShareJSON(String shareId, String title, String description, String type, String jsonString , ResponseObject responseObject)
  601. {
  602. try{
  603. String updateShareAddress = apiRoot + "social/share/update/json/" + shareId + "/" + URLEncoder.encode(type,"UTF-8") + "/" + URLEncoder.encode(title,"UTF-8") + "/" + URLEncoder.encode(description,"UTF-8");
  604. String updateResult = sendRequest(updateShareAddress, jsonString);
  605. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(updateResult, ResponsePojo.class);
  606. ResponseObject internal_ro = internal_responsePojo.getResponse();
  607. responseObject = shallowCopy(responseObject, internal_ro);
  608. return responseObject.isSuccess();
  609. }
  610. catch (Exception e)
  611. {
  612. e.printStackTrace();
  613. }
  614. return false;
  615. }
  616. public Boolean removeShare(String shareId, ResponseObject responseObject)
  617. {
  618. try{
  619. String removeShareAddress = apiRoot + "social/share/remove/" + URLEncoder.encode(shareId,"UTF-8");
  620. String updateResult = sendRequest(removeShareAddress, null);
  621. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(updateResult, ResponsePojo.class);
  622. ResponseObject internal_ro = internal_responsePojo.getResponse();
  623. responseObject = shallowCopy(responseObject, internal_ro);
  624. return responseObject.isSuccess();
  625. }
  626. catch (Exception e)
  627. {
  628. e.printStackTrace();
  629. }
  630. return false;
  631. }
  632. public Boolean addShareToCommunity(String shareId, String comment, String communityId, ResponseObject responseObject)
  633. {
  634. try
  635. {
  636. String addCommunityAddress = apiRoot + "social/share/add/community/" + shareId + "/" + URLEncoder.encode(comment,"UTF-8") + "/" + URLEncoder.encode(communityId,"UTF-8");
  637. String updateResult = sendRequest(addCommunityAddress, null);
  638. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(updateResult, ResponsePojo.class);
  639. ResponseObject internal_ro = internal_responsePojo.getResponse();
  640. responseObject = shallowCopy(responseObject, internal_ro);
  641. return responseObject.isSuccess();
  642. }
  643. catch (Exception e)
  644. {
  645. e.printStackTrace();
  646. }
  647. return false;
  648. }
  649. public Boolean removeShareFromCommunity(String shareId, String communityId, ResponseObject responseObject)
  650. {
  651. try{
  652. String addCommunityAddress = apiRoot + "social/share/remove/community/" + shareId + "/" + URLEncoder.encode(communityId,"UTF-8");
  653. String updateResult = sendRequest(addCommunityAddress, null);
  654. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(updateResult, ResponsePojo.class);
  655. ResponseObject internal_ro = internal_responsePojo.getResponse();
  656. responseObject = shallowCopy(responseObject, internal_ro);
  657. return responseObject.isSuccess();
  658. }
  659. catch (Exception e)
  660. {
  661. e.printStackTrace();
  662. }
  663. return false;
  664. }
  665. //////////////////////////////////////////////////////////////////////////////////////////////
  666. // SOCIAL - PEOPLE
  667. public String deletePerson(String personId, ResponseObject responseObject)
  668. {
  669. try
  670. {
  671. String deletePersonAddress = apiRoot + "social/person/delete/" + URLEncoder.encode(personId,"UTF-8");
  672. String deleteResult = sendRequest(deletePersonAddress, null);
  673. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(deleteResult, ResponsePojo.class);
  674. ResponseObject internal_ro = internal_responsePojo.getResponse();
  675. responseObject = shallowCopy(responseObject, internal_ro);
  676. return responseObject.getMessage();
  677. }
  678. catch (Exception e)
  679. {
  680. e.printStackTrace();
  681. }
  682. return null;
  683. }
  684. /**
  685. * getPerson
  686. * @param personId Can be the person id, email address, or Null. If Null, it will return information about current user.
  687. * @param responsePojo
  688. * @return PersonPojo
  689. */
  690. public PersonPojo getPerson(String personId, ResponseObject responseObject)
  691. {
  692. try
  693. {
  694. String getPersonAddress = apiRoot + "social/person/get";
  695. if (personId != null)
  696. getPersonAddress += "/" + URLEncoder.encode(personId,"UTF-8");
  697. String getResult = sendRequest(getPersonAddress, null);
  698. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(getResult, ResponsePojo.class, PersonPojo.class, new PersonPojoApiMap());
  699. ResponseObject internal_ro = internal_responsePojo.getResponse();
  700. responseObject = shallowCopy(responseObject, internal_ro);
  701. return (PersonPojo)internal_responsePojo.getData();
  702. }
  703. catch (Exception e)
  704. {
  705. e.printStackTrace();
  706. }
  707. return null;
  708. }
  709. /**
  710. * listPerson
  711. *
  712. * @param responseObject
  713. * @return
  714. */
  715. public List<PersonPojo> listPerson(ResponseObject responseObject)
  716. {
  717. try
  718. {
  719. String listPersonAddress = apiRoot + "social/person/list";
  720. String getResult = sendRequest(listPersonAddress, null);
  721. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(getResult, ResponsePojo.class);
  722. ResponseObject internal_ro = internal_responsePojo.getResponse();
  723. responseObject = shallowCopy(responseObject, internal_ro);
  724. List<PersonPojo> people = null;
  725. people = ApiManager.mapListFromApi((JsonElement)internal_responsePojo.getData(), PersonPojo.listType(), new PersonPojoApiMap());
  726. return people;
  727. }
  728. catch (Exception e)
  729. {
  730. e.printStackTrace();
  731. }
  732. return null;
  733. }
  734. public String registerPerson(String first_name, String last_name, String phone, String email, String password, String accountType, ResponseObject responseObject)
  735. {
  736. try {
  737. Date date = new Date();
  738. SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy kk:mm:ss aa");
  739. String today = formatter.format(date);
  740. String encrypted_password;
  741. encrypted_password = encryptWithoutEncode(password);
  742. WordPressUserPojo wpuser = new WordPressUserPojo();
  743. WordPressAuthPojo wpauth = new WordPressAuthPojo();
  744. wpuser.setCreated(today);
  745. wpuser.setModified(today);
  746. wpuser.setFirstname(first_name);
  747. wpuser.setLastname(last_name);
  748. wpuser.setPhone(phone);
  749. ArrayList<String> emailArray = new ArrayList<String>();
  750. emailArray.add(email);
  751. wpuser.setEmail(emailArray);
  752. //wpauth.setWPUserID(email);
  753. wpauth.setPassword(encrypted_password);
  754. wpauth.setAccountType(accountType);
  755. wpauth.setCreated(today);
  756. wpauth.setModified(today);
  757. WordPressSetupPojo wpSetup = new WordPressSetupPojo();
  758. wpSetup.setAuth(wpauth);
  759. wpSetup.setUser(wpuser);
  760. return registerPerson(wpSetup, responseObject);
  761. } catch (NoSuchAlgorithmException e) {
  762. e.printStackTrace();
  763. } catch (UnsupportedEncodingException e) {
  764. e.printStackTrace();
  765. }
  766. return null;
  767. }
  768. public String registerPerson(WordPressSetupPojo wpSetup, ResponseObject responseObject)
  769. {
  770. String theUrl = apiRoot + "social/person/register";
  771. String data = new Gson().toJson(wpSetup);
  772. String registerResult = sendRequest(theUrl, data);
  773. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(registerResult, ResponsePojo.class);
  774. ResponseObject internal_ro = internal_responsePojo.getResponse();
  775. responseObject = shallowCopy(responseObject, internal_ro);
  776. return responseObject.getMessage();
  777. }
  778. public String updatePerson(String first_name, String last_name, String phone, String email, String password, String accountType, ResponseObject responseObject)
  779. {
  780. try
  781. {
  782. Date date = new Date();
  783. SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy kk:mm:ss aa");
  784. String today = formatter.format(date);
  785. String encrypted_password = null;
  786. if ( password != null )
  787. encrypted_password = encryptWithoutEncode(password);
  788. WordPressUserPojo wpuser = new WordPressUserPojo();
  789. WordPressAuthPojo wpauth = new WordPressAuthPojo();
  790. wpuser.setModified(today);
  791. wpuser.setFirstname(first_name);
  792. wpuser.setLastname(last_name);
  793. wpuser.setPhone(phone);
  794. ArrayList<String> emailArray = new ArrayList<String>();
  795. emailArray.add(email);
  796. wpuser.setEmail(emailArray);
  797. wpauth.setWPUserID(email);
  798. wpauth.setPassword(encrypted_password);
  799. wpauth.setAccountType(accountType);
  800. wpauth.setModified(today);
  801. return updatePerson(wpuser, wpauth, responseObject);
  802. } catch (NoSuchAlgorithmException e) {
  803. e.printStackTrace();
  804. } catch (UnsupportedEncodingException e) {
  805. e.printStackTrace();
  806. }
  807. return null;
  808. }
  809. public String updatePerson(WordPressUserPojo wpuser, WordPressAuthPojo wpauth, ResponseObject responseObject)
  810. {
  811. String theUrl = apiRoot + "social/person/update";
  812. String data = "{ \"user\":" + new Gson().toJson(wpuser) + ", \"auth\":" + new Gson().toJson(wpauth) + "}";
  813. String updateResult = sendRequest(theUrl, data);
  814. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(updateResult, ResponsePojo.class);
  815. ResponseObject internal_ro = internal_responsePojo.getResponse();
  816. responseObject = shallowCopy(responseObject, internal_ro);
  817. return responseObject.getMessage();
  818. }
  819. public String updatePersonPassword(String id, String newPassword, ResponseObject responseObject)
  820. {
  821. try
  822. {
  823. String updatePasswordAddress = apiRoot + "social/person/update/password/" + URLEncoder.encode(id,"UTF-8") + "/" + URLEncoder.encode(newPassword,"UTF-8");
  824. String updateResult = sendRequest(updatePasswordAddress, null);
  825. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(updateResult, ResponsePojo.class);
  826. ResponseObject internal_ro = internal_responsePojo.getResponse();
  827. responseObject = shallowCopy(responseObject, internal_ro);
  828. return responseObject.getMessage();
  829. }
  830. catch (Exception e)
  831. {
  832. e.printStackTrace();
  833. }
  834. return "";
  835. }
  836. //////////////////////////////////////////////////////////////////////////////////////////////
  837. // CONFIG - SOURCE
  838. public SourcePojo getSource(String sourceId, ResponseObject responseObject)
  839. {
  840. try{
  841. String getSourceAddress = apiRoot + "config/source/get/" + URLEncoder.encode(sourceId,"UTF-8");
  842. String getResult = sendRequest(getSourceAddress, null);
  843. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(getResult, ResponsePojo.class, SourcePojo.class, new SourcePojoApiMap(null));
  844. ResponseObject internal_ro = internal_responsePojo.getResponse();
  845. responseObject = shallowCopy(responseObject, internal_ro);
  846. return (SourcePojo)internal_responsePojo.getData();
  847. }
  848. catch (Exception e)
  849. {
  850. e.printStackTrace();
  851. }
  852. return null;
  853. }
  854. public SourcePojo saveSource(SourcePojo source, String communityId, ResponseObject responseObject)
  855. {
  856. try {
  857. String address = apiRoot + "config/source/save/" + communityId + "/";
  858. String saveResult;
  859. saveResult = sendRequest(address, new Gson().toJson(source));
  860. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(saveResult, ResponsePojo.class, SourcePojo.class, new SourcePojoApiMap(null));
  861. ResponseObject internal_ro = internal_responsePojo.getResponse();
  862. responseObject = shallowCopy(responseObject, internal_ro);
  863. return (SourcePojo)internal_responsePojo.getData();
  864. }
  865. catch (Exception e)
  866. {
  867. e.printStackTrace();
  868. }
  869. return null;
  870. }
  871. public String deleteSource(String sourceId, String communityId, ResponseObject responseObject)
  872. {
  873. try {
  874. String address = apiRoot + "config/source/delete/" + sourceId + "/" + communityId;
  875. String deleteResult = sendRequest(address, null);
  876. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(deleteResult, ResponsePojo.class);
  877. ResponseObject internal_ro = internal_responsePojo.getResponse();
  878. responseObject = shallowCopy(responseObject, internal_ro);
  879. return responseObject.getMessage();
  880. }
  881. catch (Exception e)
  882. {
  883. e.printStackTrace();
  884. }
  885. return null;
  886. }
  887. public List<DocumentPojo> testSource(SourcePojo testSrc, ResponseObject response, int nToReturn, boolean bReturnFullText) {
  888. StringBuffer theUrl = new StringBuffer(apiRoot).append("config/source/test");
  889. if (nToReturn > 0) {
  890. theUrl.append("?numReturn=").append(nToReturn);
  891. }
  892. if (bReturnFullText) {
  893. if (nToReturn > 0) {
  894. theUrl.append('&');
  895. }
  896. else {
  897. theUrl.append('?');
  898. }
  899. theUrl.append("returnFullText=true");
  900. }
  901. String map = ApiManager.mapToApi(testSrc, null);
  902. String testResult = sendRequest(theUrl.toString(), map);
  903. ResponsePojo internal_response = ResponsePojo.fromApi(testResult, ResponsePojo.class);
  904. shallowCopy(response, internal_response.getResponse());
  905. List<DocumentPojo> docs = null;
  906. if (response.isSuccess()) {
  907. docs = ApiManager.mapListFromApi((JsonElement)internal_response.getData(),
  908. DocumentPojo.listType(), new DocumentPojoApiMap());
  909. }
  910. return docs;
  911. }
  912. //////////////////////////////////////////////////////////////////////////////////////////////
  913. // KNOWLEDGE - QUERY
  914. // Queries are slightly different - the entire ResponsePojo is used.
  915. public ResponsePojo sendQuery(AdvancedQueryPojo query, ObjectId communityId, ResponseObject response) {
  916. ArrayList<ObjectId> community = new ArrayList<ObjectId>(1);
  917. community.add(communityId);
  918. return sendQuery(query, community, response);
  919. }
  920. public ResponsePojo sendQuery(AdvancedQueryPojo query, Collection<ObjectId> communities, ResponseObject response) {
  921. StringBuffer theUrl = new StringBuffer(apiRoot).append("knowledge/document/query/");
  922. boolean bFirstComm = true;
  923. for (ObjectId commId: communities) {
  924. if (!bFirstComm)
  925. theUrl.append(',');
  926. theUrl.append(commId.toString());
  927. bFirstComm = false;
  928. }
  929. String testResult = sendRequest(theUrl.toString(), query.toApi());
  930. ResponsePojo internal_response = ResponsePojo.fromApi(testResult, ResponsePojo.class);
  931. shallowCopy(response, internal_response.getResponse());
  932. return internal_response;
  933. }
  934. //////////////////////////////////////////////////////////////////////////////////////////////
  935. // KNOWLEDGE - DOCUMENT - GET
  936. public DocumentPojo getDocument(String docid, ResponseObject responseObject)
  937. {
  938. return getDocument(docid,false,false,responseObject);
  939. }
  940. public DocumentPojo getDocument(String docid, boolean returnFullText, boolean returnRawData, ResponseObject responseObject)
  941. {
  942. try
  943. {
  944. StringBuffer theUrl = new StringBuffer(apiRoot).append("knowledge/document/get/");
  945. theUrl.append(docid);
  946. theUrl.append("?returnFullText=").append(returnFullText);
  947. theUrl.append("?returnRawData=").append(returnRawData);
  948. String getResult = sendRequest(theUrl.toString(), null);
  949. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(getResult, ResponsePojo.class, DocumentPojo.class, new DocumentPojoApiMap());
  950. ResponseObject internal_ro = internal_responsePojo.getResponse();
  951. responseObject = shallowCopy(responseObject, internal_ro);
  952. return (DocumentPojo)internal_responsePojo.getData();
  953. }
  954. catch (Exception ex)
  955. {
  956. ex.printStackTrace();
  957. }
  958. return null;
  959. }
  960. public DocumentPojo getDocument(String sourceKey, String url, ResponseObject responseObject)
  961. {
  962. return getDocument(sourceKey, url, false, false, responseObject);
  963. }
  964. public DocumentPojo getDocument(String sourceKey, String url, boolean returnFullText, boolean returnRawData, ResponseObject responseObject)
  965. {
  966. try
  967. {
  968. StringBuffer theUrl = new StringBuffer(apiRoot).append("knowledge/document/get/");
  969. theUrl.append(sourceKey).append("/").append(url);
  970. theUrl.append("?returnFullText=").append(returnFullText);
  971. theUrl.append("?returnRawData=").append(returnRawData);
  972. String getResult = sendRequest(theUrl.toString(), null);
  973. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(getResult, ResponsePojo.class, DocumentPojo.class, new DocumentPojoApiMap());
  974. ResponseObject internal_ro = internal_responsePojo.getResponse();
  975. responseObject = shallowCopy(responseObject, internal_ro);
  976. return (DocumentPojo)internal_responsePojo.getData();
  977. }
  978. catch (Exception ex)
  979. {
  980. ex.printStackTrace();
  981. }
  982. return null;
  983. }
  984. //////////////////////////////////////////////////////////////////////////////////////////////
  985. // CUSTOM - CREATE PLUGIN TASK
  986. // The following fields of taskConfig are filled in (string unless otherwise specified):
  987. // - jobtitle, jobdesc
  988. // - jarURL: the name of the JAR in the share
  989. // - inputCollection
  990. // - firstSchedule (Date) ... when it will be run
  991. // - scheduleFreq (SCHEDULE_FREQUENCY)
  992. // - mapper, combiner, reducer
  993. // - outputKey, outputValue
  994. // - appendResult, ageOutInDays
  995. // - jobDependencies ... though using the input param that allows them to be specified as jobtitles is recommended
  996. public ObjectId createCustomPluginTask(CustomMapReduceJobPojo taskConfig, Collection<String> dependencies, ObjectId communityId, ResponseObject response) {
  997. ArrayList<ObjectId> community = new ArrayList<ObjectId>(1);
  998. community.add(communityId);
  999. return createCustomPluginTask(taskConfig, dependencies, community, response);
  1000. }
  1001. public ObjectId createCustomPluginTask(CustomMapReduceJobPojo taskConfig, Collection<String> dependencies, Collection<ObjectId> communities, ResponseObject response) {
  1002. return createCustomPluginTask(taskConfig, dependencies, communities, response, false);
  1003. }
  1004. private ObjectId createCustomPluginTask(CustomMapReduceJobPojo taskConfig, Collection<String> dependencies, Collection<ObjectId> communities, ResponseObject response, boolean bUpdate) {
  1005. ObjectId retVal = null;
  1006. try {
  1007. StringBuffer url = new StringBuffer(apiRoot).append("custom/mapreduce/");
  1008. if (bUpdate) {
  1009. if (taskConfig._id != null) {
  1010. url.append("updatejob/").append(taskConfig._id.toString()).append("/");
  1011. }
  1012. else {
  1013. url.append("updatejob/").append(taskConfig.jobtitle).append("/");
  1014. taskConfig.jobtitle = null;
  1015. }//TESTED
  1016. }
  1017. else {
  1018. url.append("schedulejob/");
  1019. }
  1020. if (null != communities) {
  1021. for (ObjectId communityId: communities) {
  1022. url.append(communityId.toString()).append(',');
  1023. }
  1024. url.setLength(url.length() - 1);
  1025. }
  1026. else {
  1027. url.append("null");
  1028. }
  1029. url.append('/');
  1030. if ((null != taskConfig.jobDependencies) && !taskConfig.jobDependencies.isEmpty()) {
  1031. for (ObjectId jobId: taskConfig.jobDependencies) {
  1032. url.append(jobId.toString()).append(',');
  1033. }
  1034. url.setLength(url.length() - 1);
  1035. }
  1036. else if ((null != dependencies) && !dependencies.isEmpty()) {
  1037. for (String jobTitle: dependencies) {
  1038. url.append(jobTitle).append(',');
  1039. }
  1040. url.setLength(url.length() - 1);
  1041. }
  1042. else {
  1043. url.append("null");
  1044. }
  1045. url.append("/");
  1046. // "nextRunTime"==first Schedule (date)
  1047. if (null != taskConfig.firstSchedule) {
  1048. taskConfig.nextRunTime = taskConfig.firstSchedule.getTime();
  1049. }
  1050. String json = sendRequest(url.toString(), ApiManager.mapToApi(taskConfig, null));
  1051. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(json, ResponsePojo.class);
  1052. ResponseObject internal_ro = internal_responsePojo.getResponse();
  1053. response = shallowCopy(response, internal_ro);
  1054. if (response.isSuccess()) {
  1055. JsonPrimitive retValObj = (JsonPrimitive)internal_responsePojo.getData();
  1056. retVal = new ObjectId(retValObj.getAsString());
  1057. }
  1058. }
  1059. catch (Exception e) {
  1060. response.setSuccess(false);
  1061. response.setMessage(e.getMessage());
  1062. }
  1063. return retVal;
  1064. }
  1065. //TESTED (one minor clause to test, will leave for now)
  1066. ///////////////////////////////////////////////////////////////////
  1067. // Updates ... as above but jobtitle or _id must be specified
  1068. public ObjectId updateCustomPluginTask(CustomMapReduceJobPojo taskConfig, Collection<String> dependencies, ObjectId communityId, ResponseObject response) {
  1069. ArrayList<ObjectId> community = new ArrayList<ObjectId>(1);
  1070. community.add(communityId);
  1071. return updateCustomPluginTask(taskConfig, dependencies, community, response);
  1072. }
  1073. public ObjectId updateCustomPluginTask(CustomMapReduceJobPojo taskConfig, Collection<String> dependencies, Collection<ObjectId> communities, ResponseObject response) {
  1074. return createCustomPluginTask(taskConfig, dependencies, communities, response, true);
  1075. }
  1076. //TESTED
  1077. //////////////////////////////////////////////////////////////////////////////////////////////
  1078. // CUSTOM - CREATE PLUGIN TASK
  1079. // The following fields of taskConfig are filled in (string unless otherwise specified):
  1080. // - jobtitle, jobdesc
  1081. // - firstSchedule (Date) ... when it will be run
  1082. // - scheduleFreq (SCHEDULE_FREQUENCY)
  1083. // - appendResult, ageOutInDays
  1084. public ObjectId createCustomSavedQueryTask(CustomMapReduceJobPojo taskConfig, AdvancedQueryPojo query, ObjectId communityId, ResponseObject response) {
  1085. ArrayList<ObjectId> community = new ArrayList<ObjectId>(1);
  1086. community.add(communityId);
  1087. return createCustomSavedQueryTask(taskConfig, query, community, response);
  1088. }
  1089. public ObjectId createCustomSavedQueryTask(CustomMapReduceJobPojo taskConfig, ObjectId communityId, ResponseObject response) {
  1090. ArrayList<ObjectId> community = new ArrayList<ObjectId>(1);
  1091. community.add(communityId);
  1092. return createCustomSavedQueryTask(taskConfig, null, community, response);
  1093. }
  1094. public ObjectId createCustomSavedQueryTask(CustomMapReduceJobPojo taskConfig, AdvancedQueryPojo query, Collection<ObjectId> communities, ResponseObject response) {
  1095. if (null != query) {
  1096. taskConfig.query = query.toApi();
  1097. }
  1098. return createCustomPluginTask(taskConfig, null, communities, response);
  1099. }
  1100. //TESTED
  1101. ///////////////////////////////////////////////////////////////////
  1102. // Updates ... as above but jobtitle or _id must be specified
  1103. public ObjectId updateCustomSavedQueryTask(CustomMapReduceJobPojo taskConfig, AdvancedQueryPojo query, ObjectId communityId, ResponseObject response) {
  1104. ArrayList<ObjectId> community = new ArrayList<ObjectId>(1);
  1105. community.add(communityId);
  1106. return updateCustomSavedQueryTask(taskConfig, query, community, response);
  1107. }
  1108. public ObjectId updateCustomSavedQueryTask(CustomMapReduceJobPojo taskConfig, ObjectId communityId, ResponseObject response) {
  1109. ArrayList<ObjectId> community = new ArrayList<ObjectId>(1);
  1110. community.add(communityId);
  1111. return updateCustomPluginTask(taskConfig, null, community, response);
  1112. }
  1113. public ObjectId updateCustomSavedQueryTask(CustomMapReduceJobPojo taskConfig, AdvancedQueryPojo query, Collection<ObjectId> communities, ResponseObject response) {
  1114. if (null != query) {
  1115. taskConfig.query = query.toApi();
  1116. }
  1117. return updateCustomPluginTask(taskConfig, null, communities, response);
  1118. }
  1119. //TESTED
  1120. public CustomMapReduceResultPojo getCustomTaskOrQueryResults(String jobtitle, ResponseObject response)
  1121. {
  1122. CustomMapReduceResultPojo retVal = null;
  1123. try
  1124. {
  1125. StringBuilder url = new StringBuilder(apiRoot).append("custom/mapreduce/getresults/");
  1126. if ( null != jobtitle)
  1127. {
  1128. url.append(jobtitle);
  1129. }
  1130. String json = sendRequest(url.toString(), null);
  1131. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(json, ResponsePojo.class, CustomMapReduceResultPojo.class, new CustomMapReduceResultPojoApiMap());
  1132. ResponseObject internal_ro = internal_responsePojo.getResponse();
  1133. response = shallowCopy(response, internal_ro);
  1134. if (response.isSuccess())
  1135. {
  1136. //JsonElement js = (JsonElement)internal_responsePojo.getData();
  1137. //retVal = ApiManager.mapFromApi(js, CustomMapReduceResultPojo.class, null);
  1138. retVal = (CustomMapReduceResultPojo)internal_responsePojo.getData();
  1139. }
  1140. }
  1141. catch (Exception e)
  1142. {
  1143. response.setSuccess(false);
  1144. response.setMessage(e.getMessage());
  1145. }
  1146. return retVal;
  1147. }
  1148. //////////////////////////////////////////////////////////////////////////////////////////////
  1149. public List<CustomMapReduceJobPojo> getCustomTaskOrQuery(String jobtitle, ResponseObject response) {
  1150. List<CustomMapReduceJobPojo> retVal = null;
  1151. try {
  1152. StringBuilder url = new StringBuilder(apiRoot).append("custom/mapreduce/getjobs/");
  1153. if (null != jobtitle) {
  1154. url.append(jobtitle);
  1155. }
  1156. // (else get all)
  1157. String json = sendRequest(url.toString(), null);
  1158. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(json, ResponsePojo.class);
  1159. ResponseObject internal_ro = internal_responsePojo.getResponse();
  1160. response = shallowCopy(response, internal_ro);
  1161. if (response.isSuccess()) {
  1162. retVal = ApiManager.mapListFromApi((JsonElement)internal_responsePojo.getData(),
  1163. CustomMapReduceJobPojo.listType(), null);
  1164. }
  1165. }
  1166. catch (Exception e) {
  1167. response.setSuccess(false);
  1168. response.setMessage(e.getMessage());
  1169. }
  1170. return retVal;
  1171. }
  1172. //////////////////////////////////////////////////////////////////////////////////////////////
  1173. // And deletes, apply to either:
  1174. public boolean deleteCustomTaskOrQuery(String jobtitle, ResponseObject response) {
  1175. try {
  1176. StringBuilder url = new StringBuilder(apiRoot).append("custom/mapreduce/removejob/");
  1177. url.append(jobtitle);
  1178. String json = sendRequest(url.toString(), null);
  1179. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(json, ResponsePojo.class);
  1180. ResponseObject internal_ro = internal_responsePojo.getResponse();
  1181. response = shallowCopy(response, internal_ro);
  1182. }
  1183. catch (Exception e) {
  1184. response.setSuccess(false);
  1185. response.setMessage(e.getMessage());
  1186. }
  1187. return response.isSuccess();
  1188. }
  1189. public boolean deleteCustomTaskOrQuery(ObjectId taskId, ResponseObject response) {
  1190. return deleteCustomTaskOrQuery(taskId.toString(), response);
  1191. }
  1192. //TESTED
  1193. //////////////////////////////////////////////////////////////////////////////////////////////
  1194. //////////////////////////////////////////////////////////////////////////////////////////////
  1195. // ALIASES
  1196. // UPDATE, REMOVE, AND GET
  1197. // This is not super-efficient code
  1198. public Set<String> updateAliases(Collection<EntityFeaturePojo> aliasesToUpdate, String communityIdStr, boolean bUpsert, ResponseObject response) {
  1199. return updateAliases(aliasesToUpdate, communityIdStr, bUpsert, null, response);
  1200. }
  1201. public Set<String> removeAliases(Collection<String> aliasesToRemove, String communityIdStr, ResponseObject response) {
  1202. return removeAliases(aliasesToRemove, communityIdStr, null, response);
  1203. }
  1204. // (Only use this version if immediately called after getAliases since none of this is in any way atomic)
  1205. public Set<String> updateAliases(Collection<EntityFeaturePojo> aliasesToUpdate, String communityIdStr, boolean bUpsert, Map<String, List<SharePojo>> aliasMapping, ResponseObject response) {
  1206. if (null == aliasMapping) {
  1207. aliasMapping = new HashMap<String, List<SharePojo>>();
  1208. this.getAliases(communityIdStr, aliasMapping, response);
  1209. if (!response.isSuccess()) {
  1210. return null;
  1211. }
  1212. }//TESTED
  1213. Map<ObjectId, BasicDBObject> shareContentCache = new HashMap<ObjectId, BasicDBObject>();
  1214. List<SharePojo> sharesToUpdate = new LinkedList<SharePojo>();
  1215. // Step through the aliases, update the content
  1216. // Loop 1 update
  1217. SharePojo shareForNewAliases = null;
  1218. Set<String> erroredAliases = new HashSet<String>();
  1219. HashMultimap<ObjectId, String> shareToAliasMapping = HashMultimap.create();
  1220. for (EntityFeaturePojo alias: aliasesToUpdate) {
  1221. List<SharePojo> sharesForThisAlias = aliasMapping.get(alias.getIndex());
  1222. if ((null == sharesForThisAlias) && bUpsert) { // This is a new alias and not ignoring upserts
  1223. if (null == shareForNewAliases) { // Haven't yet assigned such a share
  1224. shareForNewAliases = this.upsertSharePrep(communityIdStr, shareContentCache, aliasMapping);
  1225. if (null == shareForNewAliases) {
  1226. erroredAliases.add(alias.getIndex());
  1227. continue;
  1228. }
  1229. sharesToUpdate.add(shareForNewAliases);
  1230. }
  1231. BasicDBObject shareContent = shareContentCache.get(shareForNewAliases.get_id()); // (exists by construction)
  1232. shareContent.put(alias.getIndex(), alias.toDb());
  1233. shareToAliasMapping.put(shareForNewAliases.get_id(), alias.getIndex());
  1234. }//TESTED
  1235. else if (null != sharesForThisAlias) {
  1236. for (SharePojo share: sharesForThisAlias) {
  1237. BasicDBObject shareContent = shareContentCache.get(share.get_id());
  1238. if (null == shareContent) {
  1239. try {
  1240. String json = share.getShare();
  1241. shareContent = (BasicDBObject) JSON.parse(json);
  1242. shareContentCache.put(share.get_id(), shareContent);
  1243. sharesToUpdate.add(share);
  1244. }
  1245. catch (Exception e) {
  1246. erroredAliases.add(alias.getIndex());
  1247. }
  1248. }//TESTED
  1249. shareContent.put(alias.getIndex(), alias.toDb());
  1250. shareToAliasMapping.put(share.get_id(), alias.getIndex());
  1251. }//TESTED
  1252. }
  1253. else {
  1254. erroredAliases.add(alias.getIndex());
  1255. }
  1256. // end loop over updating shares
  1257. }//end loop over aliases
  1258. // Loop 2 now update all the shares
  1259. boolean bSucceededUpdatingSomething = false;
  1260. for (SharePojo share: sharesToUpdate) {
  1261. BasicDBObject shareContent = shareContentCache.get(share.get_id()); // (exists by construction)
  1262. String shareIdStr = share.get_id().toString();
  1263. this.updateShareJSON(shareIdStr, share.getTitle(), share.getDescription(), "infinite-entity-alias", shareContent.toString(), response);
  1264. bSucceededUpdatingSomething |= response.isSuccess();
  1265. if (!response.isSuccess()) {
  1266. Set<String> failedAliases = shareToAliasMapping.get(share.get_id());
  1267. if (null != failedAliases) {
  1268. erroredAliases.addAll(failedAliases);
  1269. }
  1270. }
  1271. }//TESTED
  1272. response.setSuccess(bSucceededUpdatingSomething);
  1273. return erroredAliases;
  1274. }
  1275. // (Only use this version if immediately called after getAliases since none of this is in any way atomic)
  1276. public Set<String> removeAliases(Collection<String> aliasesToRemove, String communityIdStr, Map<String, List<SharePojo>> aliasMapping, ResponseObject response) {
  1277. if (null == aliasMapping) {
  1278. aliasMapping = new HashMap<String, List<SharePojo>>();
  1279. this.getAliases(communityIdStr, aliasMapping, response);
  1280. if (!response.isSuccess()) {
  1281. return null;
  1282. }
  1283. }//TESTED
  1284. Map<ObjectId, BasicDBObject> shareContentCache = new HashMap<ObjectId, BasicDBObject>();
  1285. List<SharePojo> sharesToUpdate = new LinkedList<SharePojo>();
  1286. // Step through the aliases, update the content
  1287. // Loop 1 update
  1288. Set<String> erroredAliases = new HashSet<String>();
  1289. HashMultimap<ObjectId, String> shareToAliasMapping = HashMultimap.create();
  1290. for (String alias: aliasesToRemove) {
  1291. List<SharePojo> sharesForThisAlias = aliasMapping.get(alias);
  1292. if (null != sharesForThisAlias) {
  1293. for (SharePojo share: sharesForThisAlias) {
  1294. BasicDBObject shareContent = shareContentCache.get(share.get_id());
  1295. if (null == shareContent) {
  1296. try {
  1297. String json = share.getShare();
  1298. shareContent = (BasicDBObject) JSON.parse(json);
  1299. shareContentCache.put(share.get_id(), shareContent);
  1300. sharesToUpdate.add(share);
  1301. }
  1302. catch (Exception e) {
  1303. erroredAliases.add(alias);
  1304. }
  1305. }//TESTED
  1306. shareContent.remove(alias);
  1307. shareToAliasMapping.put(share.get_id(), alias);
  1308. }//TESTED
  1309. }
  1310. // end loop over updating shares
  1311. }//end loop over aliases
  1312. // Loop 2 now update all the shares
  1313. boolean bSucceededUpdatingSomething = false;
  1314. for (SharePojo share: sharesToUpdate) {
  1315. BasicDBObject shareContent = shareContentCache.get(share.get_id()); // (exists by construction)
  1316. String shareIdStr = share.get_id().toString();
  1317. if (shareContent.isEmpty()) { // Remove the share
  1318. this.removeShare(shareIdStr, response);
  1319. if (!response.isSuccess()) {
  1320. Set<String> failedAliases = shareToAliasMapping.get(share.get_id());
  1321. if (null != failedAliases) {
  1322. erroredAliases.addAll(failedAliases);
  1323. }
  1324. }
  1325. }//TESTED
  1326. else {
  1327. this.updateShareJSON(shareIdStr, share.getTitle(), share.getDescription(), "infinite-entity-alias", shareContent.toString(), response);
  1328. bSucceededUpdatingSomething |= response.isSuccess();
  1329. if (!response.isSuccess()) {
  1330. Set<String> failedAliases = shareToAliasMapping.get(share.get_id());
  1331. if (null != failedAliases) {
  1332. erroredAliases.addAll(failedAliases);
  1333. }
  1334. }
  1335. }//TESTED
  1336. }//TESTED
  1337. response.setSuccess(bSucceededUpdatingSomething);
  1338. return erroredAliases;
  1339. }
  1340. // THIS IS BOTH PUBLIC AND A UTILITY FOR THE OTHER CALLS
  1341. public Map<String, EntityFeaturePojo> getAliases(String communityIdStr, ResponseObject response) {
  1342. return getAliases(communityIdStr, null, response);
  1343. }
  1344. public Map<String, EntityFeaturePojo> getAliases(String communityIdStr, Map<String, List<SharePojo>> aliasMapping, ResponseObject response) {
  1345. // Get the shares with the right type and community
  1346. List<SharePojo> shareList = this.searchShares("community", communityIdStr, "infinite-entity-alias", response);
  1347. if (!response.isSuccess()) {
  1348. return null;
  1349. }
  1350. // Generate a list
  1351. HashMap<String, EntityFeaturePojo> masterAliases = new HashMap<String, EntityFeaturePojo>();
  1352. if (null != shareList) {
  1353. for (SharePojo share: shareList) {
  1354. populateAliasTableFromShare(share, masterAliases, aliasMapping);
  1355. }
  1356. }
  1357. response.setSuccess(true);
  1358. return masterAliases;
  1359. }//TESTED
  1360. // ALIAS UTILITIES:
  1361. private SharePojo upsertSharePrep(String communityIdStr, Map<ObjectId, BasicDBObject> shareContentCache, Map<String, List<SharePojo>> aliasMapping) {
  1362. SharePojo shareForNewAliases = null;
  1363. BasicDBObject contentForNewAliases = null;
  1364. for (List<SharePojo> shares: aliasMapping.values()) {
  1365. if (!shares.isEmpty()) {
  1366. shareForNewAliases = shares.iterator().next();
  1367. try {
  1368. String json = shareForNewAliases.getShare();
  1369. contentForNewAliases = (BasicDBObject) JSON.parse(json);
  1370. shareContentCache.put(shareForNewAliases.get_id(), contentForNewAliases);
  1371. break;
  1372. }
  1373. catch (Exception e) {} // Try a different share
  1374. }
  1375. }//TESTED
  1376. if (null == shareForNewAliases) { // Didn't find one, so going to have to create something
  1377. EntityFeaturePojo discard = new EntityFeaturePojo();
  1378. discard.setDisambiguatedName("DISCARD");
  1379. discard.setType("SPECIAL");
  1380. discard.setIndex("DISCARD");
  1381. EntityFeaturePojo docDiscard = new EntityFeaturePojo();
  1382. docDiscard.setDisambiguatedName("DOCUMENT_DISCARD");
  1383. docDiscard.setType("SPECIAL");
  1384. docDiscard.setIndex("DOCUMENT_DISCARD");
  1385. contentForNewAliases = new BasicDBObject("DISCARD", discard.toDb());
  1386. contentForNewAliases.put("DOCUMENT_DISCARD", docDiscard);
  1387. ResponseObject response = new ResponseObject();
  1388. shareForNewAliases = this.addShareJSON("Alias Share: " + communityIdStr, "An alias share for a specific community", "infinite-entity-alias", "{}", response);
  1389. if ((null == shareForNewAliases) || !response.isSuccess()) {
  1390. return null;
  1391. }//TESTED
  1392. // Remove share from personal community
  1393. try {
  1394. ShareCommunityPojo currCommunity = shareForNewAliases.getCommunities().iterator().next();
  1395. String removeCommunityIdStr = currCommunity.get_id().toString();
  1396. if (!communityIdStr.equals(removeCommunityIdStr)) { // (obv not if this is my community somehow, don't think that's possible)
  1397. this.removeShareFromCommunity(shareForNewAliases.get_id().toString(), removeCommunityIdStr, response);
  1398. if (!response.isSuccess()) {
  1399. return null;
  1400. }
  1401. }
  1402. }
  1403. catch (Exception e) {} // do nothing I guess, not in any communities?
  1404. this.addShareToCommunity(shareForNewAliases.get_id().toString(), "aliasComm", communityIdStr, response);
  1405. if (!response.isSuccess()) {
  1406. return null;
  1407. }
  1408. }//TESTED
  1409. shareContentCache.put(shareForNewAliases.get_id(), contentForNewAliases);
  1410. return shareForNewAliases;
  1411. }//TESTED
  1412. // THIS IS A SUBSET OF com.ikanow.infinit.e.api.knowledge.aliases.AliasLookupTable
  1413. private void populateAliasTableFromShare(SharePojo share, HashMap<String, EntityFeaturePojo> masterAliases, Map<String, List<SharePojo>> aliasMapping) {
  1414. String json = share.getShare();
  1415. if (null != json) {
  1416. try {
  1417. DBObject dbo = (DBObject) JSON.parse(json);
  1418. if (null != dbo) {
  1419. for (Object entryObj: dbo.toMap().entrySet()) {
  1420. @SuppressWarnings("unchecked")
  1421. Map.Entry<String, Object> entry = (Map.Entry<String, Object>)entryObj;
  1422. String masterAlias = entry.getKey();
  1423. BasicDBObject entityFeatureObj = (BasicDBObject) entry.getValue();
  1424. EntityFeaturePojo aliasInfo = null;
  1425. try {
  1426. aliasInfo = EntityFeaturePojo.fromDb(entityFeatureObj, EntityFeaturePojo.class);
  1427. }
  1428. catch (Exception e) {
  1429. continue;
  1430. }
  1431. if (null == aliasInfo.getIndex()) {
  1432. aliasInfo.setIndex(masterAlias);
  1433. }
  1434. if (null != aliasInfo) { // (allow getAlias to be null/empty)
  1435. //(overwrite duplicates)
  1436. masterAliases.put(aliasInfo.getIndex(), aliasInfo);
  1437. if (null != aliasMapping) {
  1438. List<SharePojo> shareList = aliasMapping.get(aliasInfo.getIndex());
  1439. if (null == shareList) {
  1440. shareList = new LinkedList<SharePojo>();
  1441. aliasMapping.put(aliasInfo.getIndex(), shareList);
  1442. }
  1443. shareList.add(share);
  1444. }
  1445. }
  1446. }
  1447. }
  1448. }
  1449. catch (Exception e) {
  1450. } // not Json, just carry on...
  1451. }
  1452. }//TESTED
  1453. public DimensionListPojo getEntitySuggest(String searchterm, String communityIdStr, boolean includeGeo, boolean includeLinkData, ResponseObject response)
  1454. {
  1455. try
  1456. {
  1457. StringBuilder url = new StringBuilder(apiRoot).append("knowledge/feature/entitySuggest/");
  1458. url.append(URLEncoder.encode(searchterm,"UTF-8"));
  1459. url.append("/");
  1460. url.append(URLEncoder.encode(communityIdStr,"UTF-8"));
  1461. String json = sendRequest(url.toString(), null);
  1462. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(json, ResponsePojo.class);
  1463. ResponseObject internal_ro = internal_responsePojo.getResponse();
  1464. response = shallowCopy(response, internal_ro);
  1465. return new Gson().fromJson((JsonElement)internal_responsePojo.getData(), DimensionListPojo.class);
  1466. }
  1467. catch (Exception e)
  1468. {
  1469. response.setSuccess(false);
  1470. response.setMessage(e.getMessage());
  1471. }
  1472. return null;
  1473. }
  1474. public List<SearchSuggestPojo> getGeoSuggest(Double latitude, Double longitude, String communityIdStr, ResponseObject response)
  1475. {
  1476. List<SearchSuggestPojo> locations = null;
  1477. try
  1478. {
  1479. String searchterm = latitude + "," + longitude;
  1480. StringBuilder url = new StringBuilder(apiRoot).append("knowledge/feature/geoSuggest/");
  1481. url.append(URLEncoder.encode(searchterm,"UTF-8"));
  1482. url.append("/");
  1483. url.append(URLEncoder.encode(communityIdStr,"UTF-8"));
  1484. String json = sendRequest(url.toString(), null);
  1485. ResponsePojo internal_responsePojo = ResponsePojo.fromApi(json, ResponsePojo.class);
  1486. ResponseObject internal_ro = internal_responsePojo.getResponse();
  1487. response = shallowCopy(response, internal_ro);
  1488. locations = ApiManager.mapListFromApi((JsonElement)internal_responsePojo.getData(), SearchSuggestPojo.listType(), null);
  1489. }
  1490. catch (Exception e)
  1491. {
  1492. response.setSuccess(false);
  1493. response.setMessage(e.getMessage());
  1494. }
  1495. return locations;
  1496. }
  1497. //////////////////////////////////////////////////////////////////////////////////////////////
  1498. // UTILITY
  1499. public boolean hasSourceHarvested(String sourceId)
  1500. {
  1501. ResponseObject ro = new ResponseObject();
  1502. return hasSourceHarvested(getSource(sourceId, ro));
  1503. }
  1504. public boolean hasSourceHarvested(SourcePojo source)
  1505. {
  1506. if ( source != null )
  1507. {
  1508. if ( source.getHarvestStatus() != null && source.getHarvestStatus().getHarvested() != null )
  1509. {
  1510. if ( source.getHarvestStatus().getHarvest_status() == HarvestEnum.in_progress && source.getHarvestStatus().getDoccount() != null && source.getHarvestStatus().getDoccount() > 0)
  1511. {
  1512. //if the source is in progress but has a doc count, it has already completed once
  1513. return true;
  1514. }
  1515. else if ( source.getHarvestStatus().getHarvested() != null )
  1516. {
  1517. //if the source is not in progress but has a harvested date, it has completed atleast once
  1518. return true;
  1519. }
  1520. }
  1521. }
  1522. return false;
  1523. }
  1524. public boolean isAdmin()
  1525. {
  1526. return this.sendKeepalive(true);
  1527. }
  1528. ///////// Request Calls
  1529. public String sendRequest(String urlAddress, String postData)
  1530. {
  1531. try {
  1532. if (postData == null)
  1533. return sendGetRequest(urlAddress);
  1534. else
  1535. return sendPostRequest(urlAddress, postData);
  1536. } catch (Exception e) {
  1537. e.printStackTrace();
  1538. return "";
  1539. }
  1540. }
  1541. private String sendPostRequest(String urlAddress, String data) throws MalformedURLException, IOException
  1542. {
  1543. return sendPostRequest(urlAddress, data, 0);
  1544. }
  1545. private String sendPostRequest(String urlAddress, String data, int redirects) throws MalformedURLException, IOException
  1546. {
  1547. String result = "";
  1548. if (urlAddress.startsWith("https:")) {
  1549. TrustManagerManipulator.allowAllSSL();
  1550. }
  1551. URLConnection urlConnection = new URL(urlAddress).openConnection();
  1552. if ( cookie != null )
  1553. urlConnection.setRequestProperty("Cookie", cookie);
  1554. if ( apiKey != null )
  1555. urlConnection.setRequestProperty("Cookie", apiKey);
  1556. urlConnection.setDoOutput(true);
  1557. urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
  1558. ((HttpURLConnection)urlConnection).setRequestMethod("POST");
  1559. // Post JSON string to URL
  1560. OutputStream os = urlConnection.getOutputStream();
  1561. byte[] b = data.getBytes("UTF-8");
  1562. os.write(b);
  1563. int status = ((HttpURLConnection)urlConnection).getResponseCode();
  1564. // normally, 3xx is redirect
  1565. if (status != HttpURLConnection.HTTP_OK)
  1566. {
  1567. if (status == HttpURLConnection.HTTP_MOVED_TEMP
  1568. || status == HttpURLConnection.HTTP_MOVED_PERM
  1569. || status == HttpURLConnection.HTTP_SEE_OTHER)
  1570. {
  1571. if (redirects <= 5) {
  1572. String newUrlAddress = ((HttpURLConnection)urlConnection).getHeaderField("Location");
  1573. if (null != newUrlAddress) {
  1574. return sendPostRequest(newUrlAddress, data, redirects + 1);
  1575. }
  1576. }
  1577. //(else carry on, will exception out or something below)
  1578. }
  1579. }//TESTED
  1580. // Receive results back from API
  1581. InputStream inStream = urlConnection.getInputStream();
  1582. result = IOUtils.toString(inStream, "UTF-8");
  1583. inStream.close();
  1584. //save cookie if cookie is null
  1585. if ( cookie == null )
  1586. {
  1587. String headername;
  1588. for ( int i = 1; (headername = urlConnection.getHeaderFieldKey(i)) != null; i++ )
  1589. {
  1590. if ( headername.equals("Set-Cookie") )
  1591. {
  1592. cookie = urlConnection.getHeaderField(i);
  1593. break;
  1594. }
  1595. }
  1596. }
  1597. return result;
  1598. }
  1599. public String sendGetRequest(String urlAddress) throws Exception
  1600. {
  1601. return sendGetRequest(urlAddress, 0);
  1602. }
  1603. public String sendGetRequest(String urlAddress, int redirects) throws Exception
  1604. {
  1605. if (urlAddress.startsWith("https:")) {
  1606. TrustManagerManipulator.allowAllSSL();
  1607. }
  1608. URL url = new URL(urlAddress);
  1609. URLConnection urlConnection = url.openConnection();
  1610. if ( cookie != null )
  1611. urlConnection.setRequestProperty("Cookie", cookie);
  1612. if ( apiKey != null )
  1613. urlConnection.setRequestProperty("Cookie", apiKey);
  1614. ((HttpURLConnection)urlConnection).setRequestMethod("GET");
  1615. int status = ((HttpURLConnection)urlConnection).getResponseCode();
  1616. // normally, 3xx is redirect
  1617. if (status != HttpURLConnection.HTTP_OK)
  1618. {
  1619. if (status == HttpURLConnection.HTTP_MOVED_TEMP
  1620. || status == HttpURLConnection.HTTP_MOVED_PERM
  1621. || status == HttpURLConnection.HTTP_SEE_OTHER)
  1622. {
  1623. if (redirects <= 5) {
  1624. String newUrlAddress = ((HttpURLConnection)urlConnection).getHeaderField("Location");
  1625. if (null != newUrlAddress) {
  1626. return sendGetRequest(newUrlAddress, redirects + 1);
  1627. }
  1628. }
  1629. //(else carry on, will exception out or something below)
  1630. }
  1631. }//TESTED
  1632. //read back result
  1633. BufferedReader inStream = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
  1634. StringBuilder strBuilder = new StringBuilder();
  1635. String buffer;
  1636. while ( (buffer = inStream.readLine()) != null )
  1637. {
  1638. strBuilder.append(buffer);
  1639. }
  1640. inStream.close();
  1641. //save cookie if cookie is null
  1642. if ( cookie == null )
  1643. {
  1644. String headername;
  1645. for ( int i = 1; (headername = urlConnection.getHeaderFieldKey(i)) != null; i++ )
  1646. {
  1647. if ( headername.equals("Set-Cookie") )
  1648. {
  1649. cookie = urlConnection.getHeaderField(i);
  1650. break;
  1651. }
  1652. }
  1653. }
  1654. return strBuilder.toString();
  1655. }
  1656. ///////////Password Encryption
  1657. public String encryptEncodePassword(String pword) throws UnsupportedEncodingException, NoSuchAlgorithmException
  1658. {
  1659. return URLEncoder.encode(encryptWithoutEncode(pword), "UTF-8");
  1660. }
  1661. public static String encryptWithoutEncode(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException
  1662. {
  1663. MessageDigest md = MessageDigest.getInstance("SHA-256");
  1664. md.update(password.getBytes("UTF-8"));
  1665. return new String(Base64.encodeBase64(md.digest()));
  1666. }
  1667. //////////Shallow Copy Response Object
  1668. private ResponseObject shallowCopy(ResponseObject toCopy, ResponseObject fromCopy)
  1669. {
  1670. toCopy.setAction(fromCopy.getAction());
  1671. toCopy.setMessage(fromCopy.getMessage());
  1672. toCopy.setSuccess(fromCopy.isSuccess());
  1673. toCopy.setTime(fromCopy.getTime());
  1674. return fromCopy;
  1675. }
  1676. ///////////////////////////////////////////////////////////////////////
  1677. ///////////////////////////////////////////////////////////////////////
  1678. // Start of some test code
  1679. // Run standalone RESTlet API on 8184 pointing to the right place
  1680. // Invoke with username and password
  1681. public static void main(String[] args) {
  1682. if (args.length < 2) {
  1683. System.out.println("*** CALL WITH username password as args");
  1684. System.exit(-1);
  1685. }
  1686. InfiniteDriver.setDefaultApiRoot("http://localhost:8184/");
  1687. InfiniteDriver infDriver = new InfiniteDriver();
  1688. ResponseObject responseObject = new ResponseObject();
  1689. infDriver.login(args[0], args[1], responseObject);
  1690. System.out.println("DRIVER LOGIN = " + responseObject.isSuccess() + " : " + responseObject.getMessage());
  1691. List<PersonPojo> people = infDriver.listPerson(responseObject);
  1692. System.out.println("DRIVER LIST PEOPLE = " + responseObject.isSuccess() + " : " + responseObject.getMessage());
  1693. if (null != people) {
  1694. System.out.println("FOUND " + people.size());
  1695. if (people.size() > 0) {
  1696. System.out.println("EXAMPLE " + people.iterator().next().toDb());
  1697. }
  1698. }
  1699. }
  1700. }