Search in sources :

Example 11 with DesignerDataAccess

use of com.centurylink.mdw.designer.DesignerDataAccess in project mdw-designer by CenturyLinkCloud.

the class DesignerProxy method launchProcess.

public MDWStatusMessage launchProcess(WorkflowProcess processVersion, String masterRequestId, String owner, Long ownerId, List<VariableValue> variableValues, Long activityId) throws DataAccessException, XmlException, JSONException, IOException {
    Map<VariableVO, String> variables = new HashMap<>();
    for (VariableValue variableValue : variableValues) {
        variables.put(variableValue.getVariableVO(), variableValue.getValue());
    }
    MDWStatusMessageDocument statusMessageDoc = restfulServer.launchProcess(processVersion.getId(), masterRequestId, owner, ownerId, variables, activityId, project.isOldNamespaces());
    if (statusMessageDoc.getMDWStatusMessage().getStatusCode() != 0)
        throw new RemoteException("Error launching process: " + statusMessageDoc.getMDWStatusMessage().getStatusMessage());
    // audit log in separate dao since launch is multi-threaded
    UserActionVO userAction = new UserActionVO(project.getUser().getUsername(), Action.Run, processVersion.getActionEntity(), processVersion.getId(), processVersion.getLabel());
    userAction.setSource("Eclipse/RCP Designer");
    try {
        new DesignerDataAccess(dataAccess.getDesignerDataAccess()).auditLog(userAction);
    } catch (Exception ex) {
        throw new DataAccessException(-1, ex.getMessage(), ex);
    }
    return statusMessageDoc.getMDWStatusMessage();
}
Also used : UserActionVO(com.centurylink.mdw.model.value.user.UserActionVO) HashMap(java.util.HashMap) VariableValue(com.centurylink.mdw.plugin.designer.model.VariableValue) VariableVO(com.centurylink.mdw.model.value.variable.VariableVO) MDWStatusMessageDocument(com.centurylink.mdw.bpm.MDWStatusMessageDocument) DesignerDataAccess(com.centurylink.mdw.designer.DesignerDataAccess) RemoteException(java.rmi.RemoteException) JSONException(org.json.JSONException) TranslationException(com.centurylink.mdw.common.exception.TranslationException) AuthenticationException(com.centurylink.mdw.auth.AuthenticationException) IOException(java.io.IOException) XmlException(org.apache.xmlbeans.XmlException) ValidationException(com.centurylink.mdw.designer.utils.ValidationException) DataAccessOfflineException(com.centurylink.mdw.dataaccess.DataAccessOfflineException) ZipException(java.util.zip.ZipException) DataAccessException(com.centurylink.mdw.common.exception.DataAccessException) FileNotFoundException(java.io.FileNotFoundException) RemoteException(java.rmi.RemoteException) DataAccessException(com.centurylink.mdw.common.exception.DataAccessException)

Example 12 with DesignerDataAccess

use of com.centurylink.mdw.designer.DesignerDataAccess in project mdw-designer by CenturyLinkCloud.

the class AutoTestAntTask method runTests.

public void runTests() throws Exception {
    if (!baseDir.exists() || !baseDir.isDirectory())
        throw new IOException("Directory does not exist: " + baseDir);
    ThreadPool threadPool = new ThreadPool(threadCount);
    HashMap<String, ProcessVO> processCache = new HashMap<>();
    boolean hasGherkin = false;
    boolean hasNonGherkin = false;
    if (workflowDir != null) {
        DirectoryScanner scanner = getDirectoryScanner(workflowDir);
        scanner.scan();
        String jsonString;
        if (testResultsSummaryFile.exists() && testResultsSummaryFile.getName().endsWith(".json")) {
            jsonString = new String(Files.readAllBytes(testResultsSummaryFile.toPath()));
            if (jsonString != null && !jsonString.isEmpty())
                testCaseList = new TestCaseList(workflowDir, new JSONObject(jsonString));
        }
        if (testCaseList == null) {
            testCaseList = new TestCaseList(workflowDir);
            testCaseList.setPackageTests(new ArrayList<PackageTests>());
        }
        String workflowPath = workflowDir.toString().replace('\\', '/');
        String[] caseFilePaths = scanner.getIncludedFiles();
        for (String caseFilePath : caseFilePaths) {
            String casePath = caseFilePath.replace('\\', '/');
            int lastSlash = casePath.lastIndexOf('/');
            String pkgName = casePath.substring(0, lastSlash).replace('/', '.');
            File caseFile = new File(workflowPath + "/" + casePath);
            PackageTests pkgTests = testCaseList.getPackageTests(pkgName);
            if (pkgTests == null) {
                PackageDir pkgDir = new PackageDir(workflowDir, caseFile.getParentFile(), null);
                pkgDir.parse();
                pkgTests = new PackageTests(pkgDir);
                pkgTests.setTestCases(new ArrayList<com.centurylink.mdw.test.TestCase>());
                testCaseList.getPackageTests().add(pkgTests);
            }
            pkgTests.getTestCases().add(new com.centurylink.mdw.test.TestCase(pkgName, new AssetInfo(caseFile)));
            TestCase tc = new TestCase(pkgName, caseFile);
            if (tc.isGherkin())
                hasGherkin = true;
            else
                hasNonGherkin = true;
            testCases.add(tc);
        }
    } else if (jdbcUrl != null) {
        // db asset tests
        if (dbAssetTests == null)
            throw new BuildException("Attribute dbAssetTests required for non-VCS asset tests");
        String[] assets = dbAssetTests.split("\\s?,\\s?");
        for (String asset : assets) {
            int lastSlash = asset.lastIndexOf('/');
            String pkg = asset.substring(0, lastSlash);
            String assetName = asset.substring(lastSlash + 1);
            String language = RuleSetVO.getLanguage(assetName.substring(assetName.lastIndexOf('.')));
            RuleSetVO ruleSet = designerDataAccess.getRuleSet(assetName, language, 0);
            ruleSet.setPackageName(pkg);
            TestCase tc = new TestCase(pkg, ruleSet);
            testCases.add(tc);
        }
    } else {
        throw new BuildException("Missing attribute: workflowDir");
    }
    if (hasGherkin && hasNonGherkin)
        throw new BuildException("Gherkin/non-Gherkin tests require separate task/target executions.");
    // gradle
    boolean useStdErr = System.getProperty("org.gradle.appname") != null;
    // does
    // not
    // show
    // output
    // otherwise
    LogMessageMonitor monitor = hasGherkin ? null : new LogMessageMonitor(designerDataAccess, oldNamespaces);
    if (monitor != null)
        monitor.start(true);
    for (TestCase testCase : testCases) {
        String masterRequestId = user + "-" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
        File resultDir = new File(testResultsDir + "/" + testCase.getPrefix());
        testCase.prepare();
        TestCaseRun run;
        if (testCase.isGherkin()) {
            // User defined masterRequestId
            if (testCase.getMasterRequestId() != null) {
                if (testCase.getMasterRequestId().indexOf("${masterRequestId}") != -1) {
                    masterRequestId = testCase.getMasterRequestId().replace("${masterRequestId}", masterRequestId);
                } else
                    masterRequestId = testCase.getMasterRequestId();
            }
            testCase.setMasterRequestId(masterRequestId);
            run = new GherkinTestCaseRun(testCase, 0, masterRequestId, new DesignerDataAccess(designerDataAccess), monitor, processCache, oldNamespaces, resultDir, stubbing, stubPort);
        } else if (testCase.isGroovy())
            run = new GroovyTestCaseRun(testCase, 0, masterRequestId, new DesignerDataAccess(designerDataAccess), monitor, processCache, loadTests, true, oldNamespaces, null);
        else
            run = new TestCaseRun(testCase, 0, masterRequestId, new DesignerDataAccess(designerDataAccess), monitor, processCache, loadTests, true, oldNamespaces);
        File executeLog = new File(resultDir.getPath() + "/" + testCase.getCaseName() + ".log");
        if (!executeLog.getParentFile().exists() && !executeLog.getParentFile().mkdirs())
            throw new IOException("Unable to create test run directory: " + executeLog.getParentFile());
        PrintStream log = verbose ? new TeePrintStream(useStdErr ? System.err : System.out, executeLog) : new PrintStream(executeLog);
        run.prepareTest(false, resultDir, true, singleServer, stubbing, log);
        if (verbose)
            log("Test case prepared: " + testCase.getCaseName(), useStdErr ? Project.MSG_ERR : Project.MSG_INFO);
        masterRequestRunMap.put(run.getMasterRequestId(), run);
        threadPool.execute(run);
        updateResults(false);
        try {
            Thread.sleep(intervalSecs * 1000);
        } catch (InterruptedException e) {
        }
    }
    log("All cases prepared. Waiting for completion ...", Project.MSG_INFO);
    threadPool.shutdown();
    while (!threadPool.isTerminated()) {
        updateResults(false);
        try {
            Thread.sleep(2500);
        } catch (InterruptedException e) {
        }
    }
    if (monitor != null)
        monitor.shutdown();
    updateResults(true);
    log("All cases completed.", Project.MSG_ERR);
}
Also used : HashMap(java.util.HashMap) AssetInfo(com.centurylink.mdw.test.AssetInfo) RuleSetVO(com.centurylink.mdw.model.value.attribute.RuleSetVO) PackageTests(com.centurylink.mdw.test.PackageTests) PackageDir(com.centurylink.mdw.dataaccess.file.PackageDir) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) DesignerDataAccess(com.centurylink.mdw.designer.DesignerDataAccess) TestCaseList(com.centurylink.mdw.test.TestCaseList) PrintStream(java.io.PrintStream) TeePrintStream(com.centurylink.mdw.common.utilities.file.TeePrintStream) TeePrintStream(com.centurylink.mdw.common.utilities.file.TeePrintStream) IOException(java.io.IOException) Date(java.util.Date) JSONObject(org.json.JSONObject) ProcessVO(com.centurylink.mdw.model.value.process.ProcessVO) BuildException(org.apache.tools.ant.BuildException) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 13 with DesignerDataAccess

use of com.centurylink.mdw.designer.DesignerDataAccess in project mdw-designer by CenturyLinkCloud.

the class AutoTestAntTask method execute.

@Override
public void execute() throws BuildException {
    try {
        if (sslTrustStore != null)
            System.setProperty("javax.net.ssl.trustStore", sslTrustStore.getAbsolutePath());
        DesignerDataAccess.getAuthenticator().authenticate(user, password);
        RestfulServer restfulServer = new RestfulServer(jdbcUrl == null ? "dummy" : jdbcUrl, user, serverUrl.toString());
        if (workflowDir != null) {
            // vcs-based assets
            VersionControl versionControl = new VersionControlGit();
            versionControl.connect(null, null, null, workflowDir);
            restfulServer.setVersionControl(versionControl);
            restfulServer.setRootDirectory(workflowDir);
            restfulServer.setDatabaseUrl("jdbc://dummy");
            designerDataAccess = new DesignerDataAccess(restfulServer, null, user, false);
            designerDataAccess.setCurrentServer(restfulServer);
        } else {
            designerDataAccess = new DesignerDataAccess(restfulServer, null, user, oldNamespaces);
            if (designerDataAccess.getUser(user) == null)
                throw new BuildException("User '" + user + "' not found to run automated tests for this environment.");
            if (!designerDataAccess.getUser(user).hasRole(UserGroupVO.COMMON_GROUP, UserRoleVO.PROCESS_EXECUTION) && !designerDataAccess.getUser(user).hasRole(UserGroupVO.SITE_ADMIN_GROUP, UserRoleVO.PROCESS_EXECUTION))
                throw new BuildException("User '" + user + "' not authorized to run automated tests for this environment.");
        }
        VariableTypeCache.loadCache(designerDataAccess.getVariableTypes());
        log("Setup completed for test suite: '" + suiteName + "'", Project.MSG_ERR);
        try {
            if (stubbing) {
                Stubber stubber = new Stubber() {

                    public String processMessage(String masterRequestId, String request) {
                        try {
                            TestCaseRun run = masterRequestRunMap.get(masterRequestId);
                            if (run == null) {
                                JSONObject requestJson = null;
                                // mdw6
                                ActivityStubRequest activityStubRequest = null;
                                ActivityRuntimeContext activityRuntimeContext = null;
                                // mdw6
                                AdapterStubRequest adapterStubRequest = null;
                                if (request != null && request.trim().startsWith("{")) {
                                    try {
                                        requestJson = new JSONObject(request);
                                    } catch (JSONException ex) {
                                    // unparseable -- handle old way for
                                    // adapter stubbing
                                    }
                                    if (requestJson != null) {
                                        if (requestJson.has(ActivityStubRequest.JSON_NAME)) {
                                            activityStubRequest = new ActivityStubRequest(requestJson);
                                            activityRuntimeContext = activityStubRequest.getRuntimeContext();
                                        } else if (requestJson.has("ActivityRuntimeContext")) {
                                            activityRuntimeContext = new ActivityRuntimeContext(requestJson);
                                        } else if (requestJson.has(AdapterStubRequest.JSON_NAME)) {
                                            adapterStubRequest = new AdapterStubRequest(requestJson);
                                        }
                                    }
                                }
                                if (activityRuntimeContext != null) {
                                    if (activityStubRequest != null) {
                                        // mdw6+
                                        ActivityStubResponse activityStubResponse = new ActivityStubResponse();
                                        activityStubResponse.setPassthrough(true);
                                        return activityStubResponse.getJson().toString(2);
                                    } else {
                                        return "(EXECUTE_ACTIVITY)";
                                    }
                                } else {
                                    if (adapterStubRequest != null) {
                                        // mdw6+
                                        AdapterStubResponse stubResponse = new AdapterStubResponse(AdapterActivity.MAKE_ACTUAL_CALL);
                                        stubResponse.setPassthrough(true);
                                        return stubResponse.getJson().toString(2);
                                    } else {
                                        return AdapterActivity.MAKE_ACTUAL_CALL;
                                    }
                                }
                            }
                            return run.getStubResponse(masterRequestId, request, run.getRunNumber());
                        } catch (Exception ex) {
                            log(ex.getMessage(), ex, Project.MSG_ERR);
                            return null;
                        }
                    }
                };
                if (StubServer.isRunning())
                    StubServer.stop();
                StubServer.start(restfulServer, stubPort, stubber, this.oldNamespaces);
            }
            runTests();
        } finally {
            // try not to leave the socket connection open
            StubServer.stop();
        }
    } catch (BuildException ex) {
        throw ex;
    } catch (Exception ex) {
        try {
            updateResults(true);
        } catch (BuildException bex) {
            throw bex;
        } catch (IOException ioex) {
            log(ioex.getMessage(), ioex, Project.MSG_ERR);
        }
        log(ex.getMessage(), ex, Project.MSG_ERR);
        throw new BuildException(ex);
    }
}
Also used : VersionControlGit(com.centurylink.mdw.dataaccess.file.VersionControlGit) ActivityStubResponse(com.centurylink.mdw.model.value.activity.ActivityStubResponse) JSONException(org.json.JSONException) RestfulServer(com.centurylink.mdw.designer.utils.RestfulServer) ActivityStubRequest(com.centurylink.mdw.model.value.activity.ActivityStubRequest) IOException(java.io.IOException) VersionControl(com.centurylink.mdw.dataaccess.VersionControl) JSONException(org.json.JSONException) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) ActivityRuntimeContext(com.centurylink.mdw.model.value.activity.ActivityRuntimeContext) AdapterStubRequest(com.centurylink.mdw.model.value.event.AdapterStubRequest) JSONObject(org.json.JSONObject) Stubber(com.centurylink.mdw.designer.testing.StubServer.Stubber) DesignerDataAccess(com.centurylink.mdw.designer.DesignerDataAccess) BuildException(org.apache.tools.ant.BuildException) AdapterStubResponse(com.centurylink.mdw.model.value.event.AdapterStubResponse)

Example 14 with DesignerDataAccess

use of com.centurylink.mdw.designer.DesignerDataAccess in project mdw-designer by CenturyLinkCloud.

the class ControlCommandShell method main.

public static void main(String[] args) throws Exception {
    String serverUrl = null;
    String cuid = null;
    String password = null;
    String command = null;
    boolean singleCommandMode = false;
    int nonOptions = 0;
    int commandArgIndex = 0;
    for (int i = 0; i < args.length; i++) {
        if (args[i].length() >= 2 && args[i].charAt(0) == '-') {
            switch(args[i].charAt(1)) {
                case 'c':
                    singleCommandMode = true;
                    break;
                case 'u':
                    cuid = args[i].substring(2);
                    break;
                case 'p':
                    password = args[i].substring(2);
                    break;
                default:
                    usage();
            }
        } else {
            nonOptions++;
            if (nonOptions == 1)
                serverUrl = args[i];
            else if (nonOptions == 2) {
                command = args[i];
                commandArgIndex = i + 1;
            } else {
                if (singleCommandMode)
                    break;
                else
                    usage();
            }
        }
    }
    if (serverUrl == null)
        usage();
    else {
        if (singleCommandMode && command == null)
            usage();
        DesignerDataAccess dao;
        try {
            BufferedReader in = null;
            if (cuid == null) {
                in = new BufferedReader(new InputStreamReader(System.in));
                System.out.print("User ID: ");
                cuid = in.readLine();
            }
            if (password == null) {
                if (in == null)
                    in = new BufferedReader(new InputStreamReader(System.in));
                password = readPassword("Password: ", in);
            }
            Server server = new Server();
            if (serverUrl.startsWith("jdbc:oracle:thin:")) {
                serverUrl = serverUrl.substring(0, 17) + cuid + "/" + password + serverUrl.substring(17);
                server.setDatabaseUrl(serverUrl);
                dao = new DesignerDataAccess(server, null, null);
            } else {
                server.setServerUrl(serverUrl);
                if (!password.equals("ignore"))
                    DesignerDataAccess.getAuthenticator().authenticate(cuid, password);
                dao = new DesignerDataAccess(server, null, cuid);
            }
            ControlCommandShell shell = new ControlCommandShell(dao);
            if (singleCommandMode) {
                TestFileLine cmd = new TestFileLine(command);
                for (int i = commandArgIndex; i < args.length; i++) {
                    String word = args[i];
                    if (word.charAt(0) == '@') {
                        File file = new File(word.substring(1));
                        char[] parseBuffer;
                        FileReader reader = new FileReader(file);
                        parseBuffer = new char[(int) file.length()];
                        reader.read(parseBuffer);
                        reader.close();
                        word = new String(parseBuffer);
                    }
                    cmd.addWord(word);
                }
                shell.executeCommand(cmd);
            } else if (command == null) {
                // interactive mode
                if (in == null)
                    in = new BufferedReader(new InputStreamReader(System.in));
                boolean done = false;
                while (!done) {
                    System.out.print("mdw> ");
                    try {
                        TestFileLine cmd = readLine(in);
                        if (cmd == null || cmd.getWord(0).equals(EXIT))
                            done = true;
                        else
                            shell.executeCommand(cmd);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                // batch mode
                TestFile commands = new TestFile(null, command);
                shell.execute(commands);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) Server(com.centurylink.mdw.designer.utils.Server) IOException(java.io.IOException) ParseException(java.text.ParseException) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) DesignerDataAccess(com.centurylink.mdw.designer.DesignerDataAccess) File(java.io.File)

Example 15 with DesignerDataAccess

use of com.centurylink.mdw.designer.DesignerDataAccess in project mdw-designer by CenturyLinkCloud.

the class GroovyTestCaseScript method request.

public ApiRequest request(String target, Map<String, String> options, Closure<?> cl) throws TestException {
    int dotPostmanSlash = target.lastIndexOf(".postman/");
    if (dotPostmanSlash == -1)
        throw new TestException("Bad API test path: " + target);
    String assetName = target.substring(0, dotPostmanSlash + 8);
    try {
        DesignerDataAccess dao = getTestCaseRun().dao;
        RuleSetVO ruleSetVO = dao.getRuleSet(assetName, null, 0);
        if (ruleSetVO == null)
            throw new TestException("API test case asset not found: " + assetName);
        TestCase apiTestCase = new TestCase(ruleSetVO.getPackageName(), ruleSetVO.getRawFile());
        String itemDetails = target.substring(dotPostmanSlash + 9);
        int colon = itemDetails.indexOf(":");
        String method = itemDetails.substring(0, colon);
        if (method.equals("DEL"))
            method = "DELETE";
        TestCaseItem item = apiTestCase.getTestCaseItem(ruleSetVO, method, itemDetails.substring(colon + 1));
        if (item == null)
            throw new TestException("Test case item not found: " + itemDetails);
        apiTestCase.addItem(item);
        String resultsPath = ruleSetVO.getRawFile().getAbsolutePath();
        apiTestCase.setResultDirectory(new File(resultsPath.substring(0, resultsPath.indexOf("\\assets\\")) + "\\testResults\\" + ruleSetVO.getPackageName()));
        apiRequest = new ApiRequest(apiTestCase, options);
        if (cl != null) {
            cl.setResolveStrategy(Closure.DELEGATE_FIRST);
            cl.setDelegate(apiRequest);
            cl.call();
        }
        return apiRequest;
    } catch (TestException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new TestException(ex.getMessage(), ex);
    }
}
Also used : DesignerDataAccess(com.centurylink.mdw.designer.DesignerDataAccess) File(java.io.File) IOException(java.io.IOException) MbengException(com.qwest.mbeng.MbengException) RuleSetVO(com.centurylink.mdw.model.value.attribute.RuleSetVO)

Aggregations

DesignerDataAccess (com.centurylink.mdw.designer.DesignerDataAccess)15 IOException (java.io.IOException)10 ProcessInstanceVO (com.centurylink.mdw.model.value.process.ProcessInstanceVO)6 Server (com.centurylink.mdw.designer.utils.Server)5 JSONException (org.json.JSONException)5 ProcessVO (com.centurylink.mdw.model.value.process.ProcessVO)4 HashMap (java.util.HashMap)4 AuthenticationException (com.centurylink.mdw.auth.AuthenticationException)3 DataAccessException (com.centurylink.mdw.common.exception.DataAccessException)3 TranslationException (com.centurylink.mdw.common.exception.TranslationException)3 DataAccessOfflineException (com.centurylink.mdw.dataaccess.DataAccessOfflineException)3 RestfulServer (com.centurylink.mdw.designer.utils.RestfulServer)3 ValidationException (com.centurylink.mdw.designer.utils.ValidationException)3 File (java.io.File)3 FileNotFoundException (java.io.FileNotFoundException)3 VersionControl (com.centurylink.mdw.dataaccess.VersionControl)2 ProcessInstancePage (com.centurylink.mdw.designer.runtime.ProcessInstancePage)2 RuleSetVO (com.centurylink.mdw.model.value.attribute.RuleSetVO)2 ProcessList (com.centurylink.mdw.model.value.process.ProcessList)2 RemoteException (java.rmi.RemoteException)2