Commit 8f65b395 by Samir Sadykhov

сервис проверки документа

parent 7d78f0b9
*.iml
build
.idea
.gradle
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id="documentServices" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.gradle" />
<excludeFolder url="file://$MODULE_DIR$/build" />
<excludeFolder url="file://$MODULE_DIR$/out" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="sonarModuleSettings">
<option name="localAnalysisScripName" value="&lt;PROJECT&gt;" />
<option name="serverName" value="&lt;PROJECT&gt;" />
</component>
</module>
\ No newline at end of file
rootProject.name = 'documentServices'
package kz.arta.documentServices.listeners;
import kz.arta.documentServices.util.ConnectionPool;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.naming.NamingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
@MessageDriven(name = "DocflowDocument", activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "java:jboss/queues/Synergy/DocflowDocument"),
@ActivationConfigProperty(propertyName = "reconnectAttempts", propertyValue = "32"),
@ActivationConfigProperty(propertyName = "reconnectInterval", propertyValue = "4000"),
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge") })
public class DocflowDocumentListener implements MessageListener {
private static final Logger LOGGER = LoggerFactory.getLogger(DocflowDocumentListener.class);
public static final String EVENT_DOC_OPEN = "event.docflow.document.opened";
public static final String EVENT_DOC_CLOSE = "event.docflow.document.closed";
@javax.annotation.Resource
private javax.ejb.MessageDrivenContext mdc;
@Override
public void onMessage(Message message) {
try {
String eventType = message.getStringProperty("api_event");
String userID = message.getStringProperty("userId");
String documentID = message.getStringProperty("documentId");
if(documentID == null) {
ObjectMapper mapper = new ObjectMapper();
String json = message.getBody(String.class);
Map<String, String> prop = mapper.readValue(json, Map.class);
userID = prop.get("userId");
documentID = prop.get("documentId");
eventType = prop.get("api_event");
}
HashMap<String, String> info = getDocumentInfo(documentID);
String dataUUID = info.get("dataUUID");
if(null != eventType) {
LOGGER.info("************************************");
LOGGER.info("api_event: " + eventType);
LOGGER.info("documentID: " + documentID);
LOGGER.info("userID: " + userID);
HashMap<String, String> openInfo = checkOpenDocument(documentID);
LOGGER.info("[:: checkOpenDocument ::] " + openInfo);
if(userID != null) {
if(EVENT_DOC_OPEN.equalsIgnoreCase(eventType)) {
if(openInfo.get("dataUUID") == null) {
addRow(documentID, dataUUID, userID);
LOGGER.info("добавляем запись в таблицу");
}
}
if(EVENT_DOC_CLOSE.equalsIgnoreCase(eventType)) {
if(openInfo.get("dataUUID") != null && userID.equalsIgnoreCase(openInfo.get("userID"))) {
deleteRow(documentID);
LOGGER.info("удаляем запись из таблицы");
}
}
} else {
LOGGER.error("userID не должно быть NULL");
}
LOGGER.info("************************************");
}
} catch (Exception exc) {
mdc.setRollbackOnly();
}
}
private static void addRow(String documentID, String dataUUID, String userID) throws SQLException, NamingException {
if (documentID == null) return;
Connection con = null;
try {
con = ConnectionPool.getConnection();
PreparedStatement statement = con.prepareStatement("INSERT INTO opened_documents (documentID, dataUUID, userID, date) VALUES (?, ?, ?, ?)");
statement.setString(1, documentID);
statement.setString(2, dataUUID);
statement.setString(3, userID);
statement.setLong(4, new Date().getTime());
statement.executeUpdate();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
} finally {
ConnectionPool.close(con);
}
}
public static int deleteRow(String documentID) throws SQLException, NamingException {
if (documentID == null) return 0;
Connection con = null;
try {
con = ConnectionPool.getConnection();
PreparedStatement statement = con.prepareStatement("DELETE FROM opened_documents WHERE documentID = ?");
statement.setString(1, documentID);
return statement.executeUpdate();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
} finally {
ConnectionPool.close(con);
}
return 0;
}
public static int deleteAllRows() throws SQLException, NamingException {
Connection con = null;
try {
con = ConnectionPool.getConnection();
PreparedStatement statement = con.prepareStatement("DELETE FROM opened_documents");
return statement.executeUpdate();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
} finally {
ConnectionPool.close(con);
}
return 0;
}
public static HashMap<String, String> checkOpenDocument(String documentID) throws SQLException, NamingException {
if (documentID == null) return null;
Connection con = null;
try {
con = ConnectionPool.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT dataUUID, userID, date FROM opened_documents WHERE documentID = ?");
ps.setString(1, documentID);
ResultSet res = ps.executeQuery();
HashMap<String, String> result = new HashMap<>();
if (res.next()) {
result.put("documentID", documentID);
result.put("dataUUID", res.getString("dataUUID"));
result.put("userID", res.getString("userID"));
result.put("date", res.getString("date"));
}
return result;
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
} finally {
ConnectionPool.close(con);
}
return null;
}
public static ArrayList getAllDocuments() throws SQLException, NamingException {
Connection con = null;
try {
con = ConnectionPool.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT documentID, dataUUID, userID, date FROM opened_documents");
ResultSet res = ps.executeQuery();
ArrayList<HashMap<String, String>> docs = new ArrayList<>();
while (res.next()) {
HashMap<String, String> row = new HashMap<>();
row.put("documentID", res.getString("documentID"));
row.put("dataUUID", res.getString("dataUUID"));
row.put("userID", res.getString("userID"));
row.put("date", res.getString("date"));
docs.add(row);
}
return docs;
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
} finally {
ConnectionPool.close(con);
}
return null;
}
public static HashMap<String, String> getDocumentInfo(String documentID) throws SQLException, NamingException {
if (documentID == null) return null;
Connection con = null;
try {
con = ConnectionPool.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT\n" +
"rg.documentID, rg.asfDataID,\n" +
"r.registryID, r.code registryCode,\n" +
"r.formid formID, ad.code formCode\n" +
"FROM registry_documents rg\n" +
"LEFT JOIN registries r ON r.registryID = rg.registryID\n" +
"LEFT JOIN asf_definition ad ON ad.uuid = r.formid\n" +
"WHERE rg.documentID = ?");
ps.setString(1, documentID);
ResultSet res = ps.executeQuery();
String dataUUID = null;
String registryID = null;
String registryCode = null;
String formID = null;
String formCode = null;
if (res.next()) {
dataUUID = res.getString("asfDataID");
registryID = res.getString("registryID");
registryCode = res.getString("registryCode");
formID = res.getString("formID");
formCode = res.getString("formCode");
}
HashMap<String, String> result = new HashMap<>();
result.put("documentID", documentID);
result.put("dataUUID", dataUUID);
result.put("registryID", registryID);
result.put("registryCode", registryCode);
result.put("formID", formID);
result.put("formCode", formCode);
return result;
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
} finally {
ConnectionPool.close(con);
}
return null;
}
}
\ No newline at end of file
package kz.arta.documentServices.rest;
import kz.arta.documentServices.util.Config;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.HttpHeaders;
import java.io.IOException;
public class PersonApi {
private static final Logger LOGGER = LoggerFactory.getLogger(PersonApi.class);
public static int checkUserAuth(String auth) throws IOException {
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(Config.getProperty("synergy.url", "http://127.0.0.1:8080/Synergy") + "/rest/api/person/auth");
request.setHeader(HttpHeaders.AUTHORIZATION, auth);
HttpResponse response = client.execute(request);
return response.getStatusLine().getStatusCode();
}
}
package kz.arta.documentServices.rest.response;
public class ErrorCode {
public static final int NO_ERROR = 0;
public static final int EXCEPTION = 13;
public static final int WARNING = 666;
public static final int EMPTY_DATA = 1;
public static final int ACCESS_DENIED = 2;
public static final int INVALID_DATA = 3;
public static final int ILLEGAL_OBJECTIVE_APPOINTMENT = 101;
public static final int ILLEGAL_OBJECTIVE_SAVE = 102;
public static final int ILLEGAL_OBJECTIVE_REJECT = 103;
public static final int ILLEGAL_OBJECTIVE_DELETE = 104;
public static final int ILLEGAL_OBJECTIVE_CANCEL = 105;
public static final int ILLEGAL_OBJECTIVE_APPROVE = 106;
/**
* Родительская цель не существует или завершена
*/
public static final int PARENT_OBJECTIVE_DOES_NOT_EXIST = 107;
/**
* Предпринята попытка изменить показатель для цели
*/
public static final int OBJECTIVE_POINTER_HAS_BEEN_APPROVED = 108;
/**
* Статус цели изменен во время редактирования
*/
public static final int OBJECTIVE_STATE_CHANGED_CLOSED = 109;
/**
* Статус цели изменен (отклонена)
*/
public static final int OBJECTIVE_STATE_CHANGED_REJECTED = 110;
/**
* Статус цели изменен (утверждена)
*/
public static final int OBJECTIVE_STATE_CHANGED_APPROVED = 111;
/**
* Цель не может быть отклонена так как уж утверждена
*/
public static final int OBJECTIVE_CANNOT_BE_CANCELED = 112;
/**
* Данный пользователь не может быть удален, так как является
* единственным администратором корневого подразделения
*/
public static final int AT_LEAST_SINGLE_ADMIN_SHOULD_BE = 201;
public static final int TOO_LONG_LAST_NAME = 202;
public static final int TOO_LONG_FIRST_NAME = 203;
public static final int TOO_LONG_PATRONYMIC = 204;
public static final int TOO_LONG_MAIL = 205;
public static final int TOO_LONG_LOGIN = 206;
public static final int TOO_LONG_PASSWORD = 207;
public static final int TOO_LONG_DEPARTMENT_NAME_RU = 208;
public static final int TOO_LONG_DEPARTMENT_NAME_EN = 209;
public static final int TOO_LONG_DEPARTMENT_NAME_KZ = 210;
public static final int TOO_LONG_POSITION_NAME_RU = 208;
public static final int TOO_LONG_POSITION_NAME_EN = 209;
public static final int TOO_LONG_POSITION_NAME_KZ = 210;
/**
* Пользователя пытаются назначить на должность на которою он уже назначен
*/
public static final int USER_HAS_THIS_POSITION = 211;
/**
* Родительский элемнт не существует
*/
public static final int PARENT_DEPARMENT_DOES_NOT_EXIST = 212;
/**
* Достигнуто максимальное количество пользователей в базе данных
*/
public static final int MAX_USERS_COUNT_EXCEEDED = 213;
/**
* Элемент не существует
*/
public static final int ELEMENT_DOES_NOT_EXIST = 214;
/**
* Должность удалена
*/
public static final int POSITION_NOT_FOUND = 215;
/**
* Пользователь удален
*/
public static final int USER_NOT_FOUND = 216;
/**
* у департамента уже есть руководитель
*/
public static final int DEPARTMENT_HAS_MANAGER = 217;
/**
* Время исполнения задачи пересекается со временем исполнения
* другой задачи, либо время начала позже времени завершения
*/
public static final int ILLEGAL_TASK_TIME = 301;
/**
* Не выбрана цель для задачи, либо данная цель не исполняется
* пользователем или завершена.
*/
public static final int ILLEGAL_TASK_OBJECTIVE = 302;
/**
* Руководитель пытается назначить задачу задним числом
*/
public static final int CANNOT_APPOINT_TASK_IN_THE_PAST = 303;
/**
* Неверная формула показателя
*/
public static final int INVALID_POINTER_FORMULA = 401;
/**
* В формуле показателя обнаружена циклическая ссылка
*/
public static final int CYCLE_LINK = 402;
/**
* Код показателя содержит недопустимые символы (пробелы)
*/
public static final int INVALID_CODE = 403;
/**
* Данный код уже испоьзуется
*/
public static final int CODE_IN_USE = 404;
/**
* существуют цели оцениваемые данным показателем
*/
public static final int POINTER_HAS_OBJECTIVES = 405;
/**
* Существуют результирующие показатели в расчете значений которых участвует данный показатель
*/
public static final int POINTER_HAS_POINTERS = 406;
/**
* Показатель используется в расчете др показателей, его длина не мрожет быть равна 0
*/
public static final int POINTER_CODE_LENGTH_CANNOT_BE_NULL = 407;
/**
* Значение показателя может быть изменено явно только для свободных и
* формирующих показателей
*/
public static final int VALUE_CANNOT_BE_CHANGED_FOR_THIS_POINTER_TYPE = 410;
/**
* Показатель не существует
*/
public static final int POINTER_DOES_NOT_EXIST = 411;
public static final int INVALID_POINTER_VALUE = 412;
public static final int POINTER_NOT_FOUND = 413;
/**
* Пользователь с таким логином уже существует
*/
public static final int LOGIN_IS_ALREADY_EXIST = 23;
public static final int ACTION_PERCENT_CANNOT_BE_CHANGED_MANUALLY = 501;
/**
* Нет руководителей
*/
public static final int NO_OWN_MANAGER = 502;
/**
* Нельзя завершить работу
*/
public static final int CANNOT_FINISH_WORKS = 503;
public static final int CERTIFICATE_INVALIDATED = 601;
public static final int CERTIFICATE_REVOKED = 602;
public static final int ICON_TOO_BIG = 701;
public static final int NOT_PNG = 702;
/**
* Не валидная дата для создания/копирования мероприятия
*/
public static final int INVALID_PROJECT_DATE = 801;
public static final int INVALID_PROJECT_START_DATE = 802;
public static final int INVALID_PROJECT_FINISH_DATE = 803;
/**
* подписи
*/
public static final int SIGN_DATA_CHANGED = 901;
public static final int SIGNS_LIST_CHANGED = 902;
public static final int SIGNS_LIST_EMPTY = 903;
public static final int OBJECT_NOT_FOUND = 904;
/**
* невалидное ркк
*/
public static final int RCC_INVALID = 905;
/**
* ошибка ссылок на объект
*/
public static final int OBJECT_REFERENCE_ERROR = 1000;
}
package kz.arta.documentServices.rest.response;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.Serializable;
public class ErrorPOJO implements Serializable {
/**
* Значение кода ошибки по умолчанию
*/
private static final int DEFAULT_ERROR_CODE = ErrorCode.EXCEPTION;
/**
* код ошибки
*/
private int errorCode = 0;
/**
* ошибка
*/
private String errorMessage = "";
public ErrorPOJO() {
}
public ErrorPOJO(int errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
/**
* создает jaxrs ответ на основе конструктора {@link ErrorPOJO}
*
* @param errorCode код ошибки
* @param errorMessage сообщение
*/
public static Response buildResponse(int errorCode, String errorMessage) {
return new ErrorPOJO(errorCode, errorMessage)
.buildResponse();
}
/**
* возвращает валидный ответ
*
* @param errorMessage сообщение
* @return jaxrs ответ
*/
public static Response buildValid(String errorMessage) {
return Response.ok(new ErrorPOJO(ErrorCode.NO_ERROR, errorMessage)).build();
}
/**
* {@link #buildResponse(int, String)}
*/
public static Response buildResponse(String errorMessage) {
return buildResponse(DEFAULT_ERROR_CODE, errorMessage);
}
public Response buildResponse() {
return Response.serverError().entity(this).build();
}
public Response buildResponse(Response.StatusType status) {
return Response.status(status).entity(this).type(MediaType.APPLICATION_JSON_TYPE).build();
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
package kz.arta.documentServices.rest.response;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.Serializable;
/**
* Created by exile
* Date: 10.02.16
* Time: 11:04
* класс обертка для ошибок
*/
public class ResponsePOJO<T> implements Serializable {
/**
* Значение кода ошибки по умолчанию
*/
private static final int DEFAULT_ERROR_CODE = ErrorCode.EXCEPTION;
/**
* Код ошибки
*/
private int errorCode = 0;
/**
* Наименование ошибки
*/
private String errorMessage = "OK";
/**
* Результат
*/
private T data;
public ResponsePOJO() {
}
/**
* Конструктор с успешным ответом по умолчанию
*/
public ResponsePOJO(T data) {
this.data = data;
}
/**
* Конструктор с успешным ответом по умолчанию но с произвольным статусом
*/
public ResponsePOJO(int errorCode, T data) {
this.errorCode = ErrorCode.NO_ERROR;
this.data = data;
}
/**
* Конструктор с произвольным ответом
*
* @param errorCode Код ошибки
* @param errorMessage Наименование ошибки
* @param data Объект (Класса) *Вернется в ключе data*
*/
public ResponsePOJO(int errorCode, String errorMessage, T data) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.data = data;
}
public static ResponsePOJO exception(Exception e) {
return exception(e.getMessage());
}
public static ResponsePOJO exception(String msg) {
return new ResponsePOJO(ErrorCode.EXCEPTION, msg);
}
/**
* создает jaxrs ответ на основе конструктора {@link ResponsePOJO}
*
* @param errorCode код ошибки
* @param errorMessage сообщение
*/
public static Response buildResponse(int errorCode, String errorMessage) {
return new ResponsePOJO(errorCode, errorMessage)
.buildResponse();
}
/**
* Возвращает валидный ответ
*
* @param errorMessage сообщение
* @return jaxrs ответ
*/
public static Response buildValid(String errorMessage) {
return Response.ok(new ResponsePOJO(ErrorCode.NO_ERROR, errorMessage)).build();
}
/**
* {@link #buildResponse(int, String)}
*/
public static Response buildResponse(String errorMessage) {
return buildResponse(DEFAULT_ERROR_CODE, errorMessage);
}
public Response buildResponse() {
return Response.serverError().entity(this).build();
}
public Response buildResponse(Response.StatusType status) {
return Response.status(status).entity(this).type(MediaType.APPLICATION_JSON_TYPE).build();
}
public int getErrorCode() {
return this.errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public T getData() {
return this.data;
}
public void setData(T object) {
this.data = object;
}
public String getErrorMessage() {
return this.errorMessage;
}
public void setErrorMessage(String value) {
this.errorMessage = value;
}
}
package kz.arta.documentServices.rest.response;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
/**
* Created by Alex Basheyeva
* Date: 16.08.17
* Time: 16:58
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Result {
private String errorCode;
private String errorMessage;
public boolean isSuccess(){
return "0".equals(errorCode);
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
@Override
public String toString() {
return "Result{" +
"errorCode='" + errorCode + '\'' +
", errorMessage='" + errorMessage + '\'' +
'}';
}
}
package kz.arta.documentServices.service;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
/**
* Created by val
* Date: 04.10.2015
* Time: 11:18
*/
@ApplicationPath("rest/api")
public class Activator extends Application {
}
package kz.arta.documentServices.service;
import kz.arta.documentServices.rest.PersonApi;
import kz.arta.documentServices.rest.response.*;
import kz.arta.documentServices.listeners.DocflowDocumentListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.List;
@Path("/document")
@RequestScoped
public class DocumentRestServices {
private static final Logger LOGGER = LoggerFactory.getLogger(DocumentRestServices.class);
@GET
@Path("/isopen")
@Produces(MediaType.APPLICATION_JSON + "; charset=utf-8")
public Response documentIsOpen(@QueryParam("documentID") String documentID, @Context HttpHeaders headers) throws IOException {
if (documentID == null) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorPOJO(ErrorCode.EXCEPTION, "Не передан documentID")).build();
}
List<String> authHeaders = headers.getRequestHeader(HttpHeaders.AUTHORIZATION);
if (authHeaders != null && !authHeaders.isEmpty()) {
try {
int statusAuth = PersonApi.checkUserAuth(authHeaders.get(0));
if(statusAuth != 200) {
return Response.status(Response.Status.UNAUTHORIZED).entity(new ErrorPOJO(ErrorCode.ACCESS_DENIED, "Ошибка авторизации")).build();
}
HashMap<String, String> openInfo = DocflowDocumentListener.checkOpenDocument(documentID);
if(openInfo.get("dataUUID") == null) {
return Response.ok(new ResponsePOJO(ErrorCode.NO_ERROR, null)).build();
} else {
return Response.ok(new ResponsePOJO(openInfo)).build();
}
} catch (Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorPOJO(ErrorCode.EXCEPTION, e.getMessage())).build();
}
} else {
return Response.status(Response.Status.UNAUTHORIZED).entity(new ErrorPOJO(ErrorCode.EXCEPTION, "Ошибка авторизации")).build();
}
}
@GET
@Path("/info")
@Produces(MediaType.APPLICATION_JSON + "; charset=utf-8")
public Response documentInfo(@QueryParam("documentID") String documentID, @Context HttpHeaders headers) throws IOException {
if (documentID == null) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorPOJO(ErrorCode.EXCEPTION, "Не передан documentID")).build();
}
List<String> authHeaders = headers.getRequestHeader(HttpHeaders.AUTHORIZATION);
if (authHeaders != null && !authHeaders.isEmpty()) {
try {
int statusAuth = PersonApi.checkUserAuth(authHeaders.get(0));
if(statusAuth != 200) {
return Response.status(Response.Status.UNAUTHORIZED).entity(new ErrorPOJO(ErrorCode.ACCESS_DENIED, "Ошибка авторизации")).build();
}
HashMap<String, String> docInfo = DocflowDocumentListener.getDocumentInfo(documentID);
if(docInfo.get("dataUUID") == null) {
return Response.ok(new ResponsePOJO(ErrorCode.NO_ERROR, null)).build();
} else {
return Response.ok(new ResponsePOJO(docInfo)).build();
}
} catch (Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorPOJO(ErrorCode.EXCEPTION, e.getMessage())).build();
}
} else {
return Response.status(Response.Status.UNAUTHORIZED).entity(new ErrorPOJO(ErrorCode.EXCEPTION, "Ошибка авторизации")).build();
}
}
@GET
@Path("/list")
@Produces(MediaType.APPLICATION_JSON + "; charset=utf-8")
public Response getAllOpenDocuments(@Context HttpHeaders headers) throws IOException {
List<String> authHeaders = headers.getRequestHeader(HttpHeaders.AUTHORIZATION);
if (authHeaders != null && !authHeaders.isEmpty()) {
try {
int statusAuth = PersonApi.checkUserAuth(authHeaders.get(0));
if(statusAuth != 200) {
return Response.status(Response.Status.UNAUTHORIZED).entity(new ErrorPOJO(ErrorCode.ACCESS_DENIED, "Ошибка авторизации")).build();
}
List allDocuments = DocflowDocumentListener.getAllDocuments();
return Response.ok(new ResponsePOJO(allDocuments)).build();
} catch (Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorPOJO(ErrorCode.EXCEPTION, e.getMessage())).build();
}
} else {
return Response.status(Response.Status.UNAUTHORIZED).entity(new ErrorPOJO(ErrorCode.EXCEPTION, "Ошибка авторизации")).build();
}
}
@POST
@Path("/remove/{documentID}")
@Produces(MediaType.APPLICATION_JSON)
public Response removeDocument(@PathParam("documentID") String documentID, @Context HttpHeaders headers) throws IOException {
List<String> authHeaders = headers.getRequestHeader(HttpHeaders.AUTHORIZATION);
if (authHeaders != null && !authHeaders.isEmpty()) {
try {
int statusAuth = PersonApi.checkUserAuth(authHeaders.get(0));
if(statusAuth != 200) {
return Response.status(Response.Status.UNAUTHORIZED).entity(new ErrorPOJO(ErrorCode.ACCESS_DENIED, "Ошибка авторизации")).build();
}
int res = DocflowDocumentListener.deleteRow(documentID);
return Response.ok(new ResponsePOJO(res)).build();
} catch (Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorPOJO(ErrorCode.EXCEPTION, e.getMessage())).build();
}
} else {
return Response.status(Response.Status.UNAUTHORIZED).entity(new ErrorPOJO(ErrorCode.EXCEPTION, "Ошибка авторизации")).build();
}
}
@POST
@Path("/removeAll")
@Produces(MediaType.APPLICATION_JSON)
public Response removeAllDocuments(@Context HttpHeaders headers) throws IOException {
List<String> authHeaders = headers.getRequestHeader(HttpHeaders.AUTHORIZATION);
if (authHeaders != null && !authHeaders.isEmpty()) {
try {
int statusAuth = PersonApi.checkUserAuth(authHeaders.get(0));
if(statusAuth != 200) {
return Response.status(Response.Status.UNAUTHORIZED).entity(new ErrorPOJO(ErrorCode.ACCESS_DENIED, "Ошибка авторизации")).build();
}
int res = DocflowDocumentListener.deleteAllRows();
return Response.ok(new ResponsePOJO(res)).build();
} catch (Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorPOJO(ErrorCode.EXCEPTION, e.getMessage())).build();
}
} else {
return Response.status(Response.Status.UNAUTHORIZED).entity(new ErrorPOJO(ErrorCode.EXCEPTION, "Ошибка авторизации")).build();
}
}
}
package kz.arta.documentServices.service;
import kz.arta.documentServices.util.Config;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* Created by val
* Date: 04.10.2015
* Time: 11:27
*
* REST сервис с методами, которые не требуют авторизации
*/
@Path("/unsecured")
@RequestScoped
public class UnsecuredProxyService {
private static final Logger LOGGER = LoggerFactory.getLogger(UnsecuredProxyService.class);
/**
* Обертка над методом /rest/api/storage/file/get
* Не требует авторизации.
* Обращение к REST API Synergy осуществляется от имени пользователя,
* указанного в настройках (параметры synergy.user.login и synergy.user.password)
*
* @param identifier идентификатор файла в хранилище
* @return inline изображение.
*/
@GET
@Path("/image")
public Response getImage(@QueryParam("identifier") String identifier) {
try {
String auth = Config.getProperty("synergy.user.login", "1") + ":" + Config.getProperty("synergy.user.password", "1");
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("UTF-8")));
String authHeader = "Basic " + new String(encodedAuth);
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(Config.getProperty("synergy.url", "http://127.0.0.1:8080/Synergy") + "/rest/api/storage/file/get?inline=true&identifier=" + identifier);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
Response.ResponseBuilder builder = Response.ok();
builder.entity(entity.getContent());
for (Header header : response.getAllHeaders()) {
builder.header(header.getName(), header.getValue());
}
return builder.build();
} catch (IOException e) {
LOGGER.error("", e);
return Response.serverError().build();
}
}
}
package kz.arta.documentServices.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.*;
/**
* Created by val
* Date: 24.05.2015
* Time: 17:02
*
* Класс для чтения параметров .properties файла
* Указанный кофигурационный файл ищется в папке jboss/standalone/configuration
*/
public class Config {
private static final Logger LOGGER = LoggerFactory.getLogger(Config.class);
private static Properties props = new Properties();
static {
File confFile = new File(getConfigDir() + "/documentServices.properties");
if (confFile.exists()) {
try {
props.load(new InputStreamReader(new FileInputStream(confFile), "UTF8"));
} catch (IOException e) {
LOGGER.error("Configuration file not found");
}
}
}
public static URL getResource(String path) {
return Config.class.getResource(path);
}
public static String getConfigDir() {
return System.getProperty("jboss.server.config.dir");
}
public static String getProperty(String name, String defaultValue) {
return props.containsKey(name) ? props.getProperty(name) : defaultValue;
}
public static int getIntProperty(String name, int defaultValue) {
if (props.containsKey(name)) {
int value = defaultValue;
String v = props.getProperty(name);
try {
value = Integer.parseInt(v);
} catch (NumberFormatException e) {
LOGGER.error("Invalid type of value '" + v + "' for property '" + name + "'. Integer type required.");
}
return value;
} else
return defaultValue;
}
public static double getDoubleProperty(String name, double defaultValue) {
if (props.containsKey(name)) {
double value = defaultValue;
String v = props.getProperty(name);
try {
value = Double.parseDouble(v);
} catch (NumberFormatException e) {
LOGGER.error("Invalid type of value '" + v + "' for property '" + name + "'. Double type required.");
}
return value;
} else
return defaultValue;
}
public static boolean getBooleanProperty(String name, boolean defaultValue) {
if (props.containsKey(name)) {
boolean value = defaultValue;
String v = props.getProperty(name);
try {
value = Boolean.parseBoolean(v);
} catch (Exception e) {
LOGGER.error("Invalid type of value '" + v + "' for property '" + name + "'. Boolean type required.");
}
return value;
}
return defaultValue;
}
public static List<String> getPropertyList(String mask, String[] defaultValue) {
List<String> list = new ArrayList<String>();
for (String property : props.stringPropertyNames()) {
if (property.startsWith(mask)) {
list.add(property.substring(property.lastIndexOf(".") + 1));
}
}
return list.size() > 0 ? list : Arrays.asList(defaultValue);
}
public static Map<String, String> getPropertyList(String mask) {
Map<String, String> map = new HashMap<String, String>();
for (String property : props.stringPropertyNames()) {
if (property.startsWith(mask)) {
map.put(property, props.getProperty(property));
}
}
return map;
}
}
package kz.arta.documentServices.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Created by val
* Date: 04.10.2015
* Time: 11:13
*
* Пример класса, который отвечает за работу с пулом соединений
*/
public class ConnectionPool {
private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionPool.class);
private static final String POOL_NAME = "java:/documentServicesDS";
public static Connection getConnection() throws SQLException, NamingException {
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(POOL_NAME);
return ds.getConnection();
}
public static void close(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
LOGGER.error("Unable to close connection", e);
}
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2">
<deployment>
<dependencies>
<module name="org.codehaus.jackson.jackson-jaxrs"/>
<module name="org.codehaus.jackson.jackson-mapper-asl"/>
<module name="org.codehaus.jackson.jackson-core-asl"/>
</dependencies>
</deployment>
</jboss-deployment-structure>
\ No newline at end of file
<jboss-web>
<context-root>documentServices</context-root>
</jboss-web>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</web-app>
\ No newline at end of file
<!DOCTYPE HTML>
<html>
<head>
<style>
html,
body {
height: 100%;
margin:0
}
</style>
<title>documentServices</title>
<meta charset="utf-8">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body style="width:100%; height:100%">
<div id="app" style="width:100%; height:100%">
<h1>documentServices</h1>
</div>
</body>
</html>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment