Skip to content

Commit

Permalink
feat: Add server interceptors. (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
EdwinBetanc0urt authored Jan 15, 2024
1 parent 529a7ab commit 5df543f
Show file tree
Hide file tree
Showing 5 changed files with 92 additions and 35 deletions.
21 changes: 21 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
// Use IntelliSense para saber los atributos posibles.
// Mantenga el puntero para ver las descripciones de los existentes atributos.
// Para más información, visite: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "java",
"name": "ADmempiere gRPC Template",
"request": "launch",
"mainClass": "org.spin.template.server.TemplateServer",
"projectName": "adempiere-grpc-template-service",
"env": {
"ADEMPIERE_APPS_TYPE": "wildfly",
"JWT_SECRET_KEY": "2C51599F5B1248F945B93E05EFC43B3A15D8EB0707C0F02FD97028786C40976F",
"JWT_EXPIRATION_TIME": 86400000
},
"args": "'resources/env.yaml'"
}
]
}
3 changes: 2 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ jar {
}

repositories {
mavenLocal()
mavenCentral()
mavenLocal()
maven {
url = System.getenv("GITHUB_DEPLOY_REPOSITORY") ?: System.properties['deploy.repository'] ?: 'https://maven.pkg.github.com'
credentials {
Expand Down Expand Up @@ -109,6 +109,7 @@ task createRelease(type: Copy) {
}
}
}

dependencies {
implementation fileTree(
dir: 'dependencies',
Expand Down
2 changes: 1 addition & 1 deletion docker/backend_alpine.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ COPY docker/adempiere-grpc-template-service /opt/apps/server
COPY docker/env.yaml /opt/apps/server/env.yaml
COPY docker/start.sh /opt/apps/server/start.sh


RUN addgroup adempiere && \
adduser --disabled-password --gecos "" --ingroup adempiere --no-create-home adempiere && \
chown -R adempiere /opt/apps/server/ && \
Expand All @@ -48,4 +49,3 @@ USER adempiere

# Start app
ENTRYPOINT ["sh" , "start.sh"]

1 change: 1 addition & 0 deletions docker/backend_focal.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ RUN apt-get update && \
fontconfig \
ttf-dejavu && \
rm -rf /var/lib/apt/lists/* \
rm -rf /tmp/* && \
echo "Set Timezone..." && \
echo $TZ > /etc/timezone

Expand Down
100 changes: 67 additions & 33 deletions src/main/java/org/spin/template/server/TemplateServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

import org.compiere.util.Env;
Expand All @@ -33,25 +35,52 @@

public class TemplateServer {
private static final Logger logger = Logger.getLogger(TemplateServer.class.getName());
private ServiceContextProvider contextProvider = new ServiceContextProvider();

private Server server;

private ServiceContextProvider contextProvider = new ServiceContextProvider();


/** Services/Methods allow request without Bearer token validation */
private List<String> ALLOW_REQUESTS_WITHOUT_TOKEN = Arrays.asList(
// proto package . proto service / proto method
);

/** Revoke session */
private List<String> REVOKE_TOKEN_SERVICES = Arrays.asList(
// proto package . proto service / proto method
);

private AuthorizationServerInterceptor getInterceptor() {
AuthorizationServerInterceptor interceptor = new AuthorizationServerInterceptor();
interceptor.setAllowRequestsWithoutToken(this.ALLOW_REQUESTS_WITHOUT_TOKEN);
interceptor.setRevokeTokenServices(this.REVOKE_TOKEN_SERVICES);
return interceptor;
}


/**
* Get SSL / TLS context
* @return
*/
private SslContextBuilder getSslContextBuilder() {
SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(new File(SetupLoader.getInstance().getServer().getCertificate_chain_file()),
new File(SetupLoader.getInstance().getServer().getPrivate_key_file()));
if (SetupLoader.getInstance().getServer().getTrust_certificate_collection_file() != null) {
sslClientContextBuilder.trustManager(new File(SetupLoader.getInstance().getServer().getTrust_certificate_collection_file()));
sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);
}
return GrpcSslContexts.configure(sslClientContextBuilder);
SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(
new File(SetupLoader.getInstance().getServer().getCertificate_chain_file()),
new File(SetupLoader.getInstance().getServer().getPrivate_key_file())
);
if (SetupLoader.getInstance().getServer().getTrust_certificate_collection_file() != null) {
sslClientContextBuilder.trustManager(
new File(SetupLoader.getInstance().getServer().getTrust_certificate_collection_file())
);
sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);
}
return GrpcSslContexts.configure(sslClientContextBuilder);
}

private void start() throws IOException {
// Start based on provider
Env.setContextProvider(contextProvider);
Env.setContextProvider(this.contextProvider);

logger.info("Service Template added on " + SetupLoader.getInstance().getServer().getPort());
//
ServerBuilder<?> serverBuilder;
Expand All @@ -60,37 +89,41 @@ private void start() throws IOException {
.sslContext(getSslContextBuilder().build());
} else {
serverBuilder = ServerBuilder.forPort(SetupLoader.getInstance().getServer().getPort());
serverBuilder.intercept(new AuthorizationServerInterceptor());
}

// Validate JWT on all requests
AuthorizationServerInterceptor interceptor = getInterceptor();
serverBuilder.intercept(interceptor);

serverBuilder.addService(new TemplateService());
server = serverBuilder.build().start();
this.server = serverBuilder.build().start();
logger.info("Server started, listening on " + SetupLoader.getInstance().getServer().getPort());
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
logger.info("*** shutting down gRPC server since JVM is shutting down");
logger.info("*** shutting down gRPC Server since JVM is shutting down");
TemplateServer.this.stop();
logger.info("*** server shut down");
}
});
}

private void stop() {
if (server != null) {
server.shutdown();
}
if (this.server != null) {
this.server.shutdown();
}
}

/**
* Await termination on the main thread since the grpc library uses daemon threads.
*/
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
if (this.server != null) {
this.server.awaitTermination();
}
}

public static void main(String[] args) throws Exception {
if (args == null) {
throw new Exception("Arguments Not Found");
Expand All @@ -99,15 +132,16 @@ public static void main(String[] args) throws Exception {
if (args.length == 0) {
throw new Exception("Arguments Must Be: [property file name]");
}
String setupFileName = args[0];
if(setupFileName == null || setupFileName.trim().length() == 0) {
throw new Exception("Setup File not found");
}
SetupLoader.loadSetup(setupFileName);
// Validate load
SetupLoader.getInstance().validateLoad();
final TemplateServer server = new TemplateServer();
server.start();
server.blockUntilShutdown();
}
String setupFileName = args[0];
if(setupFileName == null || setupFileName.trim().length() == 0) {
throw new Exception("Setup File not found");
}
SetupLoader.loadSetup(setupFileName);
// Validate load
SetupLoader.getInstance().validateLoad();
final TemplateServer server = new TemplateServer();
server.start();
server.blockUntilShutdown();
}

}

0 comments on commit 5df543f

Please sign in to comment.