Commit 41b0d9b3 authored by Valentin Skripnikov's avatar Valentin Skripnikov

Initial commit

parents
*.iml
build
.idea
.gradle
# Шаблон веб-приложения с кастомным REST API
В приложении приведен пример создания кастомного REST API на Java.
Данное приложение можно разместить в сервере приложений JBoss, который
устанавливается вместе с Synergy.
## Сборка
Сборка осуществляется при помощи [Gradle Build Tool](https://gradle.org/)
```bash
$ ./gradlew war
```
Собранный `synergy-api-proxy-1.0.war` необходимо поместить
в `/opt/synergy/jboss/standalone/deployments`
## Конфигурация
Приложение читает конфигурационный файл `synergy-api-proxy.properties`
в директории `/opt/synergy/jboss/standalone/configuration/external`.
Параметры конфигурации:
```properties
# Приведенные ниже значения параметров являются значениями по-умолчанию
# Адрес Synergy для доступа к REST API
synergy.url=http://127.0.0.1:8080/Synergy
# Логин пользователя от имени которого будет выполняться запрос к REST API Synergy
synergy.user.login=1
# Пароль пользователя от имени которого будет выполняться запрос к REST API Synergy
synergy.user.password=1
```
## REST API
Endpoint: `http[s]://host:[port]/sap`
1. Метод получения изображения `/proxy/unsecured/image`
```
/**
* Обертка над методом /rest/api/storage/file/get
* Не требует авторизации.
* Обращение к REST API Synergy осуществляется от имени пользователя,
* указанного в настройках (параметры synergy.user.login и synergy.user.password)
*
* @param identifier идентификатор файла в хранилище
* @return inline изображение. Если запрошенный файл не является изображением, то вернется ошибка.
*/
```
Пример запроса:
`http://127.0.0.1:8080/sap/proxy/unsecured/image?identifier=29130a30-42cf-451a-98e8-6f6827d3751b`
\ No newline at end of file
apply plugin: 'war'
sourceCompatibility = 1.7
version = '1.0'
task wrapper(type: Wrapper) {
gradleVersion = '4.6'
distributionUrl = 'http://services.gradle.org/distributions/gradle-4.6-all.zip'
}
repositories {
mavenCentral()
}
dependencies {
providedCompile(group: 'org.slf4j', name: 'slf4j-api', version: '1.6.1', transitive: false)
providedCompile(group: 'org.codehaus.jackson', name: 'jackson-core-asl', version: '1.9.2', transitive: false)
providedCompile(group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version: '1.9.2', transitive: false)
compile 'org.apache.httpcomponents:httpclient:4.5.1'
providedCompile(group: 'org.jboss.resteasy', name: 'resteasy-jaxrs', version: '2.3.3.Final', transitive: false)
providedCompile 'org.jboss.spec:jboss-javaee-6.0:3.0.3.Final'
}
\ No newline at end of file
# Приведенные ниже значения параметров являются значениями по-умолчанию
# Адрес Synergy для доступа к REST API
synergy.url=http://127.0.0.1:8080/Synergy
# Логин пользователя от имени которого будет выполняться запрос к REST API Synergy
synergy.user.login=1
# Пароль пользователя от имени которого будет выполняться запрос к REST API Synergy
synergy.user.password=1
\ No newline at end of file
#Mon Apr 16 12:37:30 ALMT 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=http\://services.gradle.org/distributions/gradle-4.6-all.zip
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
rootProject.name = 'synergy-api-proxy'
package kz.arta.ext.sap.db;
import kz.arta.ext.sap.util.ConnectionPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.NamingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Created by val
* Date: 04.10.2015
* Time: 12:49
*
* Пример класса для работы с СУБД
* использует соединение, указанное в @{@link ConnectionPool}
*/
public class ClientManager {
private static final Logger LOGGER = LoggerFactory.getLogger(ClientManager.class);
public static void log(Object logItem) {
Connection con = null;
try {
con = ConnectionPool.getConnection();
PreparedStatement st = con.prepareStatement("INSERT INTO log(logged, clientid, hostname, extip, localip) VALUES (CURRENT_TIMESTAMP, ?, ?, ?, ?)");
st.setString(1, "clientId");
st.setString(2, "hostname");
st.setString(3, "extip");
st.setString(4, "localip");
st.execute();
} catch (SQLException | NamingException e) {
LOGGER.error("", e);
} finally {
ConnectionPool.close(con);
}
}
}
package kz.arta.ext.sap.service;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
/**
* Created by val
* Date: 04.10.2015
* Time: 11:18
*/
@ApplicationPath("proxy")
public class Activator extends Application {
}
package kz.arta.ext.sap.service;
import org.jboss.resteasy.annotations.interception.Precedence;
import org.jboss.resteasy.annotations.interception.ServerInterceptor;
import org.jboss.resteasy.core.Headers;
import org.jboss.resteasy.core.ResourceMethod;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.spi.Failure;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
/**
* Created by val
* Date: 17.04.2014
* Time: 18:51
*
* Обработчик доступа к методам REST API
*/
@Provider
@ServerInterceptor
@Precedence("SECURITY")
public class SecurityInterceptor implements PreProcessInterceptor {
private static final ServerResponse ACCESS_DENIED = new ServerResponse("Access allowed only for registered users", 401, new Headers<Object>());
@Context
HttpServletRequest request;
@Context
HttpServletResponse response;
@Override
public ServerResponse preProcess(HttpRequest httpRequest, ResourceMethod resourceMethod) throws Failure, WebApplicationException {
return null;
}
}
package kz.arta.ext.sap.service;
import kz.arta.ext.sap.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.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
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);
@GET
@Path("/test")
@Produces(MediaType.APPLICATION_JSON + "; charset=utf-8")
public String test() {
return "{\"status\":\"working\"}";
}
/**
* Обертка над методом /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();
int responseCode = response.getStatusLine().getStatusCode();
LOGGER.info("Request Url: " + request.getURI());
LOGGER.info("Response Code: " + responseCode);
LOGGER.info("Content-Type: " + entity.getContentType().getValue());
if (entity.getContentType().getValue().toLowerCase().startsWith("image/png")) {
Response.ResponseBuilder builder = Response.ok();
builder.entity(entity.getContent());
for (Header header : response.getAllHeaders()) {
builder.header(header.getName(), header.getValue());
}
return builder.build();
} else {
return Response.status(Response.Status.BAD_REQUEST).entity("Not an image").build();
}
} catch (IOException e) {
LOGGER.error("", e);
return Response.serverError().build();
}
}
}
package kz.arta.ext.sap.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() + "/external/synergy-api-proxy.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.ext.sap.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);
public static Connection getConnection() throws SQLException, NamingException {
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:jboss/datasources/DefineDS");
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>
<deployment>
<dependencies>
<module name="org.codehaus.jackson.jackson-jaxrs"/>
<module name="org.codehaus.jackson.jackson-mapper-asl"/>
</dependencies>
</deployment>
</jboss-deployment-structure>
<jboss-web>
<context-root>sap</context-root>
</jboss-web>
\ No newline at end of file
<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
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