Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix global job execution #328

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.condation.cms.api.extensions.http;

/*-
* #%L
* cms-api
* %%
* Copyright (C) 2023 - 2024 CondationCMS
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/

import com.condation.cms.api.extensions.AbstractExtensionPoint;

public abstract class APIHandlerExtensionPoint extends AbstractExtensionPoint {
abstract public PathMapping getMapping();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.condation.cms.api.extensions.http;

/*-
* #%L
* cms-api
* %%
* Copyright (C) 2023 - 2024 CondationCMS
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.util.Callback;

/**
*
* @author t.marx
*/
public interface HttpHandler {

boolean handle (Request request, Response response, Callback callback) throws Exception;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package com.condation.cms.api.extensions.http;

/*-
* #%L
* cms-api
* %%
* Copyright (C) 2023 - 2024 CondationCMS
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.eclipse.jetty.http.pathmap.PathSpec;

public class PathMapping {

private List<Mapping> mappings;

public PathMapping () {
mappings = new ArrayList<>();
}

public void add (PathSpec pathSpec, String method, HttpHandler handler) {
mappings.add(new Mapping(pathSpec, method, handler));
}

public Optional<HttpHandler> getMatchingHandler (String uri, String method) {
return mappings.stream().filter(entry ->
entry.pathSpec.matches(uri) && entry.method.equalsIgnoreCase(method)
).map(entry -> entry.handler).findFirst();
}


private static record Mapping (PathSpec pathSpec, String method, HttpHandler handler){};
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public enum Hooks {
SCHEDULER_REMOVE("system/scheduler/remove"),
HTTP_EXTENSION("system/server/http/extension"),
HTTP_ROUTE("system/server/http/route"),
API_ROUTE("system/server/api/route"),
TEMPLATE_SUPPLIER("system/template/supplier"),
TEMPLATE_FUNCTION("system/template/function")
;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
import com.condation.cms.api.scheduler.CronJobContext;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
Expand All @@ -36,25 +38,20 @@
*
* @author t.marx
*/
@DisallowConcurrentExecution
public class SingleCronJobRunner implements Job {

public static final String DATA_CRONJOB = "cronjob";
public static final String DATA_CONTEXT = "context";

private static final Lock lock = new ReentrantLock(true);

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
if (context.getJobDetail().getJobDataMap().get(DATA_CRONJOB) != null) {
CronJobContext jobContext = (CronJobContext) context.getJobDetail().getJobDataMap().get(DATA_CONTEXT);

lock.lock();
try {
((CronJob)context.getJobDetail().getJobDataMap().get(DATA_CRONJOB)).accept(jobContext);
} finally {
lock.unlock();
}
}
CronJobContext jobContext = (CronJobContext) context.getJobDetail().getJobDataMap().get(DATA_CONTEXT);
CronJob cronJob = (CronJob) context.getJobDetail().getJobDataMap().get(DATA_CRONJOB);

if (cronJob != null && jobContext != null) {
cronJob.accept(jobContext);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,12 @@ public HttpHandlerWrapper getHttpRoutes () {

return httpExtensions;
}

public HttpHandlerWrapper getAPIRoutes () {
var httpExtensions = new HttpHandlerWrapper();
requestContext.get(HookSystemFeature.class).hookSystem()
.execute(Hooks.API_ROUTE.hook(), Map.of("apiRoutes", httpExtensions));

return httpExtensions;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
*/


import com.condation.cms.media.FileMediaService;
import java.io.IOException;
import java.nio.file.Path;
import org.assertj.core.api.Assertions;
Expand Down
17 changes: 17 additions & 0 deletions cms-server/src/main/java/com/condation/cms/server/VHost.java
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
import com.condation.cms.server.filter.InitRequestContextFilter;
import com.condation.cms.server.filter.PooledRequestContextFilter;
import com.condation.cms.server.filter.RequestLoggingFilter;
import com.condation.cms.server.handler.api.APIHandler;
import com.condation.cms.server.handler.auth.JettyAuthenticationHandler;
import com.condation.cms.server.handler.cache.CacheHandler;
import com.condation.cms.server.handler.content.JettyContentHandler;
Expand Down Expand Up @@ -271,6 +272,10 @@ public Handler buildHttpHandler() {
createExtensionHandler()
);

pathMappingsHandler.addMapping(PathSpec.from("/" + APIHandler.PATH + "/*"),
createAPIHandler()
);

ContextHandler defaultContextHandler = new ContextHandler(
pathMappingsHandler,
injector.getInstance(SiteProperties.class).contextPath()
Expand Down Expand Up @@ -301,6 +306,18 @@ public Handler buildHttpHandler() {
return hostHandler;
}

private Handler.Wrapper createAPIHandler() {
var authHandler = injector.getInstance(JettyAuthenticationHandler.class);
var initContextHandler = injector.getInstance(InitRequestContextFilter.class);
var apiHandler = injector.getInstance(APIHandler.class);
var handlerSequence = new Handler.Sequence(
authHandler,
initContextHandler,
apiHandler
);
return requestContextFilter(handlerSequence, injector);
}

private Handler.Wrapper createExtensionHandler() {
var authHandler = injector.getInstance(JettyAuthenticationHandler.class);
var initContextHandler = injector.getInstance(InitRequestContextFilter.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import com.condation.cms.auth.services.AuthService;
import com.condation.cms.auth.services.UserService;
import com.condation.cms.media.SiteMediaManager;
import com.condation.cms.server.handler.api.APIHandler;
import com.condation.cms.server.handler.auth.JettyAuthenticationHandler;
import com.condation.cms.server.filter.InitRequestContextFilter;
import com.condation.cms.server.handler.content.JettyContentHandler;
Expand Down Expand Up @@ -75,6 +76,8 @@ protected void configure() {
bind(JettyHttpHandlerExtensionHandler.class).in(Singleton.class);
bind(JettyExtensionRouteHandler.class).in(Singleton.class);
bind(InitRequestContextFilter.class).in(Singleton.class);

bind(APIHandler.class).in(Singleton.class);

//bind(JettyAuthenticationHandler.class).in(Singleton.class);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package com.condation.cms.server.handler.api;

import com.condation.cms.api.extensions.HttpRoutesExtensionPoint;
import com.condation.cms.api.extensions.Mapping;
import com.condation.cms.api.extensions.http.APIHandlerExtensionPoint;
import com.condation.cms.api.extensions.http.PathMapping;

/*-
* #%L
* cms-server
* %%
* Copyright (C) 2023 - 2024 CondationCMS
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/

import com.condation.cms.api.request.RequestContext;
import com.condation.cms.extensions.HttpHandlerExtension;
import com.condation.cms.extensions.hooks.ServerHooks;
import com.condation.cms.extensions.http.JettyHttpHandlerWrapper;
import com.condation.cms.server.filter.CreateRequestContextFilter;
import com.condation.modules.api.ModuleManager;
import com.google.inject.Inject;

import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.util.Callback;

/**
*
* @author t.marx
*/
@RequiredArgsConstructor(onConstructor = @__({
@Inject }))
@Slf4j
public class APIHandler extends Handler.Abstract {

public static final String PATH = "api";

private final ModuleManager moduleManager;

@Override
public boolean handle(Request request, Response response, Callback callback) throws Exception {

try {
if (handleExtensionRoute(request, response, callback)) {
return true;
}

if (handleModuleRoute(request, response, callback)) {
return true;
}

Response.writeError(request, response, callback, 404);
return true;
} catch (Exception e) {
log.error(null, e);
callback.failed(e);
return true;
}
}

private boolean handleModuleRoute(Request request, Response response, Callback callback) throws Exception {

String apiRoute = getApiRoute(request);
var method = request.getMethod();

Optional<PathMapping> firstMatch = moduleManager.extensions(APIHandlerExtensionPoint.class)
.stream()
.filter(extension -> extension.getMapping().getMatchingHandler(apiRoute, method).isPresent())
.map(extension -> extension.getMapping())
.findFirst();

if (firstMatch.isPresent()) {
var mapping = firstMatch.get();
var handler = mapping.getMatchingHandler(apiRoute, method).get();
return handler.handle(request, response, callback);
}

return false;
}

private boolean handleExtensionRoute(Request request, Response response, Callback callback) throws Exception {
var requestContext = (RequestContext) request.getAttribute(CreateRequestContextFilter.REQUEST_CONTEXT);

String extension = getApiRoute(request);
var method = request.getMethod();

var httpExtensions = requestContext.get(ServerHooks.class).getAPIRoutes();
Optional<HttpHandlerExtension> findHttpHandler = httpExtensions.findHttpHandler(method, extension);

if (findHttpHandler.isPresent()) {
return new JettyHttpHandlerWrapper(findHttpHandler.get().handler()).handle(request, response, callback);
}

return false;
}

private String getApiRoute(Request request) {
var path = request.getHttpURI().getPath();
var contextPath = request.getContext().getContextPath();

if (!contextPath.endsWith("/")) {
contextPath += "/";
}

contextPath = contextPath + PATH + "/";

path = path.replaceFirst(contextPath, "");
if (!path.startsWith("/")) {
path = "/" + path;
}
return path;
}

}
Loading