Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.kristall.bgbilling.webservice;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.ArrayList;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import org.json.*;
- import bitel.billing.server.contract.bean.ContractTariffManager;
- import ru.bitel.bgbilling.common.BGException;
- import ru.bitel.bgbilling.kernel.tariff.option.common.bean.ContractTariffOption;
- import ru.bitel.bgbilling.kernel.tariff.option.server.bean.ContractTariffOptionDao;
- import ru.bitel.bgbilling.plugins.crm.common.model.RegisterTask;
- import ru.bitel.bgbilling.plugins.crm.server.dao.RegisterTaskManager;
- import ru.kristall.bgbilling.kernel.GC;
- /**
- * Класс для взаимодействия с REST API Форпост:
- * <ul>
- * <li>Таблица cvr_forpost_request заявки на подключения, еще не подтвержденные;</li>
- * <li>Таблица cvr_forpost привязка контракта из таблицы contract к аккаунтам в БД Форпост, уже подтвержденные;</li>
- * <li>Таблица cvr_forpost_login привязка аккаунта к логинам, необходим для обсчета доп.логинов;</li>
- * </ul>
- * @author aukhatov
- *
- */
- public class ForpostAPI {
- /**
- * Адрес сервера Форпост (REST API URL)
- */
- private static String stringURL = "http://172.20.0.5/system-api/";
- private static String user = "billing";
- private static String password = "dtk110111";
- private static String auth = "AdminLogin=" + user + "&AdminPassword=" + password;
- /**
- * Аккаунт активен
- */
- public static final int ACCOUNT_STATUS_ACTIVE = 1;
- /**
- * Аккаунт отключен
- */
- public static final int ACCOUNT_STATUS_CLOSED = 0;
- public static String sendGET() throws IOException {
- URL obj = new URL(stringURL);
- HttpURLConnection con = (HttpURLConnection) obj.openConnection();
- con.setRequestProperty("User-Agent", "Mozilla/5.0");
- int responseCode = con.getResponseCode();
- System.out.println("GET Response Code :: " + responseCode);
- if (responseCode == HttpURLConnection.HTTP_OK) {
- }
- return null;
- }
- /**
- * Отправить POST-запрос
- * @param method REST-метод
- * @param params Параметры метода
- * @return JSON-ответ
- * @throws IOException
- * @throws JSONException
- */
- public static JSONObject sendPost(String method, String params) throws IOException, JSONException {
- URL obj = new URL(stringURL + method);
- HttpURLConnection con = (HttpURLConnection) obj.openConnection();
- con.setDoOutput(true);
- OutputStream os = con.getOutputStream();
- params = auth + "&" + params;
- os.write(params.getBytes());
- os.flush();
- os.close();
- int responseCode = con.getResponseCode();
- System.out.println("POST Response Code :: " + responseCode);
- if (responseCode == HttpURLConnection.HTTP_OK) { //success
- BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
- String inputLine;
- StringBuffer response = new StringBuffer();
- while ((inputLine = in.readLine()) != null) {
- response.append(inputLine);
- }
- in.close();
- String jsonString = response.toString();
- if (!method.equals("EditAccount"))
- jsonString = jsonString.substring(1, jsonString.length() - 1);
- JSONObject json = new JSONObject(jsonString);
- System.out.println(json);
- return json;
- } else {
- System.out.println("POST request not worked");
- return null;
- }
- }
- public static JSONObject getCameras(int accountId) {
- JSONObject result = null;
- try {
- result = sendPost("GetCameras", "AccountID=" + accountId);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return result;
- }
- public static JSONObject addAccount(String contractTitle, String password) {
- JSONObject result = null;
- long day7 = 604800;
- try {
- result = sendPost("AddAccount", "IsActive=0&Quota=" + day7 + "&MaxCameraOnlineTranslationCount=1&"
- + "MaxCameraArchivalTranslationCount=1&MaxCameraUserOnlineTranslationCount&"
- + "MaxCameraUserArchivalTranslationCount=1&CanChangeOwnInfo=0&MaxLoginCount=2&"
- + "ContractNumber=" + contractTitle + "&Password=" + password + "&Login=" + contractTitle);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return result;
- }
- public static JSONObject addLogin(String accountId, String login, String password, String email, String fio) {
- JSONObject result = null;
- try {
- result = sendPost("AddUser","AccountID=" + accountId + "&Login=" + login
- + "&Password=" + password + "&Email=" + email + "&FIO=" + fio);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return result;
- }
- public static JSONObject getObjects(int accountId) {
- JSONObject result = null;
- try {
- result = sendPost("GetObjects", "AccountID=" + accountId);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return result;
- }
- /**
- * Изменение статуса аккаунта в форпост
- * Необходим для активации аккаунта по оплате, и обратном
- * случае для блокирования
- * @param accountId идентификатор аккаунта
- * @param status 1-Активен, 0-Заблокирован
- * @return JSON-ответ
- */
- public static JSONObject changeStatus(int accountId, int status) {
- JSONObject result = null;
- try {
- result = sendPost("EditAccount", "ID=" + accountId + "&IsActive=" + status);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return result;
- }
- /**
- * Проверка активной опции на контракте
- * @param cid код договора
- * @param optionId Проверяемая опция
- * @param con
- * @return true-если опция активна, false-опция не активна
- */
- public static boolean checkTariffOption(int cid, int optionId, Connection con) {
- boolean status = false;
- ContractTariffOptionDao cto = new ContractTariffOptionDao(con);
- try {
- List <ContractTariffOption> optionList = cto.list(cid, new Date());
- if (optionList.size() > 0) {
- Iterator<ContractTariffOption> it = optionList.iterator();
- while (it.hasNext()) {
- /**
- * Бежим по всем опциям на контракте
- */
- ContractTariffOption tariffOption = (ContractTariffOption) it.next();
- if (tariffOption.getOptionId() == optionId) {
- status = true;
- }
- }
- } else {
- /**
- * Нет активной тарифной опции
- */
- status = false;
- }
- } catch (BGException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return status;
- }
- /**
- * Получение активных контрактов с привязкой к аккаунту форпоста
- * @param con
- * @return вернет HashMap < contractId, accountId >
- */
- public static HashMap<Integer, Integer> getContractAccount(Connection con) {
- HashMap<Integer, Integer> contractAccountMap = new HashMap<Integer, Integer>();
- 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";
- try {
- Statement st = con.createStatement();
- ResultSet rst = st.executeQuery(SQL_SELECT);
- while (rst.next()) {
- contractAccountMap.put(rst.getInt("id"), rst.getInt("account_id"));
- }
- st.close();
- rst.close();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return contractAccountMap;
- }
- /**
- * Создать заявку с типом "ФорпостВидеонаблюдение подключение"
- * На группу Отдел СПД
- * @param contractId На контракт
- * @param con
- */
- public static void createRegisterTask(int contractId, Connection con) {
- //на группу
- int groupId = 2;
- //тип задачи
- int type = 68;
- //исполнители
- List<Integer> executors = new ArrayList<Integer>();
- executors.add(1);
- RegisterTaskManager rtm = new RegisterTaskManager(con);
- RegisterTask task = new RegisterTask();
- task.setContractId(contractId);
- task.setId(0);
- task.setStatus(RegisterTask.STATUS_OPEN);
- task.setOpenTime(new Date());
- task.setOpenUserId(GC.SERVER);
- task.setGroupId(groupId);
- task.setExecutors(executors);
- task.setTypeId(type);
- task.setComment("Подключение видеонаблюдения. Аккаунт подтвержден.");
- task.setAddressParamId(1);
- rtm.updateTask(task, GC.SERVER);
- return;
- }
- /**
- * Получить аккаунт по cid
- * @param cid
- * @param con
- * @return
- */
- public static int getAccount(int cid, Connection con) {
- int accountId = 0;
- String SQL_FROM = "SELECT account_id FROM cvr_forpost WHERE cid=?";
- try {
- PreparedStatement ps = con.prepareStatement(SQL_FROM);
- ps.setInt(1, cid);
- ResultSet rst = ps.executeQuery();
- while (rst.next()) {
- accountId = rst.getInt("account_id");
- }
- ps.close();
- rst.close();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return accountId;
- }
- /**
- * Получить тарифную опцию, по коду договора
- * @param cid код договора
- * @param con коннекшэн к БД
- * @return идентификатор опции (optionId)
- */
- public static int getTariffOption(int cid, Connection con) {
- int optionId = 0;
- ContractTariffManager ctm = new ContractTariffManager(con);
- int tpid = ctm.getContractTariff(cid, Calendar.getInstance()).getTariffPlanId();
- List<Integer> optionList = TariffOptionManager.getTariffOptionList(tpid, con);
- Iterator<Integer> it = optionList.iterator();
- while (it.hasNext()) {
- optionId = (Integer) it.next();
- }
- return optionId;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement