use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.
the class GenerateHashCodeStep method createStepNodeValue.
@Override
protected void createStepNodeValue(Document doc, Element stepNode) throws EngineException {
if (isEnabled()) {
try {
Engine.logBeans.info("Hashing file \"" + sourceFilePath + "\"");
File sourceFile = new File(sourceFilePath);
if (!sourceFile.exists()) {
throw new EngineException("Source file does not exist: " + sourceFilePath);
}
if (!sourceFile.isFile()) {
throw new EngineException("Source file is not a file: " + sourceFilePath);
}
if (currentOffset > sourceFile.length()) {
throw new EngineException("The currentOffset of " + currentOffset + "(/" + sourceFile.length() + ") for the file: " + sourceFilePath);
}
try (FileInputStream fis = new FileInputStream(sourceFile)) {
String hash = null;
if (currentOffset > 0) {
Engine.logBeans.debug("Skipping " + currentOffset + " bytes of the file \"" + sourceFilePath + "\" before hash.");
fis.skip(currentOffset);
}
switch(hashAlgorithm) {
case MD5:
hash = DigestUtils.md5Hex(fis);
break;
case SHA1:
hash = DigestUtils.sha1Hex(fis);
break;
}
Engine.logBeans.info("File \"" + sourceFilePath + "\" has been hashed.");
Node text = doc.createTextNode(hash);
stepNode.appendChild(text);
}
} catch (Exception e) {
setErrorStatus(true);
throw new EngineException("Unable to compute hash code", e);
}
}
}
use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.
the class MoveFileStep method configure.
@Override
public void configure(Element element) throws Exception {
super.configure(element);
String version = element.getAttribute("version");
if (version == null) {
String s = XMLUtils.prettyPrintDOM(element);
EngineException ee = new EngineException("Unable to find version number for the database object \"" + getName() + "\".\n" + "XML data: " + s);
throw ee;
}
if (VersionUtils.compareMigrationVersion(version, ".m003") < 0) {
if (!dataFile.equals(""))
dataFile = "'" + dataFile + "'";
if (!newFilename.equals(""))
newFilename = "'" + newFilename + "'";
hasChanged = true;
Engine.logBeans.warn("[MoveFileStep] The object \"" + getName() + "\" has been updated to .m003 version");
}
}
use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.
the class IfFileExistStep method evaluateStep.
@Override
protected boolean evaluateStep(Context javascriptContext, Scriptable scope) throws EngineException {
try {
String sourceFilePath = getAbsoluteFilePath(evaluateSourcePath(javascriptContext, scope));
File sourcefile = new File(sourceFilePath);
if (sourcefile.exists()) {
Engine.logBeans.info("File '" + sourceFilePath + "' exists");
return true;
} else {
Engine.logBeans.info("File '" + sourceFilePath + "' does not exist");
return false;
}
} catch (Exception e) {
setErrorStatus(true);
Engine.logBeans.error("An error occured while testing if the file or directory exists.", e);
}
return false;
}
use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.
the class ReverseProxyServlet method doRequest.
/**
* Executes the {@link HttpMethod} passed in and sends the proxy response
* back to the client via the given {@link HttpServletResponse}
*
* @param httpMethodProxyRequest
* An object representing the proxy request to be made
* @param httpServletResponse
* An object by which we can send the proxied response back to
* the client
* @throws IOException
* Can be thrown by the {@link HttpClient}.executeMethod
* @throws ServletException
* Can be thrown to indicate that another error has occurred
* @throws EngineException
*/
private void doRequest(HttpMethodType httpMethodType, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
try {
Engine.logEngine.debug("(ReverseProxyServlet) Starting request handling");
if (Boolean.parseBoolean(EnginePropertiesManager.getProperty(PropertyName.SSL_DEBUG))) {
System.setProperty("javax.net.debug", "all");
Engine.logEngine.trace("(ReverseProxyServlet) Enabling SSL debug mode");
} else {
System.setProperty("javax.net.debug", "");
Engine.logEngine.debug("(ReverseProxyServlet) Disabling SSL debug mode");
}
String baseUrl;
String projectName;
String connectorName;
String contextName;
String extraPath;
{
String requestURI = httpServletRequest.getRequestURI();
Engine.logEngine.trace("(ReverseProxyServlet) Requested URI : " + requestURI);
Matcher m = reg_fields.matcher(requestURI);
if (m.matches() && m.groupCount() >= 5) {
baseUrl = m.group(1);
projectName = m.group(2);
connectorName = m.group(3);
contextName = m.group(4);
extraPath = m.group(5);
} else {
throw new MalformedURLException("The request doesn't contains needed fields : projectName, connectorName and contextName");
}
}
String sessionID = httpServletRequest.getSession().getId();
Engine.logEngine.debug("(ReverseProxyServlet) baseUrl : " + baseUrl + " ; projectName : " + projectName + " ; connectorName : " + connectorName + " ; contextName : " + contextName + " ; extraPath : " + extraPath + " ; sessionID : " + sessionID);
Context context = Engine.theApp.contextManager.get(null, contextName, sessionID, null, projectName, connectorName, null);
Project project = Engine.theApp.databaseObjectsManager.getProjectByName(projectName);
context.projectName = projectName;
context.project = project;
ProxyHttpConnector proxyHttpConnector = (ProxyHttpConnector) project.getConnectorByName(connectorName);
context.connector = proxyHttpConnector;
context.connectorName = proxyHttpConnector.getName();
HostConfiguration hostConfiguration = proxyHttpConnector.hostConfiguration;
// Proxy configuration
String proxyServer = Engine.theApp.proxyManager.getProxyServer();
String proxyUser = Engine.theApp.proxyManager.getProxyUser();
String proxyPassword = Engine.theApp.proxyManager.getProxyPassword();
int proxyPort = Engine.theApp.proxyManager.getProxyPort();
if (!proxyServer.equals("")) {
hostConfiguration.setProxy(proxyServer, proxyPort);
Engine.logEngine.debug("(ReverseProxyServlet) Using proxy: " + proxyServer + ":" + proxyPort);
} else {
// Remove old proxy configuration
hostConfiguration.setProxyHost(null);
}
String targetHost = proxyHttpConnector.getServer();
Engine.logEngine.debug("(ReverseProxyServlet) Target host: " + targetHost);
int targetPort = proxyHttpConnector.getPort();
Engine.logEngine.debug("(ReverseProxyServlet) Target port: " + targetPort);
// Configuration SSL
Engine.logEngine.debug("(ReverseProxyServlet) Https: " + proxyHttpConnector.isHttps());
CertificateManager certificateManager = proxyHttpConnector.certificateManager;
boolean trustAllServerCertificates = proxyHttpConnector.isTrustAllServerCertificates();
if (proxyHttpConnector.isHttps()) {
Engine.logEngine.debug("(ReverseProxyServlet) Setting up SSL properties");
certificateManager.collectStoreInformation(context);
Engine.logEngine.debug("(ReverseProxyServlet) CertificateManager has changed: " + certificateManager.hasChanged);
if (certificateManager.hasChanged || (!targetHost.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != targetPort)) {
Engine.logEngine.debug("(ReverseProxyServlet) Using MySSLSocketFactory for creating the SSL socket");
Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, trustAllServerCertificates), targetPort);
hostConfiguration.setHost(targetHost, targetPort, myhttps);
}
Engine.logEngine.debug("(ReverseProxyServlet) Updated host configuration for SSL purposes");
} else {
hostConfiguration.setHost(targetHost, targetPort);
}
HttpMethod httpMethodProxyRequest;
String targetPath = proxyHttpConnector.getBaseDir() + extraPath;
// Handle the query string
if (httpServletRequest.getQueryString() != null) {
targetPath += "?" + httpServletRequest.getQueryString();
}
Engine.logEngine.debug("(ReverseProxyServlet) Target path: " + targetPath);
Engine.logEngine.debug("(ReverseProxyServlet) Requested method: " + httpMethodType);
if (httpMethodType == HttpMethodType.GET) {
// Create a GET request
httpMethodProxyRequest = new GetMethod();
} else if (httpMethodType == HttpMethodType.POST) {
// Create a standard POST request
httpMethodProxyRequest = new PostMethod();
((PostMethod) httpMethodProxyRequest).setRequestEntity(new InputStreamRequestEntity(httpServletRequest.getInputStream()));
} else {
throw new IllegalArgumentException("Unknown HTTP method: " + httpMethodType);
}
String charset = httpMethodProxyRequest.getParams().getUriCharset();
URI targetURI;
try {
targetURI = new URI(targetPath, true, charset);
} catch (URIException e) {
// Bugfix #1484
String newTargetPath = "";
for (String part : targetPath.split("&")) {
if (!newTargetPath.equals("")) {
newTargetPath += "&";
}
String[] pair = part.split("=");
try {
newTargetPath += URLDecoder.decode(pair[0], "UTF-8") + "=" + (pair.length > 1 ? URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8") : "");
} catch (UnsupportedEncodingException ee) {
newTargetPath = targetPath;
}
}
targetURI = new URI(newTargetPath, true, charset);
}
httpMethodProxyRequest.setURI(targetURI);
// Tells the method to automatically handle authentication.
httpMethodProxyRequest.setDoAuthentication(true);
HttpState httpState = getHttpState(proxyHttpConnector, context);
String basicUser = proxyHttpConnector.getAuthUser();
String basicPassword = proxyHttpConnector.getAuthPassword();
String givenBasicUser = proxyHttpConnector.getGivenAuthUser();
String givenBasicPassword = proxyHttpConnector.getGivenAuthPassword();
// Basic authentication configuration
String realm = null;
if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) {
String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser);
String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword);
httpState.setCredentials(new AuthScope(targetHost, targetPort, realm), new UsernamePasswordCredentials(userName, userPassword));
Engine.logEngine.debug("(ReverseProxyServlet) Credentials: " + userName + ":******");
}
// Setting basic authentication for proxy
if (!proxyServer.equals("") && !proxyUser.equals("")) {
httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));
Engine.logEngine.debug("(ReverseProxyServlet) Proxy credentials: " + proxyUser + ":******");
}
// Forward the request headers
setProxyRequestHeaders(httpServletRequest, httpMethodProxyRequest, proxyHttpConnector);
// Use the CEMS HttpClient
HttpClient httpClient = Engine.theApp.httpClient;
httpMethodProxyRequest.setFollowRedirects(false);
// Execute the request
int intProxyResponseCode = httpClient.executeMethod(hostConfiguration, httpMethodProxyRequest, httpState);
// Hooray for open source software
if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES && /* 300 */
intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED) /* 304 */
{
String stringStatusCode = Integer.toString(intProxyResponseCode);
String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
if (stringLocation == null) {
throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response");
}
// Modify the redirect to go to this proxy servlet rather that
// the
// proxied host
String redirect = handleRedirect(stringLocation, baseUrl, proxyHttpConnector);
httpServletResponse.sendRedirect(redirect);
Engine.logEngine.debug("(ReverseProxyServlet) Send redirect (" + redirect + ")");
return;
} else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
// 304 needs special handling. See:
// http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
// We get a 304 whenever passed an 'If-Modified-Since'
// header and the data on disk has not changed; server
// responds w/ a 304 saying I'm not going to send the
// body because the file has not changed.
httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
Engine.logEngine.debug("(ReverseProxyServlet) NOT MODIFIED (304)");
return;
}
// Pass the response code back to the client
httpServletResponse.setStatus(intProxyResponseCode);
// Pass response headers back to the client
Engine.logEngine.debug("(ReverseProxyServlet) Response headers back to the client:");
Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
for (Header header : headerArrayResponse) {
String headerName = header.getName();
String headerValue = header.getValue();
if (!headerName.equalsIgnoreCase("Transfer-Encoding") && !headerName.equalsIgnoreCase("Set-Cookie")) {
httpServletResponse.setHeader(headerName, headerValue);
Engine.logEngine.debug(" " + headerName + "=" + headerValue);
}
}
String contentType = null;
Header[] contentTypeHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Type");
for (Header contentTypeHeader : contentTypeHeaders) {
contentType = contentTypeHeader.getValue();
break;
}
String pageCharset = "UTF-8";
if (contentType != null) {
int iCharset = contentType.indexOf("charset=");
if (iCharset != -1) {
pageCharset = contentType.substring(iCharset + "charset=".length()).trim();
}
Engine.logEngine.debug("(ReverseProxyServlet) Using charset: " + pageCharset);
}
InputStream siteIn = httpMethodProxyRequest.getResponseBodyAsStream();
// Handle gzipped content
Header[] contentEncodingHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Encoding");
boolean bGZip = false, bDeflate = false;
for (Header contentEncodingHeader : contentEncodingHeaders) {
HeaderElement[] els = contentEncodingHeader.getElements();
for (int j = 0; j < els.length; j++) {
if ("gzip".equals(els[j].getName())) {
Engine.logBeans.debug("(ReverseProxyServlet) Decode GZip stream");
siteIn = new GZIPInputStream(siteIn);
bGZip = true;
} else if ("deflate".equals(els[j].getName())) {
Engine.logBeans.debug("(ReverseProxyServlet) Decode Deflate stream");
siteIn = new InflaterInputStream(siteIn, new Inflater(true));
bDeflate = true;
}
}
}
byte[] bytesDataResult;
ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
// String resourceUrl = projectName + targetPath;
String t = context.statistics.start(EngineStatistics.APPLY_USER_REQUEST);
try {
// Read either from the cache, either from the remote server
// InputStream is = proxyCacheManager.getResource(resourceUrl);
// if (is != null) {
// Engine.logEngine.debug("(ReverseProxyServlet) Getting data from cache");
// siteIn = is;
// }
int c = siteIn.read();
while (c > -1) {
baos.write(c);
c = siteIn.read();
}
// if (is != null) is.close();
} finally {
context.statistics.stop(t, true);
}
bytesDataResult = baos.toByteArray();
baos.close();
Engine.logEngine.debug("(ReverseProxyServlet) Data retrieved!");
// if (isDynamicContent(httpServletRequest.getPathInfo(),
// proxyHttpConnector.getDynamicContentFiles())) {
Engine.logEngine.debug("(ReverseProxyServlet) Dynamic content");
bytesDataResult = handleStringReplacements(baseUrl, contentType, pageCharset, proxyHttpConnector, bytesDataResult);
String billingClassName = context.getConnector().getBillingClassName();
if (billingClassName != null) {
try {
Engine.logContext.debug("Billing class name required: " + billingClassName);
AbstractBiller biller = (AbstractBiller) Class.forName(billingClassName).getConstructor().newInstance();
Engine.logContext.debug("Executing the biller");
biller.insertBilling(context);
} catch (Throwable e) {
Engine.logContext.warn("Unable to execute the biller (the billing is thus ignored): [" + e.getClass().getName() + "] " + e.getMessage());
}
}
// Send the content to the client
if (Engine.logEngine.isDebugEnabled() && MimeType.Html.is(contentType)) {
Engine.logEngine.debug("Data proxied:\n" + new String(bytesDataResult, pageCharset));
}
if (bGZip || bDeflate) {
baos = new ByteArrayOutputStream();
OutputStream compressedOutputStream = bGZip ? new GZIPOutputStream(baos) : new DeflaterOutputStream(baos, new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true));
compressedOutputStream.write(bytesDataResult);
compressedOutputStream.close();
bytesDataResult = baos.toByteArray();
baos.close();
}
httpServletResponse.setContentLength(bytesDataResult.length);
OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
outputStreamClientResponse.write(bytesDataResult);
Engine.logEngine.debug("(ReverseProxyServlet) End of document retransmission");
} catch (Exception e) {
Engine.logEngine.error("Error while trying to proxy page", e);
throw new ServletException("Error while trying to proxy page", e);
}
}
use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.
the class ServletRequester method preGetDocument.
public void preGetDocument() throws EngineException {
HttpServletRequest request = (HttpServletRequest) inputData;
HttpUtils.checkCV(request);
String remoteAddr = request.getRemoteAddr();
Engine.logContext.info("Remote-Addr: \"" + remoteAddr + "\"");
context.remoteAddr = remoteAddr;
Log4jHelper.mdcPut(mdcKeys.ClientIP, remoteAddr);
String remoteHost = "-";
context.remoteHost = remoteHost;
if (EnginePropertiesManager.getProperty(PropertyName.NET_REVERSE_DNS).equalsIgnoreCase("true")) {
remoteHost = request.getRemoteHost();
if (remoteHost != null) {
context.remoteHost = remoteHost;
Log4jHelper.mdcPut(mdcKeys.ClientHostName, context.remoteHost);
Engine.logContext.info("Remote-Host: \"" + remoteHost + "\"");
}
}
String contextID = context.contextID;
Engine.logContext.debug("Context ID: " + contextID);
String requestURI = request.getRequestURI();
Engine.logContext.debug("Request URI: " + requestURI);
String servletPath = request.getServletPath();
Engine.logContext.debug("Servlet path: " + servletPath);
context.servletPath = servletPath;
String queryString = request.getQueryString();
Engine.logContext.info("Query string: " + queryString);
String userAgent = request.getHeader(HeaderName.UserAgent.value());
Engine.logContext.info("User-Agent: \"" + userAgent + "\"");
context.userAgent = userAgent;
try {
HttpSessionListener.checkSession(request);
} catch (Throwable e) {
throw new EngineException(e.getMessage(), e);
}
}
Aggregations