use of com.twinsoft.convertigo.engine.util.LogWrapper in project convertigo by convertigo.
the class JavelinConnector method prepareForTransaction.
@Override
public void prepareForTransaction(Context context) throws EngineException {
String t = context.statistics.start(EngineStatistics.GET_JAVELIN_OBJECT);
try {
// Quick and dirty workaround for ticket #1280
if (!checkKeys())
throw new EngineException("No more key available; check your license keys!");
// if something append during transaction execution
com.twinsoft.api.Session session = Engine.theApp.sessionManager.getSession(context.contextID);
if (session != null)
session.resetSomethingChange();
if (Engine.isStudioMode()) {
if (javelin != null) {
Engine.logBeans.debug("(JavelinConnector) Using the studio Javelin object");
return;
}
throw new EngineException("Studio mode: the Legacy connector must be open in order to execute transactions");
}
Engine.logBeans.debug("(JavelinConnector) Retrieving the Javelin object");
JavelinTransaction javelinTransaction = null;
try {
javelinTransaction = (JavelinTransaction) context.requestedObject;
} catch (ClassCastException e) {
throw new EngineException("Requested object is not a transaction", e);
}
int timeout = javelinTransaction.getTimeoutForDataStable();
int threshold = javelinTransaction.getDataStableThreshold();
Authentication auth = null;
if (context.isRequestFromVic) {
// instance, from a web service call).
if (!context.isTrustedRequest) {
try {
VicApi vicApi = new VicApi();
if (!vicApi.isServiceAuthorized(context.tasUserName, context.tasVirtualServerName, context.tasServiceCode)) {
throw new EngineException("The service '" + context.tasServiceCode + "' is not authorized for the user '" + context.tasUserName);
}
} catch (IOException e) {
throw new EngineException("Unable to retrieve authorization from the VIC database.", e);
}
}
} else {
// Check the Carioca authorizations only if this is a non trusted request
if (context.isTrustedRequest) {
// Nothing to do: all the tas* variables from the context must have been set
// by the caller.
// Means we must not execute the TAS API.
} else {
// Getting Authentication object
context.tasVirtualServerName = getVirtualServer();
try {
String authName = (context.tasSessionKey == null ? context.tasUserName : context.tasSessionKey);
auth = Engine.theApp.getAuthenticationObject(context.tasVirtualServerName, authName);
// Logging to Carioca only if needed
User user = auth.getCurrentUser();
if (user == null) {
// Request from Carioca
if (context.tasSessionKey != null) {
auth.login(context.tasSessionKey);
User currentUser = auth.getCurrentUser();
context.tasUserName = currentUser.getName();
context.tasUserPassword = currentUser.getPassword();
context.tasVirtualServerName = "(SV #" + currentUser.getServerID() + ")";
String message = "Authentication to Carioca with sesskey = '" + context.tasSessionKey + "' => user: \"" + context.tasUserName + "\"";
Engine.logBeans.debug("(JavelinConnector) " + message);
} else // Specific user
if ((context.tasUserName != null) && (context.tasUserPassword != null)) {
auth.login(context.tasUserName, context.tasUserPassword);
String message = "Authentication to Carioca with user = '" + context.tasUserName + "' and password = '" + context.tasUserPassword + "'";
Engine.logBeans.debug("(JavelinConnector) " + message);
} else {
context.tasUserName = EnginePropertiesManager.getProperty(PropertyName.CARIOCA_DEFAULT_USER_NAME);
context.tasUserPassword = EnginePropertiesManager.getProperty(PropertyName.CARIOCA_DEFAULT_USER_PASSWORD);
auth.login(context.tasUserName, context.tasUserPassword);
String message = "Default authentication to Carioca";
Engine.logBeans.debug("(JavelinConnector) " + message);
}
} else {
context.tasUserName = user.getName();
context.tasUserPassword = user.getPassword();
context.tasUserGroup = user.getMainGroupName();
context.tasVirtualServerName = "(#" + Long.toString(user.getServerID()) + ")";
String message = "Already authenticated to Carioca with user = '" + context.tasUserName + "' and password = '" + context.tasUserPassword + "'";
Engine.logBeans.debug("(JavelinConnector) " + message);
}
} catch (Exception e) {
auth = null;
String message = "Unable to authenticate to Carioca.\n" + "Carioca virtual server: " + context.tasVirtualServerName + "\n" + "SessKey: \"" + context.tasSessionKey + "\"\n" + "User: \"" + context.tasUserName + "\"\n" + "Password: \"" + context.tasUserPassword + "\"";
EngineException ee = new EngineException(message, e);
throw ee;
}
}
}
// We retrieve the current project
String javelinServiceCode = context.tasServiceCode;
if (javelinServiceCode == null) {
javelinServiceCode = getServiceCode();
Engine.logBeans.debug("(JavelinConnector) No service code provided; getting the connector service code.");
}
// Analyzes/overrrides service code for device number pooling
javelinServiceCode = analyzeServiceCode(javelinServiceCode);
Engine.logBeans.debug("(JavelinConnector) Service code: " + javelinServiceCode);
session = Engine.theApp.sessionManager.getSession(context.contextID);
if (session == null) {
Engine.logBeans.debug("(JavelinConnector) No session has been found; creation of a new one and ignoring the user request.");
context.inputDocument = null;
try {
if (context.isRequestFromVic) {
session = Engine.theApp.sessionManager.addVicSession(javelinServiceCode, context.tasUserName, context.tasUserGroup + "@" + context.tasVirtualServerName, context.tasDteAddress, context.tasCommDevice, context.contextID);
} else if (context.isTrustedRequest) {
String connectionParameters = getServiceCode();
try {
StringTokenizer st = new StringTokenizer(connectionParameters, ",");
String appType = st.nextToken();
if (appType.equals("vic")) {
javelinServiceCode = st.nextToken();
context.tasDteAddress = st.nextToken();
context.tasCommDevice = st.nextToken();
Engine.logBeans.debug("(JavelinConnector) Trusted request => the connector handles connection parameters : " + connectionParameters);
Engine.logBeans.debug("(JavelinConnector) serviceCode: " + javelinServiceCode);
Engine.logBeans.debug("(JavelinConnector) dteAddress: " + context.tasDteAddress);
Engine.logBeans.debug("(JavelinConnector) commDevice: " + context.tasCommDevice);
Engine.logBeans.debug("(JavelinConnector) user: " + context.tasUserName);
String group = context.tasUserGroup + "@" + context.tasVirtualServerName;
Engine.logBeans.debug("(JavelinConnector) group: " + group);
session = Engine.theApp.sessionManager.addVicSession(javelinServiceCode, context.tasUserName, group, context.tasDteAddress, context.tasCommDevice, context.contextID);
}
} catch (NoSuchElementException e) {
Engine.logBeans.error("(JavelinConnector) Invalid connector connection parameters: " + connectionParameters);
}
} else {
session = Engine.theApp.sessionManager.addSession((int) emulatorID, auth, javelinServiceCode, context.contextID, getJavelinLanguage(), isSslEnabled(), isSslTrustAllServerCertificates(), getIbmTerminalType());
}
} catch (Exception e) {
String message = "Unable to open the Javelin session: serviceCode= '" + javelinServiceCode + "', contextID = '" + context.contextID + "'";
EngineException ee = new EngineException(message, e);
throw ee;
}
if (session == null) {
String message = "Unable to add a new session: the access to the service '" + javelinServiceCode + "' has been forbidden by the Carioca administrator.";
EngineException ee = new EngineException(message);
throw ee;
}
javelin = session.getJavelinObject();
javelin.setLog(new LogWrapper(Engine.logEmulators));
javelin.setDataStableOnCursorOn(false);
javelin.connect(javelinTransaction.getTimeoutForConnect());
boolean isConnected = javelin.isConnected();
Engine.logBeans.debug("(JavelinConnector) isConnected=" + isConnected);
if (!isConnected) {
throw new ConnectionException("Unable to connect the session! See the emulator logs for more details...");
}
executeConnectionSyncCode(javelin, timeout, threshold);
} else {
Engine.logBeans.debug("(JavelinConnector) Using the existing session");
if (context.isNewSession) {
Engine.logBeans.debug("(JavelinConnector) New session required and ignoring the user request");
context.inputDocument = null;
// First, we remove the previous session
Engine.theApp.sessionManager.removeSession(context.contextID);
try {
if (context.isRequestFromVic) {
session = Engine.theApp.sessionManager.addVicSession(javelinServiceCode, context.tasUserName, context.tasUserGroup, context.tasDteAddress, context.tasCommDevice, context.contextID);
} else {
session = Engine.theApp.sessionManager.addSession((int) emulatorID, auth, javelinServiceCode, context.contextID, getJavelinLanguage(), isSslEnabled(), isSslTrustAllServerCertificates(), getIbmTerminalType());
}
} catch (Exception e) {
String message = "Unable to open the Javelin session: serviceCode= '" + javelinServiceCode + "', contextID = '" + context.contextID + "'";
Engine.logBeans.warn("(JavelinConnector) " + message);
EngineException ee = new EngineException(message, e);
throw ee;
}
if (session == null) {
String message = "Unable to add a new session: the access to the service '" + javelinServiceCode + "' has been forbidden by the Carioca administrator.";
Engine.logBeans.warn("(JavelinConnector) " + message);
EngineException ee = new EngineException(message);
throw ee;
}
javelin = session.getJavelinObject();
javelin.setLog(new LogWrapper(Engine.logEmulators));
javelin.setDataStableOnCursorOn(false);
javelin.connect(javelinTransaction.getTimeoutForConnect());
if (!javelin.isConnected()) {
throw new ConnectionException("Unable to connect the session! See the emulator logs for more details...");
}
executeConnectionSyncCode(javelin, timeout, threshold);
} else {
javelin = session.getJavelinObject();
// Reconnect only if the requested transaction is not the end transaction
if ((!context.isDestroying) && (!session.isConnected())) {
javelin.setDataStableOnCursorOn(false);
javelin.connect(javelinTransaction.getTimeoutForConnect());
if (!javelin.isConnected()) {
throw new ConnectionException("Unable to connect the session! See the emulator logs for more details...");
}
executeConnectionSyncCode(javelin, timeout, threshold);
}
}
}
context.isNewSession = false;
} finally {
context.statistics.stop(t);
}
}
use of com.twinsoft.convertigo.engine.util.LogWrapper in project convertigo by convertigo.
the class ConvertigoPlugin method start.
/**
* This method is called upon plug-in activation
*/
@Override
public void start(final BundleContext context) throws Exception {
super.start(context);
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (activeWindow != null) {
IWorkbenchPage activePage = activeWindow.getActivePage();
if (activePage != null) {
IEditorReference[] editorRefs = activePage.getEditorReferences();
for (int i = 0; i < editorRefs.length; i++) {
IEditorReference editorRef = (IEditorReference) editorRefs[i];
String id = editorRef.getId();
if (id.startsWith("com.twinsoft.convertigo.eclipse.editors") || id.equals("org.eclipse.ui.internal.emptyEditorTab")) {
activePage.closeEditors(new IEditorReference[] { editorRef }, false);
}
}
}
}
// Version check
if (!com.twinsoft.convertigo.eclipse.Version.productVersion.equals(com.twinsoft.convertigo.beans.Version.productVersion)) {
throw new Exception("The product version numbers of Eclipse Plugin and Objects libraries are differents.");
} else if (!com.twinsoft.convertigo.eclipse.Version.productVersion.equals(com.twinsoft.convertigo.engine.Version.productVersion)) {
throw new Exception("The product version numbers of Eclipse Plugin and Engine libraries are differents.");
}
Engine.setStudioMode();
plugin = this;
try {
resourceBundle = ResourceBundle.getBundle("com.twinsoft.convertigo.eclipse.ConvertigoPluginResources");
} catch (MissingResourceException x) {
resourceBundle = null;
}
log = getLog();
projectManager = new ProjectManager();
clipboardManagerSystem = new ClipboardManager();
clipboardManagerDND = new ClipboardManager();
// learnProxy = new LearnProxy();
// Create consoles
createConsoles();
// Redirect stdout and stderr
System.setOut(new StdoutStream());
System.setErr(new StderrStream());
studioLog = new Log(ConvertigoPlugin.getDefault().stdoutConsoleStream);
runAtStartup(() -> {
studioLog = new LogWrapper(Engine.logStudio);
});
studioLog.logLevel = Log.LOGLEVEL_DEBUG;
try {
studioLog.logLevel = Integer.valueOf(ConvertigoPlugin.getProperty(ConvertigoPlugin.PREFERENCE_LOG_LEVEL)).intValue();
} catch (NumberFormatException e) {
studioLog.warning("Unable to retrieve the log level; using default log level (4).");
}
studioLog.message("Starting the Convertigo studio eclipse plugin");
try {
highlightDetectedObject = Boolean.valueOf(ConvertigoPlugin.getProperty(ConvertigoPlugin.PREFERENCE_TREE_HIGHLIGHT_DETECTED)).booleanValue();
} catch (NumberFormatException e) {
studioLog.warning("Unable to retrieve the highlight option; using default highlight option (true).");
}
try {
autoOpenDefaultConnector = Boolean.valueOf(ConvertigoPlugin.getProperty(ConvertigoPlugin.PREFERENCE_AUTO_OPEN_DEFAULT_CONNECTOR)).booleanValue();
} catch (NumberFormatException e) {
studioLog.warning("Unable to retrieve the auto open default connector option; using default (false).");
}
try {
mobileBuilderThreshold = Integer.valueOf(ConvertigoPlugin.getProperty(ConvertigoPlugin.PREFERENCE_MOBILE_BUILDER_THRESHOLD)).intValue();
} catch (NumberFormatException e) {
studioLog.warning("Unable to retrieve the mobile builder threshold option; using default (200).");
}
// In STUDIO, the Convertigo User Workspace is in the current Eclipse Workspace/.metadata/.plugins/com.twinsoft.convertigo.studio
Engine.USER_WORKSPACE_PATH = getDefault().getStateLocation().toFile().getCanonicalPath();
// In STUDIO, the Convertigo Projects directory is the current Eclipse Workspace
Engine.PROJECTS_PATH = ResourcesPlugin.getWorkspace().getRoot().getRawLocation().toFile().getCanonicalPath();
// checkPre_6_2_0_Migration();
// Adds listeners
addListeners();
runAtStartup(() -> {
Engine.theApp.eventManager.addListener(this, ProgressEventListener.class);
Engine.execute(() -> Engine.theApp.couchDbManager.getFullSyncClient());
});
DatabaseObjectsManager.studioProjects = this;
final Exception[] afterPscException = { null };
final Runnable afterPscOk = new Runnable() {
public void run() {
try {
// Create embedded Tomcat
studioLog.message("Starting the embedded Tomcat");
System.setProperty("org.apache.commons.logging.log", "org.apache.commons.logging.impl.Jdk14Logger");
Path path = new Path("tomcat");
URL tomcatHomeUrl = FileLocator.find(context.getBundle(), path, null);
String xulrunner_url = System.getProperty("org.eclipse.swt.browser.XULRunnerPath");
if (xulrunner_url == null || xulrunner_url.equals("")) {
Bundle[] bundles = Platform.getFragments(context.getBundle());
if (bundles != null) {
studioLog.message("Fragments bundles: " + bundles.length);
for (Bundle bundle : bundles) {
String symbolicName = bundle.getSymbolicName();
studioLog.message("Fragment bundle symbolic name: " + symbolicName);
if (symbolicName.startsWith("com.twinsoft.convertigo.studio.xulrunner")) {
URL url = FileLocator.find(bundle, new Path("xulrunner"), null);
studioLog.message("Xulrunner url: " + url);
xulrunner_url = FileLocator.toFileURL(url).getPath();
studioLog.message("Xulrunner xulrunner_url: " + xulrunner_url);
System.setProperty("org.eclipse.swt.browser.XULRunnerPath", xulrunner_url);
break;
}
}
}
}
String tomcatHome = FileLocator.toFileURL(tomcatHomeUrl).getPath();
int index = (System.getProperty("os.name").indexOf("Windows") != -1) ? 1 : 0;
tomcatHome = tomcatHome.substring(index);
embeddedTomcat = new EmbeddedTomcat(tomcatHome);
configureDeployConfiguration();
// displayWaitScreen();
runAtStartup(() -> {
ProjectExplorerView pew = getProjectExplorerView();
pew.initialize();
});
new Thread(embeddedTomcat, "Embedded Tomcat").start();
new Thread(new Runnable() {
public void run() {
int nbRetry = 0;
while (!Engine.isStartFailed && !Engine.isStarted) {
try {
Thread.sleep(500);
nbRetry++;
} catch (InterruptedException e) {
// Ignore
}
// Aborting if too many retries
if (nbRetry > 360)
return;
}
if (Engine.isStartFailed) {
logError("Unable to start engine; see console for more details");
return;
}
// The console threads must be started AFTER the engine
consolePipes.startConsoleThreads();
try {
deploymentConfigurationManager.doMigration();
} catch (Exception e) {
logException(e, "Unable to migrate deployment configurations");
}
studioLog.message("Embedded Tomcat started");
for (Runnable runnable : runAtStartup) {
Display.getDefault().asyncExec(runnable);
}
runAtStartup.clear();
}
}, "Wait Embedded Tomcat started").start();
getDisplay().asyncExec(() -> {
launchStartupPage(true);
});
} catch (Exception e) {
afterPscException[0] = e;
}
}
};
try {
decodePsc();
// Engine.isStartFailed = true;
afterPscOk.run();
if (afterPscException[0] != null) {
throw afterPscException[0];
}
} catch (PscException e) {
studioLog.message("No valid PSC, the Engine will start after the registration wizard.\nFailure message : " + e.getMessage());
Engine.isStartFailed = true;
Display display = getDisplay();
display.asyncExec(new Runnable() {
public void run() {
try {
boolean success = SetupAction.runSetup();
if (success) {
Engine.isStartFailed = false;
new Thread(afterPscOk, "Start embedded Tomcat").start();
} else {
studioLog.message("PSC not validated, please restart the Studio to get the Convertigo Setup wizard again.");
}
} catch (Throwable t) {
studioLog.exception(t, "Failure during the Convertigo setup wizard");
}
}
});
}
runAtStartup(() -> {
String nodeVersion = ProcessUtils.getDefaultNodeVersion();
Job job = Job.create("Retrieve default nodejs " + nodeVersion, monitor -> {
try {
monitor.beginTask("In progress", 120);
monitor.subTask("checking for existing nodejs");
monitor.worked(1);
boolean[] first = { true };
File nodeDir = ProcessUtils.getNodeDir(nodeVersion, new org.apache.commons.fileupload.ProgressListener() {
@Override
public void update(long pBytesRead, long pContentLength, int pItems) {
if (first[0]) {
monitor.worked(10);
monitor.subTask("downloading nodejs [" + (pContentLength / (1024 * 1024)) + " MB]");
first[0] = false;
}
Engine.logConvertigo.info("download NodeJS " + nodeVersion + ": " + Math.round(100f * pBytesRead / pContentLength) + "% [" + pBytesRead + "/" + pContentLength + "]");
monitor.worked(10 + Math.round(100f * pBytesRead / pContentLength));
if (pBytesRead == pContentLength) {
monitor.subTask("installing nodejs");
monitor.worked(110);
}
}
});
monitor.worked(120);
File nodeExe = new File(nodeDir, Engine.isWindows() ? "node.exe" : "node");
Engine.logStudio.warn("node ready: " + nodeExe.getAbsolutePath() + " exists ? " + nodeExe.exists());
System.setProperty("org.eclipse.wildwebdeveloper.nodeJSLocation", nodeExe.getAbsolutePath());
ProcessUtils.setDefaultNodeDir(nodeDir);
monitor.done();
} catch (Exception e) {
Engine.logStudio.error("Failed to init NPM: " + e.getMessage(), e);
}
});
job.schedule();
});
studioLog.message("Convertigo studio started");
}
use of com.twinsoft.convertigo.engine.util.LogWrapper in project convertigo by convertigo.
the class Engine method start.
public static synchronized void start() throws EngineException {
if (Engine.theApp == null) {
System.out.println("Starting Convertigo Enterprise Mobility Server");
System.out.println("Version: " + ProductVersion.fullProductVersion);
// If the engine has been stopped by the admin, we must reload
// properties
EnginePropertiesManager.loadProperties();
boolean bProjectsDataCompatibilityMode = Boolean.parseBoolean(EnginePropertiesManager.getProperty(PropertyName.PROJECTS_DATA_COMPATIBILITY_MODE));
if (bProjectsDataCompatibilityMode) {
System.out.println("Projects data compatibility mode required");
try {
Engine.PROJECTS_PATH = new File(Engine.WEBAPP_PATH + "/projects").getCanonicalPath();
File projectsDir = new File(Engine.PROJECTS_PATH);
projectsDir.mkdir();
} catch (IOException e) {
throw new EngineException("Unable to update projects path for compatibility mode", e);
}
}
isStarted = false;
isStartFailed = false;
RequestableObject.nbCurrentWorkerThreads = 0;
Engine.startStopDate = System.currentTimeMillis();
System.out.println("Creating/updating loggers");
String logFile = EnginePropertiesManager.getProperty(PropertyName.LOG4J_APPENDER_CEMSAPPENDER_FILE);
System.out.println("Log file: " + logFile);
// Main loggers
Engine.logConvertigo = Logger.getLogger("cems");
Engine.logEngine = Logger.getLogger("cems.Engine");
Engine.logAdmin = Logger.getLogger("cems.Admin");
Engine.logBeans = Logger.getLogger("cems.Beans");
Engine.logBillers = Logger.getLogger("cems.Billers");
Engine.logEmulators = Logger.getLogger("cems.Emulators");
Engine.logContext = Logger.getLogger("cems.Context");
Engine.logUser = Logger.getLogger("cems.Context.User");
Engine.logUsageMonitor = Logger.getLogger("cems.UsageMonitor");
Engine.logStatistics = Logger.getLogger("cems.Statistics");
Engine.logScheduler = Logger.getLogger("cems.Scheduler");
Engine.logSiteClipper = Logger.getLogger("cems.SiteClipper");
Engine.logSecurityFilter = Logger.getLogger("cems.SecurityFilter");
Engine.logStudio = Logger.getLogger("cems.Studio");
Engine.logAudit = Logger.getLogger("cems.Context.Audit");
// Managers
Engine.logContextManager = Logger.getLogger("cems.ContextManager");
Engine.logCacheManager = Logger.getLogger("cems.CacheManager");
Engine.logTracePlayerManager = Logger.getLogger("cems.TracePlayerManager");
Engine.logJobManager = Logger.getLogger("cems.JobManager");
Engine.logCertificateManager = Logger.getLogger("cems.CertificateManager");
Engine.logDatabaseObjectManager = Logger.getLogger("cems.DatabaseObjectManager");
Engine.logProxyManager = Logger.getLogger("cems.ProxyManager");
Engine.logDevices = Logger.getLogger("cems.Devices");
Engine.logCouchDbManager = Logger.getLogger("cems.CouchDbManager");
Engine.logSecurityTokenManager = Logger.getLogger("cems.SecurityTokenManager");
// Logger for compatibility issues
Engine.log = new LogWrapper(Engine.logConvertigo);
LogWrapper.initWrapper(Engine.logEmulators);
LogCleaner.start();
try {
Engine.logEngine.info("===========================================================");
Engine.logEngine.info("Web app home: " + Engine.WEBAPP_PATH);
Engine.logEngine.info("User workspace: " + Engine.USER_WORKSPACE_PATH);
Engine.logEngine.info("Configuration path: " + Engine.CONFIGURATION_PATH);
Engine.logEngine.info("Projects path: " + Engine.PROJECTS_PATH);
if (bProjectsDataCompatibilityMode) {
Engine.logEngine.warn("Projects data compatibility mode required");
}
Engine.logEngine.info("Log: " + Engine.LOG_PATH);
if (cloud_customer_name != null) {
Engine.logEngine.info("Cloud customer: " + cloud_customer_name);
}
// Check environment and native dependencies
if (!isStudioMode()) {
StartupDiagnostics.run();
}
// Initializing the engine
Engine.theApp = new Engine();
CachedIntrospector.prefetchDatabaseObjectsAsync();
try {
Engine.theApp.usageMonitor = new UsageMonitor();
Engine.theApp.usageMonitor.init();
Thread vulture = new Thread(Engine.theApp.usageMonitor);
vulture.setName("UsageMonitor");
vulture.setDaemon(true);
vulture.start();
} catch (Exception e) {
Engine.logEngine.error("Unable to launch the usage monitor.", e);
}
Engine.theApp.eventManager = new EventManager();
Engine.theApp.eventManager.init();
Engine.theApp.databaseObjectsManager = new DatabaseObjectsManager();
Engine.theApp.databaseObjectsManager.init();
Engine.theApp.databaseObjectsManager.addDatabaseObjectListener(ComponentRefManager.get(Mode.start));
Engine.theApp.systemDatabaseObjectsManager = new SystemDatabaseObjectsManager();
Engine.theApp.systemDatabaseObjectsManager.init();
Engine.theApp.sqlConnectionManager = new JdbcConnectionManager();
Engine.theApp.sqlConnectionManager.init();
Engine.theApp.filePropertyManager = new FilePropertyManager();
Engine.theApp.filePropertyManager.init();
try {
Engine.theApp.proxyManager = new ProxyManager();
Engine.theApp.proxyManager.init();
} catch (Exception e) {
Engine.logEngine.error("Unable to launch the proxy manager.", e);
}
try {
Engine.theApp.billerTokenManager = new BillerTokenManager();
Engine.theApp.billerTokenManager.init();
} catch (Exception e) {
Engine.logEngine.error("Unable to launch the biller token manager.", e);
}
try {
Engine.theApp.billingManager = new BillingManager();
Engine.theApp.billingManager.init();
} catch (Exception e) {
Engine.logEngine.error("Unable to launch the billing manager.", e);
}
// Initialization of the trace player
try {
Engine.theApp.tracePlayerManager = new TracePlayerManager();
Engine.theApp.tracePlayerManager.init();
} catch (Exception e) {
Engine.logEngine.error("Unable to run the trace player.", e);
}
try {
Engine.theApp.minificationManager = new MinificationManager();
Engine.theApp.minificationManager.init();
} catch (Exception e) {
Engine.logEngine.error("Unable to run the minification manager.", e);
}
try {
Engine.theApp.couchDbManager = new CouchDbManager();
Engine.theApp.couchDbManager.init();
} catch (Exception e) {
Engine.logEngine.error("Unable to run the couchDbProxy manager.", e);
}
try {
Engine.theApp.pluginsManager = new PluginsManager();
Engine.theApp.pluginsManager.init();
} catch (Exception e) {
Engine.logEngine.error("Unable to run the plugins manager.", e);
}
try {
Engine.theApp.restApiManager = RestApiManager.getInstance();
Engine.theApp.restApiManager.init();
} catch (Exception e) {
Engine.logEngine.error("Unable to run the rest api manager.", e);
}
Engine.logEngine.info("Current working directory is '" + System.getProperty("user.dir") + "'.");
// Creating the Carioca Authentication objects
Engine.logEngine.debug("Creating the Carioca Authentication objects");
String cariocaUserName = EnginePropertiesManager.getProperty(PropertyName.CARIOCA_DEFAULT_USER_NAME);
String cariocaPassword = EnginePropertiesManager.getProperty(PropertyName.CARIOCA_DEFAULT_USER_PASSWORD);
Engine.theApp.authentications = new HashMap<String, Authentication>();
// Initialization of the default TAS properties
try {
KeyManager.log = new LogWrapper(Engine.logEngine);
Authentication auth = Engine.theApp.getAuthenticationObject("", null);
auth.login(cariocaUserName, cariocaPassword);
} catch (Exception e) {
Engine.logEngine.error("The authentication to Carioca has failed (user name: \"" + cariocaUserName + "\", user password: \"" + cariocaPassword + "\").", e);
}
// TODO : retrieve SOA flag from KeyManager
isSOA = true;
// Creation of the session manager
Engine.theApp.sessionManager = new SessionManager();
Engine.theApp.sessionManager.setLog(new LogWrapper(Engine.logEngine));
Engine.theApp.sessionManager.setProductCode(SessionManager.CONVERTIGO);
String s = EnginePropertiesManager.getProperty(PropertyName.CONNECTORS_MONITORING);
Engine.theApp.setMonitored(s.equalsIgnoreCase("true"));
// Create Projects directory if needed
File projectsDirFile = new File(Engine.PROJECTS_PATH);
try {
if (!projectsDirFile.exists())
projectsDirFile.mkdirs();
} catch (Exception e) {
Engine.logEngine.error("An error occured while creating projects directory.", e);
}
// Starts projects migration process
MigrationManager.performProjectsMigration();
// Security providers registration
try {
File dir = new File(Engine.CERTIFICATES_PATH);
String[] files = dir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith((".pkcs11"));
}
});
if (files != null && files.length > 0) {
Engine.logEngine.info("Registering security providers...");
try {
Class<?> sunPKCS11Class = Class.forName("sun.security.pkcs11.SunPKCS11");
String file;
for (int i = 0; i < files.length; i++) {
file = Engine.CERTIFICATES_PATH + "/" + files[i];
try {
Constructor<?> constructor = sunPKCS11Class.getConstructor(new Class[] { String.class });
Provider provider = (Provider) constructor.newInstance(new Object[] { file });
Security.addProvider(provider);
Engine.logEngine.info("Provider '" + provider.getName() + "' has been successfully registered.");
} catch (Exception e) {
Engine.logEngine.error("Unable to register security provider from file: " + file + " . Please check that the implementation library is in the Java lib path.");
}
}
} catch (ClassNotFoundException e) {
Engine.logEngine.error("Unable to find sun.security.pkcs11.SunPKCS11 class! PKCS#11 authentication won't be available. You must use JVM 1.5 or higher in order to use PKCS#11 authentication.");
}
}
Provider[] providers = Security.getProviders();
String sProviders = "";
for (int i = 0; i < providers.length; i++) {
sProviders += providers[i].getName() + ", ";
}
Engine.logEngine.debug("Registered providers: " + sProviders);
} catch (Exception e) {
Engine.logEngine.error("Unable to register security providers.", e);
}
// Launch the cache manager
try {
String cacheManagerClassName = EnginePropertiesManager.getProperty(PropertyName.CACHE_MANAGER_CLASS);
Engine.logEngine.debug("Cache manager class: " + cacheManagerClassName);
Engine.theApp.cacheManager = (CacheManager) Class.forName(cacheManagerClassName).getConstructor().newInstance();
Engine.theApp.cacheManager.init();
} catch (Exception e) {
Engine.logEngine.error("Unable to launch the cache manager.", e);
}
// Launch the thread manager
try {
Engine.theApp.threadManager = new ThreadManager();
Engine.theApp.threadManager.init();
Thread vulture = new Thread(Engine.theApp.threadManager);
Engine.theApp.threadManager.executionThread = vulture;
vulture.setName("ThreadManager");
vulture.setDaemon(true);
vulture.start();
} catch (Exception e) {
Engine.theApp.threadManager = null;
Engine.logEngine.error("Unable to launch the thread manager.", e);
}
// Launch the context manager
try {
Engine.theApp.contextManager = new ContextManager();
Engine.theApp.contextManager.init();
Thread vulture = new Thread(Engine.theApp.contextManager);
Engine.theApp.contextManager.executionThread = vulture;
vulture.setName("ContextManager");
vulture.setDaemon(true);
vulture.start();
} catch (Exception e) {
Engine.theApp.contextManager = null;
Engine.logEngine.error("Unable to launch the context manager.", e);
}
// Initialize the HttpClient
try {
Engine.logEngine.debug("HttpClient initializing...");
HttpMethodParams.getDefaultParams().setParameter(HttpMethodParams.CREDENTIAL_CHARSET, "UTF-8");
Engine.theApp.httpClient = HttpUtils.makeHttpClient3(true);
Engine.theApp.httpClient4 = HttpUtils.makeHttpClient(true);
Engine.logEngine.debug("HttpClient initialized!");
} catch (Exception e) {
Engine.logEngine.error("Unable to initialize the HttpClient.", e);
}
// Initialization of the schedule manager
Engine.theApp.schedulerManager = new SchedulerManager(true);
// Initialization of the RSA manager
Engine.theApp.rsaManager = new RsaManager();
Engine.theApp.rsaManager.init();
// Initialization of the Schema manager
Engine.theApp.schemaManager = new SchemaManager();
Engine.theApp.schemaManager.init();
Engine.theApp.referencedProjectManager = new ReferencedProjectManager();
// XUL initialization
String xulrunner_url = System.getProperty("org.eclipse.swt.browser.XULRunnerPath");
if (xulrunner_url == null || xulrunner_url.equals("")) {
xulrunner_url = EnginePropertiesManager.getProperty(PropertyName.XULRUNNER_URL);
}
File f = new File(xulrunner_url);
if (f.exists()) {
xulrunner_url = f.getAbsolutePath();
Engine.logEngine.debug("initMozillaSWT: org.eclipse.swt.browser.XULRunnerPath=" + xulrunner_url);
System.setProperty("org.eclipse.swt.browser.XULRunnerPath", xulrunner_url);
Engine.bXulRunner = true;
} else {
if (Engine.isLinux() && "i386".equals(System.getProperty("os.arch"))) {
Engine.logEngine.error("Error in initMozillaSWT: " + xulrunner_url + " doesn't exist, fix it with xulrunner.url");
} else {
Engine.logEngine.debug("No XulRunner to init.");
}
}
if (Engine.isEngineMode() && Engine.isLinux() && "true".equals(EnginePropertiesManager.getProperty(PropertyName.LINUX_LAUNCH_XVNC))) {
final String display = System.getenv("DISPLAY");
Engine.logEngine.debug("Linux launch XVNC on display: " + display);
if (display != null) {
try {
String port = System.getProperty("xvnc.port");
if (port == null) {
port = "" + (Integer.parseInt(display.replaceAll(".*:(\\d*)", "$1")) + 5900);
System.setProperty("xvnc.port", port);
}
Engine.logEngine.debug("Xvnc should listen on " + port + " port");
} catch (Exception e) {
}
try {
File vncDir = new File(Engine.WEBAPP_PATH + "/WEB-INF/xvnc");
File Xvnc = new File(vncDir, "/Xvnc");
File fonts = new File(vncDir, "/fonts");
File wm = new File(vncDir, "/matchbox-window-manager");
if (vncDir.exists() && Xvnc.exists() && fonts.exists() && wm.exists()) {
for (File file : GenericUtils.<File>asList(Xvnc, wm)) {
new ProcessBuilder("/bin/chmod", "u+x", file.getAbsolutePath()).start().waitFor();
}
String depth = EnginePropertiesManager.getProperty(PropertyName.LINUX_XVNC_DEPTH);
String geometry = EnginePropertiesManager.getProperty(PropertyName.LINUX_XVNC_GEOMETRY);
Engine.logEngine.debug("Xvnc will use depth " + depth + " and geometry " + geometry);
Process pr_xvnc = new ProcessBuilder(Xvnc.getAbsolutePath(), display, "-fp", fonts.getAbsolutePath(), "-depth", depth, "-geometry", geometry).start();
Thread.sleep(500);
try {
int exit = pr_xvnc.exitValue();
InputStream err = pr_xvnc.getErrorStream();
byte[] buf = new byte[err.available()];
err.read(buf);
Engine.logEngine.debug("Xvnc failed to run with exit code " + exit + " and this error : <<" + new String(buf, "UTF-8") + ">>");
} catch (Exception e) {
new ProcessBuilder(wm.getAbsolutePath()).start();
Engine.logEngine.debug("Xvnc successfully started !");
}
} else {
Engine.logEngine.info(vncDir.getAbsolutePath() + " not found or incomplet, cannot start Xvnc");
}
} catch (Exception e) {
Engine.logEngine.info("failed to launch Xvnc (maybe already launched", e);
}
} else
Engine.logEngine.warn("Trying to start Xvnc on Linux without DISPLAY environment variable !");
}
isStarted = true;
Engine.logEngine.info("Convertigo engine started");
if (Engine.isEngineMode()) {
theApp.addMigrationListener(new MigrationListener() {
@Override
public void projectMigrated(EngineEvent engineEvent) {
}
@Override
public void migrationFinished(EngineEvent engineEvent) {
List<String> names = Engine.theApp.databaseObjectsManager.getAllProjectNamesList();
Engine.logEngine.info("Convertigo engine will load: " + names);
for (String name : names) {
try {
Engine.theApp.databaseObjectsManager.getProjectByName(name);
} catch (Exception e) {
Engine.logEngine.error("Failed to load " + name, e);
}
}
boolean newProjectLoaded = Engine.theApp.referencedProjectManager.check();
if (!newProjectLoaded && Thread.currentThread().getName().equalsIgnoreCase("Migration")) {
Engine.logEngine.info("Convertigo will run auto start Sequences.");
for (String name : names) {
Project.executeAutoStartSequences(name);
}
}
}
});
}
if (DelegateServlet.canDelegate()) {
execute(() -> {
try {
Engine.logEngine.info("Call delegate action 'engineStarted'");
JSONObject json = new JSONObject();
json.put("action", "engineStarted");
DelegateServlet.delegate(json);
} catch (JSONException e) {
}
});
}
} catch (Throwable e) {
isStartFailed = true;
Engine.logEngine.error("Unable to successfully start the engine.", e);
}
} else {
Engine.logEngine.info("Convertigo engine already started");
}
}
use of com.twinsoft.convertigo.engine.util.LogWrapper in project convertigo by convertigo.
the class RequestableObject method insertObjectsInScope.
protected void insertObjectsInScope() throws EngineException {
// Insert the DOM into the scripting context
Scriptable jsContext = org.mozilla.javascript.Context.toObject(context, scope);
scope.put("context", scope, jsContext);
// Insert the log object into the scripting context
Scriptable jsLog = org.mozilla.javascript.Context.toObject(new LogWrapper(Engine.logUser), scope);
scope.put("log", scope, jsLog);
// Insert the steps vector into the scripting context
Scriptable jsSteps = org.mozilla.javascript.Context.toObject(context.steps, scope);
scope.put("steps", scope, jsSteps);
// Insert the DOM into the scripting context
Scriptable jsDOM = org.mozilla.javascript.Context.toObject(context.outputDocument, scope);
scope.put("dom", scope, jsDOM);
try {
scope.put("use", scope, new FunctionObject("use", getClass().getMethod("useInScope", org.mozilla.javascript.Context.class, Scriptable.class, Object[].class, Function.class), scope));
} catch (Exception e) {
Engine.logBeans.warn("Failed to declare 'use' in the JS scope", e);
}
try {
scope.put("include", scope, new FunctionObject("include", getClass().getMethod("includeInScope", org.mozilla.javascript.Context.class, Scriptable.class, Object[].class, Function.class), scope));
} catch (Exception e) {
Engine.logBeans.warn("Failed to declare 'include' in the JS scope", e);
}
try {
scope.put("synchronized", scope, new FunctionObject("synchronized", getClass().getMethod("synchronize", org.mozilla.javascript.Context.class, Scriptable.class, Object[].class, Function.class), scope));
} catch (Exception e) {
Engine.logBeans.warn("Failed to declare 'include' in the JS scope", e);
}
}
Aggregations