Advertisement
Guest User

Untitled

a guest
Jul 12th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.14 KB | None | 0 0
  1. package ru.kristall.bgbilling.webservice;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStream;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9. import java.sql.Connection;
  10. import java.sql.PreparedStatement;
  11. import java.sql.ResultSet;
  12. import java.sql.SQLException;
  13. import java.sql.Statement;
  14. import java.util.ArrayList;
  15. import java.util.Calendar;
  16. import java.util.Date;
  17. import java.util.HashMap;
  18. import java.util.Iterator;
  19. import java.util.List;
  20.  
  21. import org.json.*;
  22.  
  23. import bitel.billing.server.contract.bean.ContractTariffManager;
  24. import ru.bitel.bgbilling.common.BGException;
  25. import ru.bitel.bgbilling.kernel.tariff.option.common.bean.ContractTariffOption;
  26. import ru.bitel.bgbilling.kernel.tariff.option.server.bean.ContractTariffOptionDao;
  27. import ru.bitel.bgbilling.plugins.crm.common.model.RegisterTask;
  28. import ru.bitel.bgbilling.plugins.crm.server.dao.RegisterTaskManager;
  29. import ru.kristall.bgbilling.kernel.GC;
  30. /**
  31. * Класс для взаимодействия с REST API Форпост:
  32. * <ul>
  33. * <li>Таблица cvr_forpost_request заявки на подключения, еще не подтвержденные;</li>
  34. * <li>Таблица cvr_forpost привязка контракта из таблицы contract к аккаунтам в БД Форпост, уже подтвержденные;</li>
  35. * <li>Таблица cvr_forpost_login привязка аккаунта к логинам, необходим для обсчета доп.логинов;</li>
  36. * </ul>
  37. * @author aukhatov
  38. *
  39. */
  40. public class ForpostAPI {
  41.  
  42. /**
  43. * Адрес сервера Форпост (REST API URL)
  44. */
  45. private static String stringURL = "http://172.20.0.5/system-api/";
  46. private static String user = "billing";
  47. private static String password = "dtk110111";
  48. private static String auth = "AdminLogin=" + user + "&AdminPassword=" + password;
  49. /**
  50. * Аккаунт активен
  51. */
  52. public static final int ACCOUNT_STATUS_ACTIVE = 1;
  53. /**
  54. * Аккаунт отключен
  55. */
  56. public static final int ACCOUNT_STATUS_CLOSED = 0;
  57.  
  58.  
  59. public static String sendGET() throws IOException {
  60. URL obj = new URL(stringURL);
  61. HttpURLConnection con = (HttpURLConnection) obj.openConnection();
  62. con.setRequestProperty("User-Agent", "Mozilla/5.0");
  63. int responseCode = con.getResponseCode();
  64. System.out.println("GET Response Code :: " + responseCode);
  65. if (responseCode == HttpURLConnection.HTTP_OK) {
  66.  
  67. }
  68. return null;
  69. }
  70. /**
  71. * Отправить POST-запрос
  72. * @param method REST-метод
  73. * @param params Параметры метода
  74. * @return JSON-ответ
  75. * @throws IOException
  76. * @throws JSONException
  77. */
  78. public static JSONObject sendPost(String method, String params) throws IOException, JSONException {
  79. URL obj = new URL(stringURL + method);
  80. HttpURLConnection con = (HttpURLConnection) obj.openConnection();
  81. con.setDoOutput(true);
  82. OutputStream os = con.getOutputStream();
  83. params = auth + "&" + params;
  84. os.write(params.getBytes());
  85. os.flush();
  86. os.close();
  87. int responseCode = con.getResponseCode();
  88. System.out.println("POST Response Code :: " + responseCode);
  89.  
  90. if (responseCode == HttpURLConnection.HTTP_OK) { //success
  91. BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  92. String inputLine;
  93. StringBuffer response = new StringBuffer();
  94.  
  95. while ((inputLine = in.readLine()) != null) {
  96. response.append(inputLine);
  97. }
  98. in.close();
  99. String jsonString = response.toString();
  100. if (!method.equals("EditAccount"))
  101. jsonString = jsonString.substring(1, jsonString.length() - 1);
  102. JSONObject json = new JSONObject(jsonString);
  103. System.out.println(json);
  104. return json;
  105. } else {
  106. System.out.println("POST request not worked");
  107. return null;
  108. }
  109. }
  110.  
  111. public static JSONObject getCameras(int accountId) {
  112. JSONObject result = null;
  113. try {
  114. result = sendPost("GetCameras", "AccountID=" + accountId);
  115.  
  116. } catch (IOException e) {
  117. // TODO Auto-generated catch block
  118. e.printStackTrace();
  119. } catch (JSONException e) {
  120. // TODO Auto-generated catch block
  121. e.printStackTrace();
  122. }
  123. return result;
  124. }
  125.  
  126. public static JSONObject addAccount(String contractTitle, String password) {
  127. JSONObject result = null;
  128. long day7 = 604800;
  129. try {
  130. result = sendPost("AddAccount", "IsActive=0&Quota=" + day7 + "&MaxCameraOnlineTranslationCount=1&"
  131. + "MaxCameraArchivalTranslationCount=1&MaxCameraUserOnlineTranslationCount&"
  132. + "MaxCameraUserArchivalTranslationCount=1&CanChangeOwnInfo=0&MaxLoginCount=2&"
  133. + "ContractNumber=" + contractTitle + "&Password=" + password + "&Login=" + contractTitle);
  134. } catch (IOException e) {
  135. // TODO Auto-generated catch block
  136. e.printStackTrace();
  137. } catch (JSONException e) {
  138. // TODO Auto-generated catch block
  139. e.printStackTrace();
  140. }
  141. return result;
  142. }
  143.  
  144. public static JSONObject addLogin(String accountId, String login, String password, String email, String fio) {
  145. JSONObject result = null;
  146. try {
  147. result = sendPost("AddUser","AccountID=" + accountId + "&Login=" + login
  148. + "&Password=" + password + "&Email=" + email + "&FIO=" + fio);
  149. } catch (IOException e) {
  150. // TODO Auto-generated catch block
  151. e.printStackTrace();
  152. } catch (JSONException e) {
  153. // TODO Auto-generated catch block
  154. e.printStackTrace();
  155. }
  156. return result;
  157. }
  158. public static JSONObject getObjects(int accountId) {
  159. JSONObject result = null;
  160. try {
  161. result = sendPost("GetObjects", "AccountID=" + accountId);
  162.  
  163. } catch (IOException e) {
  164. // TODO Auto-generated catch block
  165. e.printStackTrace();
  166. } catch (JSONException e) {
  167. // TODO Auto-generated catch block
  168. e.printStackTrace();
  169. }
  170. return result;
  171. }
  172.  
  173. /**
  174. * Изменение статуса аккаунта в форпост
  175. * Необходим для активации аккаунта по оплате, и обратном
  176. * случае для блокирования
  177. * @param accountId идентификатор аккаунта
  178. * @param status 1-Активен, 0-Заблокирован
  179. * @return JSON-ответ
  180. */
  181. public static JSONObject changeStatus(int accountId, int status) {
  182. JSONObject result = null;
  183. try {
  184. result = sendPost("EditAccount", "ID=" + accountId + "&IsActive=" + status);
  185.  
  186. } catch (IOException e) {
  187. // TODO Auto-generated catch block
  188. e.printStackTrace();
  189. } catch (JSONException e) {
  190. // TODO Auto-generated catch block
  191. e.printStackTrace();
  192. }
  193. return result;
  194. }
  195. /**
  196. * Проверка активной опции на контракте
  197. * @param cid код договора
  198. * @param optionId Проверяемая опция
  199. * @param con
  200. * @return true-если опция активна, false-опция не активна
  201. */
  202. public static boolean checkTariffOption(int cid, int optionId, Connection con) {
  203. boolean status = false;
  204. ContractTariffOptionDao cto = new ContractTariffOptionDao(con);
  205. try {
  206. List <ContractTariffOption> optionList = cto.list(cid, new Date());
  207. if (optionList.size() > 0) {
  208. Iterator<ContractTariffOption> it = optionList.iterator();
  209. while (it.hasNext()) {
  210. /**
  211. * Бежим по всем опциям на контракте
  212. */
  213. ContractTariffOption tariffOption = (ContractTariffOption) it.next();
  214. if (tariffOption.getOptionId() == optionId) {
  215. status = true;
  216. }
  217. }
  218. } else {
  219. /**
  220. * Нет активной тарифной опции
  221. */
  222. status = false;
  223. }
  224. } catch (BGException e) {
  225. // TODO Auto-generated catch block
  226. e.printStackTrace();
  227. }
  228. return status;
  229. }
  230. /**
  231. * Получение активных контрактов с привязкой к аккаунту форпоста
  232. * @param con
  233. * @return вернет HashMap < contractId, accountId >
  234. */
  235. public static HashMap<Integer, Integer> getContractAccount(Connection con) {
  236. HashMap<Integer, Integer> contractAccountMap = new HashMap<Integer, Integer>();
  237. String SQL_SELECT = "SELECT c.id, f.account_id FROM contract c JOIN cvr_forpost f ON c.id=f.cid WHERE c.status=0";
  238. try {
  239. Statement st = con.createStatement();
  240. ResultSet rst = st.executeQuery(SQL_SELECT);
  241. while (rst.next()) {
  242. contractAccountMap.put(rst.getInt("id"), rst.getInt("account_id"));
  243. }
  244. st.close();
  245. rst.close();
  246. } catch (SQLException e) {
  247. // TODO Auto-generated catch block
  248. e.printStackTrace();
  249. }
  250.  
  251. return contractAccountMap;
  252. }
  253. /**
  254. * Создать заявку с типом "ФорпостВидеонаблюдение подключение"
  255. * На группу Отдел СПД
  256. * @param contractId На контракт
  257. * @param con
  258. */
  259. public static void createRegisterTask(int contractId, Connection con) {
  260. //на группу
  261. int groupId = 2;
  262. //тип задачи
  263. int type = 68;
  264. //исполнители
  265. List<Integer> executors = new ArrayList<Integer>();
  266. executors.add(1);
  267. RegisterTaskManager rtm = new RegisterTaskManager(con);
  268. RegisterTask task = new RegisterTask();
  269. task.setContractId(contractId);
  270. task.setId(0);
  271. task.setStatus(RegisterTask.STATUS_OPEN);
  272. task.setOpenTime(new Date());
  273. task.setOpenUserId(GC.SERVER);
  274. task.setGroupId(groupId);
  275. task.setExecutors(executors);
  276. task.setTypeId(type);
  277. task.setComment("Подключение видеонаблюдения. Аккаунт подтвержден.");
  278. task.setAddressParamId(1);
  279. rtm.updateTask(task, GC.SERVER);
  280. return;
  281. }
  282. /**
  283. * Получить аккаунт по cid
  284. * @param cid
  285. * @param con
  286. * @return
  287. */
  288. public static int getAccount(int cid, Connection con) {
  289. int accountId = 0;
  290. String SQL_FROM = "SELECT account_id FROM cvr_forpost WHERE cid=?";
  291. try {
  292. PreparedStatement ps = con.prepareStatement(SQL_FROM);
  293. ps.setInt(1, cid);
  294. ResultSet rst = ps.executeQuery();
  295. while (rst.next()) {
  296. accountId = rst.getInt("account_id");
  297. }
  298. ps.close();
  299. rst.close();
  300. } catch (SQLException e) {
  301. // TODO Auto-generated catch block
  302. e.printStackTrace();
  303. }
  304.  
  305. return accountId;
  306. }
  307.  
  308. /**
  309. * Получить тарифную опцию, по коду договора
  310. * @param cid код договора
  311. * @param con коннекшэн к БД
  312. * @return идентификатор опции (optionId)
  313. */
  314. public static int getTariffOption(int cid, Connection con) {
  315. int optionId = 0;
  316. ContractTariffManager ctm = new ContractTariffManager(con);
  317. int tpid = ctm.getContractTariff(cid, Calendar.getInstance()).getTariffPlanId();
  318. List<Integer> optionList = TariffOptionManager.getTariffOptionList(tpid, con);
  319. Iterator<Integer> it = optionList.iterator();
  320. while (it.hasNext()) {
  321. optionId = (Integer) it.next();
  322. }
  323. return optionId;
  324. }
  325. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement