use of com.dexels.navajo.script.api.FatalException in project navajo by Dexels.
the class ServiceCommand method performCall.
protected Navajo performCall(ArticleRuntime runtime, String name, Navajo n, String instance) throws APIException {
try {
Navajo result = dispatcher.handle(n, instance, true);
handleError(result);
return result;
} catch (UserException | AuthorizationException | FatalException e) {
throw new APIException(e.getMessage(), e, APIErrorCode.InternalError);
} catch (ConditionErrorException e) {
throw new APIException(e.getMessage(), e, APIErrorCode.ConditionError);
}
}
use of com.dexels.navajo.script.api.FatalException in project navajo by Dexels.
the class Dispatcher method generateErrorMessage.
/**
* Generate a Navajo error message and log the error to the Database.
*/
@Override
public final Navajo generateErrorMessage(Access access, String message, int code, int level, Throwable t) throws FatalException {
if (message == null) {
message = "Null pointer exception";
}
if (t != null) {
logger.error("Generating error message for: ", t);
}
try {
Navajo outMessage = NavajoFactory.getInstance().createNavajo();
// Make sure empty Header is constructed
Header h = NavajoFactory.getInstance().createHeader(outMessage, "", "", "", -1);
outMessage.addHeader(h);
Message errorMessage = NavajoFactory.getInstance().createMessage(outMessage, Constants.ERROR_MESSAGE);
outMessage.addMessage(errorMessage);
Property prop = NavajoFactory.getInstance().createProperty(outMessage, "message", Property.STRING_PROPERTY, message, 200, "Message", Property.DIR_OUT);
errorMessage.addProperty(prop);
prop = NavajoFactory.getInstance().createProperty(outMessage, "code", Property.INTEGER_PROPERTY, code + "", 100, "Code", Property.DIR_OUT);
errorMessage.addProperty(prop);
prop = NavajoFactory.getInstance().createProperty(outMessage, "level", Property.INTEGER_PROPERTY, level + "", 100, "Level", Property.DIR_OUT);
errorMessage.addProperty(prop);
if (access != null) {
prop = NavajoFactory.getInstance().createProperty(outMessage, "access_id", Property.STRING_PROPERTY, access.accessID + "", 100, "Access id", Property.DIR_OUT);
errorMessage.addProperty(prop);
access.setException(t);
}
if (access != null) {
access.setOutputDoc(outMessage);
}
return outMessage;
} catch (Exception e) {
throw new FatalException(e.getMessage(), e);
}
}
use of com.dexels.navajo.script.api.FatalException in project navajo by Dexels.
the class TmlHttpServlet method doPost.
/**
* Handle a request.
*
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
MDC.clear();
Date created = new java.util.Date();
long start = created.getTime();
String sendEncoding = request.getHeader("Accept-Encoding");
String recvEncoding = request.getHeader("Content-Encoding");
if (sendEncoding != null) {
MDC.put("Accept-Encoding", sendEncoding);
}
if (recvEncoding != null) {
MDC.put("Content-Encoding", recvEncoding);
}
DispatcherInterface dis = null;
BufferedReader r = null;
BufferedWriter out = null;
try {
Navajo in = null;
if (streamingMode) {
if (sendEncoding != null && sendEncoding.equals(COMPRESS_JZLIB)) {
r = new BufferedReader(new java.io.InputStreamReader(new InflaterInputStream(request.getInputStream()), "UTF-8"));
} else if (sendEncoding != null && sendEncoding.equals(COMPRESS_GZIP)) {
r = new BufferedReader(new java.io.InputStreamReader(new java.util.zip.GZIPInputStream(request.getInputStream()), "UTF-8"));
} else {
r = new BufferedReader(request.getReader());
}
in = NavajoFactory.getInstance().createNavajo(r);
r.close();
r = null;
} else {
logger.info("Warning: Using non-streaming mode for " + request.getRequestURI() + ", file written: " + logfileIndex + ", total size: " + bytesWritten);
InputStream is = request.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
copyResource(bos, is);
is.close();
bos.close();
byte[] bytes = bos.toByteArray();
try {
if (sendEncoding != null && sendEncoding.equals(COMPRESS_JZLIB)) {
r = new BufferedReader(new java.io.InputStreamReader(new InflaterInputStream(new ByteArrayInputStream(bytes)), "UTF-8"));
} else if (sendEncoding != null && sendEncoding.equals(COMPRESS_GZIP)) {
r = new BufferedReader(new java.io.InputStreamReader(new java.util.zip.GZIPInputStream(new ByteArrayInputStream(bytes)), "UTF-8"));
} else {
r = new BufferedReader(new java.io.InputStreamReader(new ByteArrayInputStream(bytes), "UTF-8"));
}
in = NavajoFactory.getInstance().createNavajo(r);
if (in == null) {
throw new Exception("Invalid Navajo");
}
r.close();
r = null;
} catch (Throwable t) {
// Write request to temp file.
File f = DispatcherFactory.getInstance().getTempDir();
if (f != null) {
bytesWritten += bytes.length;
logfileIndex++;
FileOutputStream fos = new FileOutputStream(new File(f, "request-" + logfileIndex));
copyResource(fos, new ByteArrayInputStream(bytes));
fos.close();
PrintWriter fw = new PrintWriter(new FileWriter(new File(f, "exception-" + logfileIndex)));
t.printStackTrace(fw);
fw.flush();
fw.close();
}
dumHttp(request, logfileIndex, f);
throw new ServletException(t);
}
}
long stamp = System.currentTimeMillis();
int pT = (int) (stamp - start);
if (in == null) {
throw new ServletException("Invalid request.");
}
Header header = in.getHeader();
if (header == null) {
throw new ServletException("Empty Navajo header.");
}
dis = DispatcherFactory.getInstance();
if (dis == null) {
System.err.println("SERIOUS: No dispatcher found. The navajo context did not initialize properly, check the logs to find out why!");
return;
}
// Check for certificate.
Object certObject = request.getAttribute("javax.servlet.request.X509Certificate");
// Call Dispatcher with parsed TML document as argument.
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.equals("")) {
ip = request.getRemoteAddr();
}
ClientInfo clientInfo = new ClientInfo(ip, "unknown", recvEncoding, pT, (recvEncoding != null && (recvEncoding.equals(COMPRESS_GZIP) || recvEncoding.equals(COMPRESS_JZLIB))), (sendEncoding != null && (sendEncoding.equals(COMPRESS_GZIP) || sendEncoding.equals(COMPRESS_JZLIB))), request.getContentLength(), created);
String instance = determineInstanceFromRequest(request);
Navajo outDoc = handleTransaction(instance, dis, in, certObject, clientInfo);
response.setContentType("text/xml; charset=UTF-8");
response.setHeader("Accept-Ranges", "none");
if (recvEncoding != null && recvEncoding.equals(COMPRESS_JZLIB)) {
response.setHeader("Content-Encoding", COMPRESS_JZLIB);
out = new BufferedWriter(new OutputStreamWriter(new DeflaterOutputStream(response.getOutputStream()), "UTF-8"));
} else if (recvEncoding != null && recvEncoding.equals(COMPRESS_GZIP)) {
response.setHeader("Content-Encoding", COMPRESS_GZIP);
out = new BufferedWriter(new OutputStreamWriter(new java.util.zip.GZIPOutputStream(response.getOutputStream()), "UTF-8"));
} else {
out = new BufferedWriter(response.getWriter());
}
outDoc.write(out);
out.flush();
out.close();
if (in.getHeader() != null && outDoc.getHeader() != null && !Dispatcher.isSpecialwebservice(in.getHeader().getRPCName())) {
statLogger.info("Finished {} ({}) in {}ms", outDoc.getHeader().getHeaderAttribute("accessId"), in.getHeader().getRPCName(), (System.currentTimeMillis() - start));
}
out = null;
} catch (Throwable e) {
logger.error("Error: ", e);
dumHttp(request, -1, null);
if (e instanceof FatalException) {
FatalException fe = (FatalException) e;
if (fe.getMessage().equals("500.13")) {
// Server too busy.
throw new ServletException("500.13", e);
}
}
throw new ServletException(e);
} finally {
dis = null;
if (r != null) {
try {
r.close();
} catch (Exception e) {
// NOT INTERESTED.
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) {
// NOT INTERESTED.
}
}
}
}
use of com.dexels.navajo.script.api.FatalException in project navajo by Dexels.
the class Dispatcher method generateAuthorizationErrorMessage.
/**
* Generate a Navajo authorization error response.
*
* @param access
* Beware, might be null
* @param ae
* @return
* @throws FatalException
*/
private final Navajo generateAuthorizationErrorMessage(Access access, AuthorizationException ae, String rpcName) throws FatalException {
try {
Navajo outMessage = NavajoFactory.getInstance().createNavajo();
// Make sure empty Header is constructed
Header h = NavajoFactory.getInstance().createHeader(outMessage, "", "", "", -1);
outMessage.addHeader(h);
Message errorMessage = NavajoFactory.getInstance().createMessage(outMessage, (ae.isNotAuthorized() ? AuthorizationException.AUTHORIZATION_ERROR_MESSAGE : AuthorizationException.AUTHENTICATION_ERROR_MESSAGE));
outMessage.addMessage(errorMessage);
Property prop = NavajoFactory.getInstance().createProperty(outMessage, "Message", Property.STRING_PROPERTY, ae.getMessage(), 0, "Message", Property.DIR_OUT);
errorMessage.addProperty(prop);
prop = NavajoFactory.getInstance().createProperty(outMessage, "User", Property.STRING_PROPERTY, ae.getUser(), 0, "User", Property.DIR_OUT);
errorMessage.addProperty(prop);
prop = NavajoFactory.getInstance().createProperty(outMessage, "Webservice", Property.STRING_PROPERTY, rpcName, 0, "User", Property.DIR_OUT);
errorMessage.addProperty(prop);
if (access != null) {
access.setException(ae);
access.setOutputDoc(outMessage);
}
return outMessage;
} catch (Exception e) {
throw new FatalException(e.getMessage(), e);
}
}
use of com.dexels.navajo.script.api.FatalException in project navajo by Dexels.
the class Dispatcher method processNavajo.
/**
* Handle a webservice.
*
* @param inMessage
* @param userCertificate
* @param clientInfo
* @param origRunnable
* @param skipAuth
* , always skip authorization part.
* @return
* @throws FatalException
*/
private final Navajo processNavajo(Navajo inMessage, String instance, Object userCertificate, ClientInfo clientInfo, boolean skipAuth, TmlRunnable origRunnable, AfterWebServiceEmitter emit) throws FatalException {
Access access = null;
Navajo outMessage = null;
String rpcName = "";
String rpcUser = "";
String rpcPassword = "";
Throwable myException = null;
String origThreadName = null;
boolean scheduledWebservice = false;
boolean afterWebServiceActivated = false;
int accessSetSize = accessSet.size();
setRequestRate(clientInfo, accessSetSize);
Navajo result = handleCallbackPointers(inMessage, instance);
if (result != null) {
return result;
}
Header header = inMessage.getHeader();
rpcName = header.getRPCName();
rpcUser = header.getRPCUser();
rpcPassword = header.getRPCPassword();
boolean preventFinalize = false;
try {
/**
* Phase II: Authorisation/Authentication of the user. Is the user
* known and valid and may it use the specified service? Also log
* the access.
*/
long startAuth = System.currentTimeMillis();
if (rpcName == null) {
throw new FatalException("No script defined");
}
if (rpcName.equals("navajo_ping")) {
// Ping!
outMessage = NavajoFactory.getInstance().createNavajo();
Header h = NavajoFactory.getInstance().createHeader(outMessage, "", "", "", -1);
outMessage.addHeader(h);
return outMessage;
}
access = new Access(1, 1, rpcUser, rpcName, "", "", "", userCertificate, false, null);
access.setTenant(instance);
access.rpcPwd = rpcPassword;
access.setInDoc(inMessage);
access.setClientDescription(header.getHeaderAttribute("clientdescription"));
access.setApplication(header.getHeaderAttribute("application"));
access.setOrganization(header.getHeaderAttribute("organization"));
if (clientInfo != null) {
access.ipAddress = clientInfo.getIP();
access.hostName = clientInfo.getHost();
}
NavajoEventRegistry.getInstance().publishEvent(new NavajoRequestEvent(access));
appendGlobals(inMessage, instance);
if (useAuthorisation && !skipAuth) {
try {
if (navajoConfig == null) {
throw new FatalException("EMPTY NAVAJOCONFIG, INVALID STATE OF DISPATCHER!");
}
// if (instance == null) {
// throw new SystemException(-1, "No tenant set -cannot authenticate!");
// }
// Determine authenticator
final AuthenticationMethod authenticator;
if (clientInfo == null) {
authenticator = authMethodBuilder.getInstanceForRequest(null);
} else {
authenticator = authMethodBuilder.getInstanceForRequest(clientInfo.getAuthHeader());
}
if (authenticator == null) {
throw new FatalException("Missing authenticator");
}
authenticator.process(access);
} catch (AuthorizationException ex) {
outMessage = generateAuthorizationErrorMessage(access, ex, rpcName);
AuditLog.log(AuditLog.AUDIT_MESSAGE_AUTHORISATION, "(service=" + rpcName + ", user=" + rpcUser + ", message=" + ex.getMessage(), Level.WARNING);
access.setExitCode(Access.EXIT_AUTH_EXECPTION);
return outMessage;
}/*catch (SystemException se) { //
logger.error("SystemException on authenticateUser {} for {}: ", rpcUser, rpcName, se);
outMessage = generateErrorMessage(access, se.getMessage(), SystemException.NOT_AUTHORISED, 1, new Exception("NOT AUTHORISED"));
AuditLog.log(AuditLog.AUDIT_MESSAGE_AUTHORISATION, "(service=" + rpcName + ", user=" + rpcUser + ", message=" + se.getMessage(),
Level.WARNING);
access.setExitCode(Access.EXIT_AUTH_EXECPTION);
return outMessage;
}*/
catch (Throwable t) {
logger.error("Unexpected exception on authenticateUser {} for {}: ", rpcUser, rpcName, t);
outMessage = generateErrorMessage(access, t.getMessage(), SystemException.NOT_AUTHORISED, 1, new Exception("NOT AUTHORISED"));
access.setExitCode(Access.EXIT_AUTH_EXECPTION);
access.setException(t);
return outMessage;
}
}
if (clientInfo != null) {
access.ipAddress = clientInfo.getIP();
access.hostName = clientInfo.getHost();
access.parseTime = clientInfo.getParseTime();
access.queueTime = clientInfo.getQueueTime();
access.requestEncoding = clientInfo.getEncoding();
access.compressedReceive = clientInfo.isCompressedRecv();
access.compressedSend = clientInfo.isCompressedSend();
access.contentLength = clientInfo.getContentLength();
access.created = clientInfo.getCreated();
access.queueId = clientInfo.getQueueId();
access.queueSize = clientInfo.getQueueSize();
// Set the name of this thread.
origThreadName = Thread.currentThread().getName();
Thread.currentThread().setName(getThreadName(access));
}
final GlobalManager gm;
if (instance != null) {
gm = globalManagers.get(instance);
} else {
gm = globalManagers.get("default");
}
if (gm != null) {
gm.initGlobals(inMessage);
}
if (origRunnable != null) {
access.setOriginalRunnable(origRunnable);
// and vice versa, for the endTransaction
origRunnable.setAttribute("access", access);
}
String fullLog = inMessage.getHeader().getHeaderAttribute("fullLog");
if ("true".equals(fullLog)) {
logger.info("Full debug detected. Accesshash: {}", access.hashCode());
access.setDebugAll(true);
}
if ((access.userID == -1) || (access.serviceID == -1)) {
// ACCESS NOTGRANTED.
String errorMessage = "";
if (access.userID == -1) {
errorMessage = "Cannot authenticate user: " + rpcUser;
} else {
errorMessage = "Cannot authorise use of: " + rpcName;
}
outMessage = generateErrorMessage(access, errorMessage, SystemException.NOT_AUTHORISED, 1, new Exception("NOT AUTHORISED"));
return outMessage;
} else {
// ACCESS GRANTED.
access.authorisationTime = (int) (System.currentTimeMillis() - startAuth);
accessSet.add(access);
// username might've changed as the username might've been a placeholder while we're authenticating using a bearer token
rpcUser = access.getRpcUser();
// Be very defensive not to add null values to the MDC, as they will fail at unexpected moments
if (access.accessID != null) {
MDC.put("accessId", access.accessID);
}
if (access.getRpcName() != null) {
MDC.put("rpcName", access.getRpcName());
}
if (access.getRpcUser() != null) {
MDC.put("rpcUser", access.getRpcUser());
}
if (access.getTenant() != null) {
MDC.put("tenant", access.getTenant());
}
if (getNavajoConfig().getRootPath() != null) {
MDC.put("rootPath", getNavajoConfig().getRootPath());
}
if (getNavajoConfig().getInstanceName() != null) {
MDC.put("instanceName", getNavajoConfig().getInstanceName());
}
if (getNavajoConfig().getInstanceGroup() != null) {
MDC.put("instanceGroup", getNavajoConfig().getInstanceGroup());
}
if (inMessage.getHeader().getSchedule() != null && !inMessage.getHeader().getSchedule().equals("")) {
if (validTimeSpecification(inMessage.getHeader().getSchedule())) {
scheduledWebservice = true;
logger.info("Scheduling webservice: {} on {} ", inMessage.getHeader().getRPCName(), inMessage.getHeader().getSchedule());
TaskRunnerInterface trf = TaskRunnerFactory.getInstance();
TaskInterface ti = trf.createTask();
try {
ti.setTrigger(inMessage.getHeader().getSchedule());
ti.setNavajo(inMessage);
// Make sure task gets persisted in tasks.xml
ti.setPersisted(true);
if (inMessage.getHeader().getHeaderAttribute("keeprequestresponse") != null && inMessage.getHeader().getHeaderAttribute("keeprequestresponse").equals("true")) {
ti.setKeepRequestResponse(true);
}
trf.addTask(ti);
outMessage = generateScheduledMessage(inMessage.getHeader(), ti.getId(), false);
} catch (TriggerException e) {
logger.info("WARNING: Invalid trigger specified for task {}: {}", ti.getId(), inMessage.getHeader().getSchedule());
trf.removeTask(ti);
outMessage = generateErrorMessage(access, "Could not schedule task:" + e.getMessage(), -1, -1, e);
}
} else {
// obsolete time specification
outMessage = generateScheduledMessage(inMessage.getHeader(), null, true);
}
} else {
/**
* Phase VI: Dispatch to proper servlet.
*/
// Create beforeWebservice event.
access.setInDoc(inMessage);
long bstart = System.currentTimeMillis();
Navajo useProxy = (WebserviceListenerFactory.getInstance() != null ? WebserviceListenerFactory.getInstance().beforeWebservice(rpcName, access) : null);
access.setBeforeServiceTime((int) (System.currentTimeMillis() - bstart));
if (useAuthorisation) {
if (useProxy == null) {
outMessage = dispatch(access);
} else {
rpcName = access.rpcName;
outMessage = useProxy;
}
} else {
throw new UnsupportedOperationException("I've removed this code because I assumed it wasn't used any more");
}
}
}
} catch (AuthorizationException aee) {
outMessage = generateAuthorizationErrorMessage(access, aee, rpcName);
AuditLog.log(AuditLog.AUDIT_MESSAGE_AUTHORISATION, "(service=" + rpcName + ", user=" + rpcUser + ", message=" + aee.getMessage() + ")", Level.WARNING);
myException = aee;
access.setExitCode(Access.EXIT_AUTH_EXECPTION);
return outMessage;
} catch (UserException ue) {
try {
outMessage = generateErrorMessage(access, ue.getMessage(), ue.code, 1, (ue.getCause() != null ? ue.getCause() : ue));
myException = ue;
return outMessage;
} catch (Exception ee) {
logger.error("Error: ", ee);
myException = ee;
return errorHandler(access, ee, inMessage);
}
} catch (SystemException se) {
logger.error("Error: ", se);
myException = se;
try {
outMessage = generateErrorMessage(access, se.getMessage(), se.code, 1, (se.getCause() != null ? se.getCause() : se));
return outMessage;
} catch (Exception ee) {
logger.error("Error: ", ee);
return errorHandler(access, ee, inMessage);
}
} catch (Throwable e) {
logger.error("Error: ", e);
myException = e;
return errorHandler(access, e, inMessage);
} finally {
if (!preventFinalize) {
finalizeService(inMessage, access, rpcName, rpcUser, myException, origThreadName, scheduledWebservice, afterWebServiceActivated, emit);
}
}
return access.getOutputDoc();
}
Aggregations