use of com.twinsoft.util.TWSKey in project convertigo by convertigo.
the class JavelinConnector method checkKeys.
public boolean checkKeys() {
try {
long emulatorID = findEmulatorId();
TWSKey twsKey = new TWSKey();
twsKey.CreateKey(52);
boolean hasExpired = true;
for (Object okey : KeyManager.keys.values()) {
Key key = (Key) okey;
if (key.emulatorID == emulatorID) {
hasExpired &= (key.cv == 0) || twsKey.hasExpired(key.sKey);
}
}
return !hasExpired;
} catch (Exception e) {
}
return false;
}
use of com.twinsoft.util.TWSKey in project convertigo by convertigo.
the class Update method getServiceResult.
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
Element rootElement = document.getDocumentElement();
Element keysListElement = document.createElement("keys");
rootElement.appendChild(keysListElement);
Document post = null;
post = XMLUtils.parseDOM(request.getInputStream());
NodeList nl = post.getElementsByTagName("key");
String tasRoot = EnginePropertiesManager.getProperty(PropertyName.CARIOCA_URL);
for (int i = 0; i < nl.getLength(); i++) {
String newKey = ((Element) nl.item(i)).getAttribute("text");
if (newKey != null) {
Element keyElement = document.createElement("key");
String keyInfos;
TWSKey twsKey = new TWSKey();
twsKey.CreateKey(52);
keyInfos = twsKey.decypherbis(newKey);
if (keyInfos.length() == 0) {
keyElement.setAttribute("errorMessage", "The key is not valid!");
keyElement.setAttribute("valid", "false");
keyElement.setAttribute("text", newKey);
keysListElement.appendChild(keyElement);
} else {
try {
StringTokenizer st = new StringTokenizer(keyInfos, ";");
int product = Integer.parseInt(st.nextToken());
if (product != 52) {
keyElement.setAttribute("errorMessage", "The key is not a Convertigo key!");
keyElement.setAttribute("valid", "false");
keyElement.setAttribute("text", newKey);
keysListElement.appendChild(keyElement);
} else {
st.nextToken();
int cv = Integer.parseInt(st.nextToken());
if (cv < 1) {
keyElement.setAttribute("errorMessage", "The key is not valid (cv < 1)!");
keyElement.setAttribute("valid", "false");
keyElement.setAttribute("text", newKey);
keysListElement.appendChild(keyElement);
} else if (twsKey.hasExpired(newKey)) {
keyElement.setAttribute("errorMessage", "The key is already expired!");
keyElement.setAttribute("valid", "false");
keyElement.setAttribute("text", newKey);
keysListElement.appendChild(keyElement);
} else {
Properties keysProperties = PropertiesUtils.load(tasRoot + "/Java/keys.txt");
// Check if key already exists
if (keysProperties.getProperty(newKey) != null) {
keyElement.setAttribute("errorMessage", "The key has already been added!");
keyElement.setAttribute("valid", "false");
keyElement.setAttribute("text", newKey);
keysListElement.appendChild(keyElement);
} else {
keysProperties.setProperty(newKey, "");
PropertiesUtils.store(keysProperties, tasRoot + "/Java/keys.txt");
KeyManager.addKey(newKey, keyInfos);
keyElement.setAttribute("valid", "true");
keyElement.setAttribute("text", newKey);
keysListElement.appendChild(keyElement);
/* The keys have been updated */
Engine.logAdmin.info("The key '" + newKey + "' has been added");
/* update key file */
updateKeyFile();
Engine.logAdmin.info("The key file updated");
}
}
}
} catch (Exception e) {
keyElement.setAttribute("errorMessage", "The key is not valid!");
keyElement.setAttribute("valid", "false");
keyElement.setAttribute("text", newKey);
keysListElement.appendChild(keyElement);
}
}
}
}
}
use of com.twinsoft.util.TWSKey in project convertigo by convertigo.
the class GetStatus method getServiceResult.
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
Element rootElement = document.getDocumentElement();
Locale locale = Locale.getDefault();
String timezone = Calendar.getInstance().getTimeZone().getDisplayName(false, TimeZone.SHORT);
long now = System.currentTimeMillis();
long currentTimeSec = now / 1000;
long startDateSec = Engine.startStopDate / 1000;
long runningElapseDays = (currentTimeSec - startDateSec) / 86400;
long runningElapseHours = ((currentTimeSec - startDateSec) / 3600) % 24;
long runningElapseMin = ((currentTimeSec - startDateSec) / 60) % 60;
long runningElapseSec = (currentTimeSec - startDateSec) % 60;
Element versionElement = document.createElement("version");
versionElement.setAttribute("product", com.twinsoft.convertigo.engine.Version.fullProductVersion);
versionElement.setAttribute("id", com.twinsoft.convertigo.engine.Version.fullProductVersionID);
versionElement.setAttribute("beans", com.twinsoft.convertigo.beans.Version.version);
versionElement.setAttribute("engine", com.twinsoft.convertigo.engine.Version.version);
versionElement.setAttribute("build", com.twinsoft.convertigo.engine.Version.revision);
// We list each keys to know how are valid and what is the SE key
Iterator<?> iter = KeyManager.keys.values().iterator();
int nbValidKey = 0;
boolean licenceMismatch = true;
Key seKey = null;
while (iter.hasNext()) {
Key key = (Key) iter.next();
if (key.emulatorID == com.twinsoft.api.Session.EmulIDSE) {
// check (unlimited key or currentKey expiration date later than previous)
if ((seKey == null) || (key.expiration == 0) || (key.expiration >= seKey.expiration)) {
seKey = key;
licenceMismatch = false;
}
// skip overdated or overriden session key, only ONE is allowed
continue;
}
nbValidKey += KeyManager.hasExpired(key.emulatorID) ? 0 : (key.bDemo ? 0 : 1);
}
int iCategory = 0;
int iStations = 0;
String endDate = null;
Date currentDate = new Date();
Date expiredDate = null;
int iNumberOfDays = -1;
TWSKey twsKey = new TWSKey();
twsKey.CreateKey(3);
if (seKey != null) {
iCategory = 15;
iStations = seKey.licence;
iNumberOfDays = seKey.expiration;
// We search the license expiration date
if (iNumberOfDays != 0) {
expiredDate = new Date((long) (iNumberOfDays) * 1000 * 60 * 60 * 24);
SimpleDateFormat formater = new SimpleDateFormat("MM/dd/yyyy");
endDate = formater.format(expiredDate);
}
}
versionElement.setAttribute("licence-type", iCategory == 15 ? (nbValidKey > 1 ? "Convertigo Extended Edition" + (licenceMismatch ? "(! license mismatch !)" : "") : (nbValidKey == 0 ? "Convertigo Community Edition" : (licenceMismatch ? "(! license mismatch !)" : "Convertigo Standard Edition"))) : "Convertigo Community Edition");
versionElement.setAttribute("licence-number", iCategory == 15 ? (990000000 + iStations) + "" : "n/a");
int snb = KeyManager.getMaxCV(Session.EmulIDSE) - HttpSessionListener.countSessions();
versionElement.setAttribute("licence-sessions", Integer.toString(snb));
String licenceEnd = (iNumberOfDays != 0) ? (iNumberOfDays < 0 ? "n/a" : endDate) : "unlimited";
versionElement.setAttribute("licence-end", licenceEnd);
versionElement.setAttribute("licence-expired", iNumberOfDays != 0 ? (iNumberOfDays < 0 ? "n/a" : currentDate.compareTo(expiredDate) > 0) + "" : "false");
rootElement.appendChild(versionElement);
try {
Element buildElement = document.createElement("build");
Properties properties = new Properties();
ServletContext servletContext = request.getSession().getServletContext();
InputStream buildInfoFile = servletContext.getResourceAsStream("/WEB-INF/build.txt");
if (buildInfoFile != null) {
PropertiesUtils.load(properties, buildInfoFile);
buildElement.setAttribute("date", properties.getProperty("build.date"));
buildElement.setAttribute("filename", properties.getProperty("build.filename"));
buildElement.setAttribute("version", properties.getProperty("build.version"));
rootElement.appendChild(buildElement);
}
} catch (Exception e) {
// Ignore
Engine.logAdmin.error("Unable to get build info", e);
}
Element EngineState = document.createElement("engineState");
Text textStart = null;
if (Engine.isStarted) {
textStart = document.createTextNode("started");
} else {
textStart = document.createTextNode("stopped");
}
EngineState.appendChild(textStart);
rootElement.appendChild(EngineState);
Element startStopDateElement = document.createElement("startStopDate");
Text textNode = document.createTextNode(String.valueOf(Engine.startStopDate));
startStopDateElement.appendChild(textNode);
startStopDateElement.setAttribute("localeFormatted", DateFormat.getDateInstance(DateFormat.LONG, locale).format(Engine.startStopDate) + " - " + DateFormat.getTimeInstance(DateFormat.MEDIUM, locale).format(Engine.startStopDate));
startStopDateElement.setAttribute("locale", locale.toString());
startStopDateElement.setAttribute("timezone", timezone);
rootElement.appendChild(startStopDateElement);
Element runningElapseElement = document.createElement("runningElapse");
runningElapseElement.setAttribute("days", String.valueOf(runningElapseDays));
runningElapseElement.setAttribute("hours", String.valueOf(runningElapseHours));
runningElapseElement.setAttribute("minutes", String.valueOf(runningElapseMin));
runningElapseElement.setAttribute("seconds", String.valueOf(runningElapseSec));
textNode = document.createTextNode(String.valueOf(now - Engine.startStopDate));
runningElapseElement.appendChild(textNode);
rootElement.appendChild(runningElapseElement);
Element dateTime = document.createElement("time");
dateTime.setTextContent(String.valueOf(now));
dateTime.setAttribute("localeFormatted", DateFormat.getDateInstance(DateFormat.LONG, locale).format(now) + " - " + DateFormat.getTimeInstance(DateFormat.MEDIUM, locale).format(now));
dateTime.setAttribute("locale", locale.toString());
dateTime.setAttribute("timezone", timezone);
rootElement.appendChild(dateTime);
Element mode = document.createElement("mode");
mode.setTextContent(Engine.isStudioMode() ? "studio" : "server");
rootElement.appendChild(mode);
}
use of com.twinsoft.util.TWSKey in project convertigo by convertigo.
the class Engine method getDocument.
/**
* Retrieves the XML document according to the given context.
*
* @param requester
* the calling requester.
* @param context
* the request context.
*
* @return the generated XML document.
*/
public Document getDocument(Requester requester, Context context) throws EngineException {
Document outputDom = null;
String t = context.statistics.start(EngineStatistics.GET_DOCUMENT);
try {
Engine.logContext.trace("Engine.getDocument: started");
// Are we in the studio context?
if (isStudioMode()) {
Engine.logContext.debug("The requested object will be processed in the studio context.");
}
// Checking whether the asynchronous mode has been requested.
if ((context.isAsync) && (JobManager.jobExists(context.contextID))) {
Engine.logContext.debug("The requested object is working and is asynchronous; requesting job status...");
HttpServletRequest request = (HttpServletRequest) requester.inputData;
if (request.getParameter(Parameter.Abort.getName()) != null) {
Engine.logContext.debug("Job abortion has been required");
return JobManager.abortJob(context.contextID);
}
return JobManager.getJobStatus(context.contextID);
}
// Loading project
if (context.projectName == null)
throw new EngineException("The project name has been specified!");
// Checking whether the asynchronous mode has been requested.
if ((context.isAsync) && (JobManager.jobExists(context.contextID))) {
Engine.logContext.debug("The requested object is working and is asynchronous; requesting job status...");
HttpServletRequest request = (HttpServletRequest) requester.inputData;
if (request.getParameter(Parameter.Abort.getName()) != null) {
Engine.logContext.debug("Job abortion has been required");
return JobManager.abortJob(context.contextID);
}
return JobManager.getJobStatus(context.contextID);
}
// Loading project
if (context.projectName == null)
throw new EngineException("The project name has been specified!");
Project currentProject;
if ("system".equals(context.contextID)) {
context.project = currentProject = systemDatabaseObjectsManager.getOriginalProjectByName(context.getProjectName());
} else if (isStudioMode()) {
if (objectsProvider == null) {
throw new EngineException("Is the Projects view opened in the Studio? Failed to load: " + context.projectName);
}
currentProject = objectsProvider.getProject(context.projectName);
if (currentProject == null) {
throw new EngineException("No project has been opened in the Studio. A project should be opened in the Studio in order that the Convertigo engine can work.");
} else if (!currentProject.getName().equalsIgnoreCase(context.projectName)) {
throw new EngineException("The requested project (\"" + context.projectName + "\") does not match with the opened project (\"" + currentProject.getName() + "\") in the Studio.\nYou cannot make a request on a different project than the one opened in the Studio.");
}
Engine.logContext.debug("Using project from Studio");
context.project = currentProject;
} else {
if ((context.project == null) || (context.isNewSession)) {
Engine.logEngine.debug("New project requested: '" + context.projectName + "'");
context.project = Engine.theApp.databaseObjectsManager.getProjectByName(context.projectName);
Engine.logContext.debug("Project loaded: " + context.project.getName());
}
}
context.project.checkSymbols();
if (context.httpServletRequest != null && !RequestAttribute.corsOrigin.has(context.httpServletRequest)) {
String origin = HeaderName.Origin.getHeader(context.httpServletRequest);
String corsOrigin = HttpUtils.filterCorsOrigin(context.project.getCorsOrigin(), origin);
if (corsOrigin != null) {
context.setResponseHeader(HeaderName.AccessControlAllowOrigin.value(), corsOrigin);
context.setResponseHeader(HeaderName.AccessControlAllowCredentials.value(), "true");
Engine.logContext.trace("Add CORS header for: " + corsOrigin);
}
RequestAttribute.corsOrigin.set(context.httpServletRequest, corsOrigin == null ? "" : corsOrigin);
}
// Loading sequence
if (context.sequenceName != null) {
context.loadSequence();
} else {
// Loading connector
context.loadConnector();
// provided
if (context.transactionName == null) {
context.requestedObject = context.getConnector().getDefaultTransaction();
context.transaction = (Transaction) context.requestedObject;
context.transactionName = context.requestedObject.getName();
Engine.logContext.debug("Default transaction loaded: " + context.transactionName);
} else // Try to load overriden transaction
{
context.requestedObject = context.getConnector().getTransactionByName(context.transactionName);
context.transaction = (Transaction) context.requestedObject;
if (context.requestedObject == null) {
throw new EngineException("Unknown transaction \"" + context.transactionName + "\"");
}
Engine.logContext.debug("Transaction loaded: " + context.requestedObject.getName());
}
context.transaction.checkSymbols();
if (context.getConnector().isTasAuthenticationRequired()) {
if (context.tasSessionKey == null) {
throw new EngineException("A Carioca authentication is required in order to process the transaction.");
} else {
// Checking VIC information if needed
if (context.isRequestFromVic) {
Engine.logContext.debug("[Engine.getDocument()] Checking VIC session key");
String s = Crypto2.decodeFromHexString(context.tasSessionKey);
int i = s.indexOf(',');
if (i == -1)
throw new EngineException("Unable to decrypt the VIC session key (reason: #1)!");
try {
long t0 = Long.parseLong(s.substring(0, i));
Engine.logContext.debug("[VIC key check] t0=" + t0);
long t1 = System.currentTimeMillis();
Engine.logContext.debug("[VIC key check] t1=" + t1);
long d = Math.abs(t1 - t0);
Engine.logContext.debug("[VIC key check] d=" + d);
String user = s.substring(i + 1);
Engine.logContext.debug("[VIC key check] user: " + user);
long deltaT = 1000 * 60 * 10;
if (d > deltaT)
throw new EngineException("The VIC session key has expired.");
if (!user.equals(context.tasUserName))
throw new EngineException("Wrong user name!");
} catch (NumberFormatException e) {
throw new EngineException("Unable to decrypt the VIC session key (reason: #2)!");
}
Engine.logContext.debug("[VIC key check] VIC session key OK");
} else // Checking Carioca session key
if (context.isTrustedRequest) {
if (!context.tasSessionKeyVerified) {
Engine.logContext.debug("[Engine.getDocument()] Checking Carioca session key");
TWSKey twsKey = new TWSKey();
twsKey.CreateKey(1);
int cariocaSessionKeyLifeTime = 60;
try {
cariocaSessionKeyLifeTime = Integer.parseInt(EnginePropertiesManager.getProperty(EnginePropertiesManager.PropertyName.CARIOCA_SESSION_KEY_LIFE_TIME));
} catch (NumberFormatException e) {
Engine.logContext.warn("The Carioca session key life time value is not valid (not a number)! Setting default to 60s.");
}
Engine.logContext.debug("Carioca session key lifetime: " + cariocaSessionKeyLifeTime + " second(s)");
String result = checkCariocaSessionKey(context, context.tasSessionKey, context.tasServiceCode, 0, cariocaSessionKeyLifeTime);
if (result != null)
throw new EngineException(result);
Engine.logContext.debug("[ContextManager] Carioca session key OK");
context.tasSessionKeyVerified = true;
}
}
}
}
}
// Check requestable accessibility
requester.checkAccessibility();
// Check requestable access policy
requester.checkSecuredConnection();
// Check authenticated context requirement
requester.checkAuthenticatedContext();
requester.checkParentContext();
RequestableObject requestedObject = context.requestedObject;
String contextResponseExpiryDate = (String) context.get(Parameter.ResponseExpiryDate.getName());
String oldResponseExpiryDate = null;
if (contextResponseExpiryDate != null) {
oldResponseExpiryDate = requestedObject.getResponseExpiryDate();
requestedObject.setResponseExpiryDate(contextResponseExpiryDate);
context.remove(Parameter.ResponseExpiryDate.getName());
}
try {
if (context.isAsync) {
outputDom = JobManager.addJob(cacheManager, requestedObject, requester, context);
} else {
outputDom = cacheManager.getDocument(requester, context);
}
} finally {
if (oldResponseExpiryDate != null) {
requestedObject.setResponseExpiryDate(oldResponseExpiryDate);
}
onDocumentRetrieved(context, outputDom);
}
Element documentElement = outputDom.getDocumentElement();
documentElement.setAttribute("version", Version.fullProductVersion);
documentElement.setAttribute("context", context.name);
documentElement.setAttribute("contextId", context.contextID);
DatabaseObject lastDetectedObject = (DatabaseObject) context.lastDetectedObject;
if (lastDetectedObject != null) {
documentElement.setAttribute("screenclass", lastDetectedObject.getName());
// TODO :
// documentElement.setAttribute(lastDetectedObject.getClass().getName().toLowerCase(),
// lastDetectedObject.getName());
}
context.documentSignatureSent = System.currentTimeMillis();
documentElement.setAttribute("signature", Long.toString(context.documentSignatureSent));
// Add the user reference if any
if (context.userReference != null) {
documentElement.setAttribute("userReference", context.userReference);
}
} catch (EngineException e) {
String message = "[Engine.getDocument()] Context ID#" + context.contextID + " - Unable to build the XML document.";
message += "\n[" + e.getClass().getName() + "] " + e.getMessage();
if (System.getProperty("java.specification.version").compareTo("1.4") >= 0) {
Throwable eCause = e;
while ((eCause = eCause.getCause()) != null) {
if (!(eCause instanceof ConvertigoException)) {
message += "\n" + Log.getStackTrace(eCause);
} else {
message += "\n[" + eCause.getClass().getName() + "] " + eCause.getMessage();
}
}
}
Engine.logContext.error(message);
// Just re-throw the exception
throw (EngineException) e;
} catch (Throwable e) {
Engine.logEngine.error("Context ID#" + context.contextID + " - An unexpected error has occured while building the XML document.", e);
throw new EngineException("An unexpected error has occured while building the XML document." + "Please contact Convertigo support, providing the following information:", e);
} finally {
if (context.requestedObject != null) {
Engine.logContext.debug("Requested object is billable: " + context.requestedObject.isBillable());
if (context.requestedObject.isBillable()) {
// context.outputDocument!
if (context.outputDocument == null) {
Engine.logContext.warn("Billing aborted because the generated XML document is null");
} else {
String billingClassName = context.getConnector().getBillingClassName();
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());
}
}
}
}
context.statistics.stop(t);
if (context.requestedObject != null) {
try {
Engine.theApp.billingManager.insertBilling(context);
} catch (Exception e) {
Engine.logContext.warn("Unable to insert billing ticket (the billing is thus ignored): [" + e.getClass().getName() + "] " + e.getMessage());
}
}
Engine.logContext.trace("Engine.getDocument: finished");
}
XMLUtils.logXml(outputDom, Engine.logContext, "Generated XML");
return outputDom;
}
Aggregations