use of org.osgl.mvc.result.Result in project actframework by actframework.
the class ReflectedHandlerInvoker method handle.
public Result handle(final ActionContext context) {
if (disabled) {
return ActNotFound.get();
}
if (null != throttleFilter) {
Result throttleResult = throttleFilter.handle(context);
if (null != throttleResult) {
return throttleResult;
}
}
Result result = pluginBeforeHandler.apply(context);
if (null != result) {
return result;
}
context.setReflectedHandlerInvoker(this);
app.eventBus().emit(new ReflectedHandlerInvokerInvoke(this, context));
if (isLargeResponse) {
context.setLargeResponse();
}
if (null != filters) {
context.fastjsonFilters(filters);
}
if (null != features) {
context.fastjsonFeatures(features);
}
if (null != dateFormatPattern) {
context.dateFormatPattern(dateFormatPattern);
}
if (byPassImplicityTemplateVariable && context.state().isHandling()) {
context.byPassImplicitVariable();
}
context.templateChangeListener(templateChangeListener);
if (noTemplateCache) {
context.disableTemplateCaching();
}
context.currentMethod(method);
String urlContext = this.controller.urlContext();
if (S.notBlank(urlContext)) {
context.urlContext(urlContext);
}
String templateContext = this.controller.templateContext();
if (null != templateContext) {
context.templateContext(templateContext);
}
preventDoubleSubmission(context);
processForceResponse(context);
if (forceDataBinding || context.state().isHandling()) {
ensureJsonDTOGenerated(context);
}
final Object controller = controllerInstance(context);
/*
* We will send back response immediately when param validation
* failed in either of the following cases:
* 1) this is an ajax call
* 2) the accept content type is **NOT** html
*/
boolean failOnViolation = context.isAjax() || context.accept() != H.Format.HTML;
final Object[] params = params(controller, context);
if (failOnViolation && context.hasViolation()) {
String msg = context.violationMessage(";");
return ActBadRequest.create(msg);
}
if (async) {
JobManager jobManager = context.app().jobManager();
String jobId = jobManager.prepare(new TrackableWorker() {
@Override
protected void run(ProgressGauge progressGauge) {
try {
invoke(handler, context, controller, params);
} catch (Exception e) {
logger.warn(e, "Error executing async handler: " + handler);
}
}
});
context.setJobId(jobId);
WebSocketConnectionManager wscm = app.getInstance(WebSocketConnectionManager.class);
wscm.subscribe(context.session(), SimpleProgressGauge.wsJobProgressTag(jobId));
jobManager.now(jobId);
return new RenderJSON(C.Map("jobId", jobId));
}
try {
return pluginAfterHandler.apply(invoke(handler, context, controller, params), context);
} finally {
if (hasOutputVar) {
fillOutputVariables(controller, params, context);
}
}
}
use of org.osgl.mvc.result.Result in project actframework by actframework.
the class ControllerEnhancerTest method returnResultWithParamAppCtxField.
@Test
public void returnResultWithParamAppCtxField() throws Exception {
prepare("ReturnResultWithParamCtxField");
m = method(int.class, String.class);
Method setCtx = cc.getMethod("setAppContext", ActionContext.class);
setCtx.invoke(c, ctx);
Object r = m.invoke(c, 100, "foo");
yes(r instanceof Result);
eq(100, ctx.renderArg("foo"));
eq("foo", ctx.renderArg("bar"));
}
use of org.osgl.mvc.result.Result in project actframework by actframework.
the class NetworkHandler method handle.
public void handle(final ActionContext ctx, final NetworkDispatcher dispatcher) {
if (isDestroyed()) {
return;
}
Exception refreshError = null;
if (Act.isDev()) {
try {
boolean updated = app.checkUpdates(false);
if (updated && !app.hasBlockIssue()) {
app.jobManager().on(SysEventId.POST_START, new Runnable() {
@Override
public void run() {
handle(ctx, dispatcher);
}
}, true);
dispatcher.keep();
return;
}
} catch (Exception e) {
refreshError = e;
}
}
final H.Request req = ctx.req();
String url = req.url();
H.Method method = req.method();
url = contentSuffixProcessor.apply(req, url);
try {
url = urlContextProcessor.apply(req, url);
} catch (NotFound notFound) {
ctx.handler(AlwaysNotFound.INSTANCE);
ctx.saveLocal();
AlwaysNotFound.INSTANCE.apply(ctx);
return;
}
Timer timer = metric.startTimer(MetricInfo.ROUTING);
final RequestHandler requestHandler = router().getInvoker(method, url, ctx);
ctx.handler(requestHandler);
timer.stop();
boolean resourceGetter = requestHandler instanceof ResourceGetter || requestHandler instanceof FileGetter;
if (null != refreshError && !resourceGetter) {
ctx.saveLocal();
handleException(refreshError, ctx, "Error refreshing app");
ActionContext.clearCurrent();
return;
}
NetworkJob job = new NetworkJob() {
@Override
public void run() {
Timer timer = Metric.NULL_METRIC.startTimer("null");
if (metric != Metric.NULL_METRIC) {
String key = S.concat(MetricInfo.HTTP_HANDLER, ":", requestHandler.toString());
timer = metric.startTimer(key);
}
ctx.saveLocal();
EventBus eventBus = app.eventBus();
try {
eventBus.emit(new PreHandle(ctx));
requestHandler.handle(ctx);
} catch (Result r) {
if (isError(r)) {
ctx.handler(FastRequestHandler.DUMB);
}
try {
r = RequestHandlerProxy.GLOBAL_AFTER_INTERCEPTOR.apply(r, ctx);
} catch (Exception e) {
logger.error(e, "Error calling global after interceptor");
r = ActErrorResult.of(e);
}
if (null == ctx.handler() || isError(r)) {
ctx.handler(FastRequestHandler.DUMB);
}
H.Format fmt = req.accept();
if (H.Format.UNKNOWN == fmt) {
fmt = req.contentType();
}
ctx.prepareRespForWrite().addHeaderIfNotAdded(H.Header.Names.CONTENT_TYPE, fmt.contentType());
r.apply(req, ctx.prepareRespForWrite());
} catch (Exception e) {
handleException(e, ctx, "Error handling network request");
} finally {
// we don't destroy ctx here in case it's been passed to
// another thread
eventBus.emit(new PostHandle(ctx));
ActionContext.clearCurrent();
timer.stop();
}
}
};
if (method.unsafe() || !requestHandler.express(ctx)) {
dispatcher.dispatch(job);
} else {
job.run();
}
}
use of org.osgl.mvc.result.Result in project actframework by actframework.
the class NetworkHandler method handleException.
private void handleException(Exception exception, final ActionContext ctx, String errorMessage) {
logger.error(exception, errorMessage);
Result r;
try {
r = RequestHandlerProxy.GLOBAL_EXCEPTION_INTERCEPTOR.apply(exception, ctx);
} catch (Exception e) {
logger.error(e, "Error calling global exception interceptor");
r = ActErrorResult.of(e);
}
if (null == r) {
r = ActErrorResult.of(exception);
} else if (r instanceof ErrorResult) {
r = ActErrorResult.of(r);
}
if (null == ctx.handler()) {
ctx.handler(FastRequestHandler.DUMB);
}
r.apply(ctx.req(), ctx.prepareRespForWrite());
}
use of org.osgl.mvc.result.Result in project actframework by actframework.
the class RenderAny method apply.
// TODO: Allow plugin to support rendering pdf, xls or other binary types
public void apply(ActionContext context) {
Boolean hasTemplate = context.hasTemplate();
if (null != hasTemplate && hasTemplate) {
RenderTemplate.get(context.successStatus()).apply(context);
return;
}
H.Format fmt = context.accept();
if (fmt == UNKNOWN) {
H.Request req = context.req();
H.Method method = req.method();
String methodInfo = S.concat(method.name(), " method to ");
String acceptHeader = req.header(H.Header.Names.ACCEPT);
throw E.unsupport(S.concat("Unknown accept content type(", acceptHeader, "): ", methodInfo, req.url()));
}
Result result = null;
if (JSON == fmt) {
List<String> varNames = context.__appRenderArgNames();
Map<String, Object> map = new HashMap<>(context.renderArgs());
if (null != varNames && !varNames.isEmpty()) {
for (String name : varNames) {
map.put(name, context.renderArg(name));
}
}
result = new RenderJSON(map);
} else if (XML == fmt) {
List<String> varNames = context.__appRenderArgNames();
Map<String, Object> map = new HashMap<>();
if (null != varNames && !varNames.isEmpty()) {
for (String name : varNames) {
map.put(name, context.renderArg(name));
}
}
result = new FilteredRenderXML(map, null, context);
} else if (HTML == fmt || TXT == fmt || CSV == fmt) {
if (!ignoreMissingTemplate) {
throw E.unsupport("Template[%s] not found", context.templatePath());
}
context.nullValueResultIgnoreRenderArgs().apply(context.req(), context.prepareRespForWrite());
return;
} else if (PDF == fmt || XLS == fmt || XLSX == fmt || DOC == fmt || DOCX == fmt) {
List<String> varNames = context.__appRenderArgNames();
if (null != varNames && !varNames.isEmpty()) {
Object firstVar = context.renderArg(varNames.get(0));
String action = S.str(context.actionPath()).afterLast(".").toString();
if (firstVar instanceof File) {
File file = (File) firstVar;
result = new RenderBinary(file, action);
} else if (firstVar instanceof InputStream) {
InputStream is = (InputStream) firstVar;
result = new RenderBinary(is, action);
} else if (firstVar instanceof ISObject) {
ISObject sobj = (ISObject) firstVar;
result = new RenderBinary(sobj.asInputStream(), action);
}
if (null == result) {
throw E.unsupport("Unknown render arg type [%s] for binary response", firstVar.getClass());
}
} else {
throw E.unexpected("No render arg found for binary response");
}
}
if (null != result) {
ActResponse<?> resp = context.prepareRespForWrite();
result.status(context.successStatus()).apply(context.req(), resp);
} else {
throw E.unexpected("Unknown accept content type: %s", fmt.contentType());
}
}
Aggregations