From ba445d2db3fcd41715d04142040a0dc64617de41 Mon Sep 17 00:00:00 2001 From: ioanvranauhp Date: Thu, 8 Jan 2015 09:27:42 +0200 Subject: [PATCH] removed ScoreSSHShell, ScoreSSHShellLogOff and ScoreSSHShellLogon Actions. Also removed the simulator package, that depend on jcterm. --- score-ssh/pom.xml | 15 +- .../content/ssh/actions/SSHShellAction.java | 71 ---- .../content/ssh/actions/SSHShellLogoff.java | 45 --- .../content/ssh/actions/SSHShellLogon.java | 60 --- .../ssh/entities/ExpectCommandResult.java | 17 - .../content/ssh/services/SSHService.java | 26 +- .../ssh/services/actions/ScoreSSHShell.java | 96 ----- .../actions/ScoreSSHShellCommand.java | 7 +- .../services/actions/ScoreSSHShellLogOff.java | 41 -- .../services/actions/ScoreSSHShellLogon.java | 71 ---- .../ssh/services/impl/SSHServiceImpl.java | 74 +--- .../content/ssh/utils/CacheUtils.java | 8 +- .../content/ssh/utils/SSHSessionResource.java | 2 +- .../ssh/utils/simulator/IScriptRunner.java | 13 - .../ssh/utils/simulator/SafeMatcher.java | 32 -- .../ssh/utils/simulator/ScriptLines.java | 49 --- .../ssh/utils/simulator/ScriptModel.java | 110 ------ .../ssh/utils/simulator/ScriptRunner.java | 370 ------------------ .../ssh/utils/simulator/ShellSimulator.java | 219 ----------- .../utils/simulator/elements/AlwaysOn.java | 46 --- .../ssh/utils/simulator/elements/Expect.java | 70 ---- .../simulator/elements/ExpectEndsWith.java | 14 - .../simulator/elements/ExpectLastLine.java | 19 - .../simulator/elements/ScriptElement.java | 18 - .../ssh/utils/simulator/elements/Send.java | 58 --- .../utils/simulator/elements/SendChar.java | 21 - .../elements/SetSimulatorCapture.java | 16 - .../SimulatorModificationCommand.java | 34 -- .../simulator/visualization/ByteWrapper.java | 44 --- .../visualization/IShellVisualizer.java | 10 - .../visualization/LinearUpdateTask.java | 43 -- .../visualization/ScreenEmulator.java | 351 ----------------- .../simulator/visualization/ScreenTask.java | 15 - .../ssh/services/impl/SSHServiceImplTest.java | 79 +--- .../ssh/utils/simulator/SafeMacherTest.java | 17 - .../ssh/utils/simulator/ScriptLinesTest.java | 51 --- .../ssh/utils/simulator/ScriptModelTest.java | 80 ---- .../ssh/utils/simulator/ScriptRunnerTest.java | 161 -------- .../utils/simulator/ShellSimulatorTest.java | 155 -------- .../simulator/elements/AlwaysOnTest.java | 71 ---- .../elements/ExpectEndsWithTest.java | 36 -- .../elements/ExpectLastLineTest.java | 37 -- .../simulator/elements/SendCharTest.java | 34 -- .../elements/SetSimulatorCaptureTest.java | 35 -- .../SimulatorModificationCommandTest.java | 35 -- .../visualization/ByteWrapperTest.java | 80 ---- .../visualization/LinearUpdateTaskTest.java | 79 ---- .../visualization/ScreenEmulatorTest.java | 136 ------- 48 files changed, 25 insertions(+), 3146 deletions(-) delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/actions/SSHShellAction.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/actions/SSHShellLogoff.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/actions/SSHShellLogon.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/entities/ExpectCommandResult.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShell.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShellLogOff.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShellLogon.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/IScriptRunner.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/SafeMatcher.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ScriptLines.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ScriptModel.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ScriptRunner.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ShellSimulator.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/AlwaysOn.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/Expect.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/ExpectEndsWith.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/ExpectLastLine.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/ScriptElement.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/Send.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/SendChar.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/SetSimulatorCapture.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/SimulatorModificationCommand.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/ByteWrapper.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/IShellVisualizer.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/LinearUpdateTask.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/ScreenEmulator.java delete mode 100644 score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/ScreenTask.java delete mode 100644 score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/SafeMacherTest.java delete mode 100644 score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ScriptLinesTest.java delete mode 100644 score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ScriptModelTest.java delete mode 100644 score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ScriptRunnerTest.java delete mode 100644 score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ShellSimulatorTest.java delete mode 100644 score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/AlwaysOnTest.java delete mode 100644 score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/ExpectEndsWithTest.java delete mode 100644 score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/ExpectLastLineTest.java delete mode 100644 score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/SendCharTest.java delete mode 100644 score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/SetSimulatorCaptureTest.java delete mode 100644 score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/SimulatorModificationCommandTest.java delete mode 100644 score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/visualization/ByteWrapperTest.java delete mode 100644 score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/visualization/LinearUpdateTaskTest.java delete mode 100644 score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/visualization/ScreenEmulatorTest.java diff --git a/score-ssh/pom.xml b/score-ssh/pom.xml index 0de940e39..2b13cb1d7 100644 --- a/score-ssh/pom.xml +++ b/score-ssh/pom.xml @@ -31,14 +31,14 @@ - Mihai David - mihai.david@hp.com + Octavian Hasna + octavian-lucian.hasna@hp.com HP Software http://www8.hp.com/us/en/software/enterprise-software.html - Adina Tusa - adina.tusa@hp.com + Ioan Vranau + ioan.vranau@hp.com HP Software http://www8.hp.com/us/en/software/enterprise-software.html @@ -81,11 +81,6 @@ jsch 0.1.50 - - com.jcraft - jcterm - 0.0.11 - dom4j dom4j @@ -94,7 +89,7 @@ bouncycastle bcprov-jdk15 - 144 + 140 diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/actions/SSHShellAction.java b/score-ssh/src/main/java/org/openscore/content/ssh/actions/SSHShellAction.java deleted file mode 100644 index f566a3548..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/actions/SSHShellAction.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.openscore.content.ssh.actions; - -import com.hp.oo.sdk.content.annotations.Action; -import com.hp.oo.sdk.content.annotations.Output; -import com.hp.oo.sdk.content.annotations.Param; -import com.hp.oo.sdk.content.annotations.Response; -import com.hp.oo.sdk.content.plugin.ActionMetadata.MatchType; -import com.hp.oo.sdk.content.plugin.ActionMetadata.ResponseType; -import com.hp.oo.sdk.content.plugin.GlobalSessionObject; -import org.openscore.content.ssh.entities.SSHConnection; -import org.openscore.content.ssh.entities.SSHShellInputs; -import org.openscore.content.ssh.services.actions.SSHShellAbstract; -import org.openscore.content.ssh.services.actions.ScoreSSHShell; -import org.openscore.content.ssh.utils.Constants; - -import java.util.Map; - -/** - * @author ioanvranauhp - * Date: 11/03/14 - */ -public class SSHShellAction extends SSHShellAbstract { - - @Action(name = "SSH Shell", - outputs = { - @Output(Constants.OutputNames.RETURN_CODE), - @Output(Constants.OutputNames.RETURN_RESULT), - @Output(Constants.OutputNames.EXCEPTION), - @Output(Constants.STDOUT), - @Output(Constants.VISUALIZED) - }, - responses = { - @Response(text = Constants.ResponseNames.SUCCESS, field = Constants.OutputNames.RETURN_CODE, value = Constants.ReturnCodes.RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), - @Response(text = Constants.ResponseNames.FAILURE, field = Constants.OutputNames.RETURN_CODE, value = Constants.ReturnCodes.RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) - } - ) - public Map runSshExpectCommand( - @Param(value = Constants.InputNames.HOST, required = true) String host, - @Param(Constants.InputNames.PORT) String port, - @Param(value = Constants.InputNames.USERNAME, required = true) String username, - @Param(value = Constants.InputNames.PASSWORD, required = true, encrypted = true) String password, - @Param(Constants.PRIVATE_KEY_FILE) String privateKeyFile, - @Param(Constants.KNOWN_HOSTS_POLICY) String knownHostsPolicy, - @Param(Constants.KNOWN_HOSTS_PATH) String knownHostsPath, - @Param(value = Constants.COMMAND, required = true) String command, - @Param(Constants.InputNames.CHARACTER_SET) String characterSet, - @Param(Constants.CHARACTER_DELAY) String characterDelay, - @Param(Constants.NEWLINE_SEQUENCE) String newlineCharacters, - @Param(Constants.InputNames.TIMEOUT) String timeout, - @Param(Constants.SSH_SESSIONS_DEFAULT_ID) GlobalSessionObject> globalSessionObject, - @Param(Constants.SESSION_ID) String sessionId) { - - SSHShellInputs sshShellInputs = new SSHShellInputs(); - sshShellInputs.setHost(host); - sshShellInputs.setPort(port); - sshShellInputs.setUsername(username); - sshShellInputs.setPassword(password); - sshShellInputs.setPrivateKeyFile(privateKeyFile); - sshShellInputs.setKnownHostsPolicy(knownHostsPolicy); - sshShellInputs.setKnownHostsPath(knownHostsPath); - sshShellInputs.setCommand(command); - sshShellInputs.setCharacterSet(characterSet); - sshShellInputs.setCharacterDelay(characterDelay); - sshShellInputs.setNewlineCharacters(newlineCharacters); - sshShellInputs.setTimeout(timeout); - sshShellInputs.setSshGlobalSessionObject(globalSessionObject); - sshShellInputs.setSessionId(sessionId); - - return new ScoreSSHShell().execute(sshShellInputs); - } -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/actions/SSHShellLogoff.java b/score-ssh/src/main/java/org/openscore/content/ssh/actions/SSHShellLogoff.java deleted file mode 100644 index 27ad10f0b..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/actions/SSHShellLogoff.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.openscore.content.ssh.actions; - -import com.hp.oo.sdk.content.annotations.Action; -import com.hp.oo.sdk.content.annotations.Output; -import com.hp.oo.sdk.content.annotations.Param; -import com.hp.oo.sdk.content.annotations.Response; -import com.hp.oo.sdk.content.plugin.ActionMetadata.MatchType; -import com.hp.oo.sdk.content.plugin.ActionMetadata.ResponseType; -import com.hp.oo.sdk.content.plugin.GlobalSessionObject; -import org.openscore.content.ssh.services.actions.SSHShellAbstract; -import org.openscore.content.ssh.services.actions.ScoreSSHShellLogOff; -import org.openscore.content.ssh.entities.SSHConnection; -import org.openscore.content.ssh.entities.SSHShellInputs; -import org.openscore.content.ssh.utils.Constants; - -import java.util.Map; - -/** - * @author ioanvranauhp - * Date: 11/03/14 - */ -public class SSHShellLogoff extends SSHShellAbstract { - - @Action(name = "SSH Shell Logoff", - outputs = { - @Output(Constants.OutputNames.RETURN_CODE), - @Output(Constants.OutputNames.RETURN_RESULT), - @Output(Constants.OutputNames.EXCEPTION) - }, - responses = { - @Response(text = Constants.ResponseNames.SUCCESS, field = Constants.OutputNames.RETURN_CODE, value = Constants.ReturnCodes.RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), - @Response(text = Constants.ResponseNames.FAILURE, field = Constants.OutputNames.RETURN_CODE, value = Constants.ReturnCodes.RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) - } - ) - public Map sshLogoff( - @Param(Constants.SSH_SESSIONS_DEFAULT_ID) GlobalSessionObject> globalSessionObject, - @Param(value = Constants.SESSION_ID, required = true) String sessionId) { - - SSHShellInputs sshShellInputs = new SSHShellInputs(); - sshShellInputs.setSshGlobalSessionObject(globalSessionObject); - sshShellInputs.setSessionId(sessionId); - - return new ScoreSSHShellLogOff().execute(sshShellInputs); - } -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/actions/SSHShellLogon.java b/score-ssh/src/main/java/org/openscore/content/ssh/actions/SSHShellLogon.java deleted file mode 100644 index e047cb908..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/actions/SSHShellLogon.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.openscore.content.ssh.actions; - -import com.hp.oo.sdk.content.annotations.Action; -import com.hp.oo.sdk.content.annotations.Output; -import com.hp.oo.sdk.content.annotations.Param; -import com.hp.oo.sdk.content.annotations.Response; -import com.hp.oo.sdk.content.plugin.ActionMetadata.MatchType; -import com.hp.oo.sdk.content.plugin.ActionMetadata.ResponseType; -import com.hp.oo.sdk.content.plugin.GlobalSessionObject; -import org.openscore.content.ssh.entities.SSHConnection; -import org.openscore.content.ssh.entities.SSHShellInputs; -import org.openscore.content.ssh.services.actions.SSHShellAbstract; -import org.openscore.content.ssh.services.actions.ScoreSSHShellLogon; -import org.openscore.content.ssh.utils.Constants; - -import java.util.Map; - -/** - * @author ioanvranauhp - * Date: 11/03/14 - */ -public class SSHShellLogon extends SSHShellAbstract { - - @Action(name = "SSH Shell Logon", - outputs = { - @Output(Constants.OutputNames.RETURN_CODE), - @Output(Constants.OutputNames.RETURN_RESULT), - @Output(Constants.SESSION_ID), - @Output(Constants.OutputNames.EXCEPTION) - }, - responses = { - @Response(text = Constants.ResponseNames.SUCCESS, field = Constants.OutputNames.RETURN_CODE, value = Constants.ReturnCodes.RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), - @Response(text = Constants.ResponseNames.FAILURE, field = Constants.OutputNames.RETURN_CODE, value = Constants.ReturnCodes.RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) - } - ) - public Map sshLogon( - @Param(value = Constants.InputNames.HOST, required = true) String host, - @Param(Constants.InputNames.PORT) String port, - @Param(value = Constants.InputNames.USERNAME, required = true) String username, - @Param(value = Constants.InputNames.PASSWORD, required = true, encrypted = true) String password, - @Param(Constants.PRIVATE_KEY_FILE) String privateKeyFile, - @Param(Constants.KNOWN_HOSTS_POLICY) String knownHostsPolicy, - @Param(Constants.KNOWN_HOSTS_PATH) String knownHostsPath, - @Param(Constants.SSH_SESSIONS_DEFAULT_ID) GlobalSessionObject> globalSessionObject) { - - SSHShellInputs sshShellInputs = new SSHShellInputs(); - sshShellInputs.setHost(host); - sshShellInputs.setPort(port); - sshShellInputs.setUsername(username); - sshShellInputs.setPassword(password); - sshShellInputs.setPrivateKeyFile(privateKeyFile); - sshShellInputs.setSshGlobalSessionObject(globalSessionObject); - sshShellInputs.setKnownHostsPolicy(knownHostsPolicy); - sshShellInputs.setKnownHostsPath(knownHostsPath); - - return new ScoreSSHShellLogon().execute(sshShellInputs); - } - - -} \ No newline at end of file diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/entities/ExpectCommandResult.java b/score-ssh/src/main/java/org/openscore/content/ssh/entities/ExpectCommandResult.java deleted file mode 100644 index 49a84c8f1..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/entities/ExpectCommandResult.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.openscore.content.ssh.entities; - -/** - * @author ioanvranauhp - * Date: 10/29/14 - */ -public class ExpectCommandResult extends CommandResult { - private String expectXmlOutputs; - - public String getExpectXmlOutputs() { - return expectXmlOutputs; - } - - public void setExpectXmlOutputs(String expectXmlOutputs) { - this.expectXmlOutputs = expectXmlOutputs; - } -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/services/SSHService.java b/score-ssh/src/main/java/org/openscore/content/ssh/services/SSHService.java index 62dbe63e6..85d137e95 100644 --- a/score-ssh/src/main/java/org/openscore/content/ssh/services/SSHService.java +++ b/score-ssh/src/main/java/org/openscore/content/ssh/services/SSHService.java @@ -1,11 +1,10 @@ package org.openscore.content.ssh.services; import com.hp.oo.sdk.content.plugin.GlobalSessionObject; -import org.openscore.content.ssh.entities.CommandResult; -import org.openscore.content.ssh.entities.ExpectCommandResult; -import org.openscore.content.ssh.entities.SSHConnection; import com.jcraft.jsch.Channel; import com.jcraft.jsch.Session; +import org.openscore.content.ssh.entities.CommandResult; +import org.openscore.content.ssh.entities.SSHConnection; import java.util.Map; @@ -34,13 +33,6 @@ public interface SSHService extends AutoCloseable { */ boolean isConnected(); - /** - * Checks the SSH channel for the Expect command. - * - * @return true if the SSH channel is opened, otherwise false. - */ - boolean isExpectChannelConnected(); - /** * Close the SSH session. */ @@ -60,19 +52,7 @@ public interface SSHService extends AutoCloseable { * @param sessionParam The cache (Operation Orchestration session). * @param sessionId The key of the Operation Orchestration session. */ - void removeFromCache(GlobalSessionObject> sessionParam, String sessionId); - - /** - * Run a expect command through SSH protocol. - * - * @param command The list of commands (send and expect). - * @param characterSet The character set for the command and for the output of the command. - * @param newline The character(s) used to separate send and expect commands and also the enter key pressed. - * @param writeCharacterTimeout The write character delay. - * @param connectTimeout The channel connection timeout. - * @param commandTimeout The command timeout. @return the result of the expect commands - */ - ExpectCommandResult runExpectCommand(String command, String characterSet, String newline, int writeCharacterTimeout, int connectTimeout, int commandTimeout); + void removeFromCache(GlobalSessionObject> sessionParam, String sessionId); /** * Create a local SSH tunnel (connect to a local port on the engine, which is then forwarded to the remote end of the tunnel. diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShell.java b/score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShell.java deleted file mode 100644 index 032c76426..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShell.java +++ /dev/null @@ -1,96 +0,0 @@ -package org.openscore.content.ssh.services.actions; - -import org.openscore.content.ssh.entities.ConnectionDetails; -import org.openscore.content.ssh.entities.ExpectCommandResult; -import org.openscore.content.ssh.entities.KeyFile; -import org.openscore.content.ssh.entities.KnownHostsFile; -import org.openscore.content.ssh.entities.SSHShellInputs; -import org.openscore.content.ssh.services.SSHService; -import org.openscore.content.ssh.services.impl.SSHServiceImpl; -import org.openscore.content.ssh.utils.Constants; -import org.openscore.content.ssh.utils.StringUtils; - -import java.nio.file.Path; -import java.util.HashMap; -import java.util.Map; - -/** - * Created by ioanvranauhp on 11/5/2014. - */ -public class ScoreSSHShell extends SSHShellAbstract { - - /** - * This method executes a ssh shell operations based on the sshShellInputs parameter - * You ned to populate sshShellInputs parameter with the following values: - * host, port, username, password, privateKeyFile, command, characterSet, characterDelay, newlineCharacters, timeout, - * globalSessionObject, sessionObject, sessionId - * - * @param sshShellInputs - */ - public Map execute(SSHShellInputs sshShellInputs) { - - Map returnResult = new HashMap<>(); - boolean providerAdded = addSecurityProvider(); - - try { - if (StringUtils.isEmpty(sshShellInputs.getCommand())) { - throw new RuntimeException(COMMAND_IS_NOT_SPECIFIED_MESSAGE); - } - - // default values - int portNumber = StringUtils.toInt(sshShellInputs.getPort(), Constants.DEFAULT_PORT); - String knownHostsPolicy = StringUtils.toNotEmptyString(sshShellInputs.getKnownHostsPolicy(), Constants.DEFAULT_KNOWN_HOSTS_POLICY); - Path knownHostsPath = StringUtils.toPath(sshShellInputs.getKnownHostsPath(), Constants.DEFAULT_KNOWN_HOSTS_PATH); - sshShellInputs.setCharacterSet(StringUtils.toNotEmptyString(sshShellInputs.getCharacterSet(), Constants.DEFAULT_CHARACTER_SET)); - int characterDelayNumber = StringUtils.toInt(sshShellInputs.getCharacterDelay(), Constants.DEFAULT_WRITE_CHARACTER_TIMEOUT); - String newline = StringUtils.toNewline(sshShellInputs.getNewlineCharacters()); - int timeoutNumber = StringUtils.toInt(sshShellInputs.getTimeout(), Constants.DEFAULT_TIMEOUT); - - // configure ssh parameters - ConnectionDetails connection = new ConnectionDetails(sshShellInputs.getHost(), portNumber, sshShellInputs.getUsername(), sshShellInputs.getPassword()); - KeyFile keyFile = getKeyFile(sshShellInputs.getPrivateKeyFile(), sshShellInputs.getPassword()); - KnownHostsFile knownHostsFile = new KnownHostsFile(knownHostsPath, knownHostsPolicy); - - SSHService service = getSshService(sshShellInputs, connection, keyFile, knownHostsFile); - - // run the SSH Expect command - ExpectCommandResult commandResult = service.runExpectCommand( - sshShellInputs.getCommand(), - sshShellInputs.getCharacterSet(), - newline, - characterDelayNumber, - Constants.DEFAULT_CONNECT_TIMEOUT, - timeoutNumber); - - // populate the results - populateResult(returnResult, commandResult); - } catch (Exception e) { - populateResult(returnResult, e); - } finally { - if (providerAdded) { - removeSecurityProvider(); - } - } - return returnResult; - } - - private SSHService getSshService(SSHShellInputs sshShellInputs, ConnectionDetails connection, KeyFile keyFile, KnownHostsFile knownHostsFile) { - SSHService service = null; - if (sshShellInputs.getSessionId() != null) { - // get the cached SSH session - service = getFromCache(sshShellInputs, sshShellInputs.getSessionId()); // TODO SESSION Object - } - if (service == null || !service.isConnected() || !service.isExpectChannelConnected()) { - service = new SSHServiceImpl(connection, keyFile, knownHostsFile, Constants.DEFAULT_CONNECT_TIMEOUT, true); - } - return service; - } - - - private void populateResult(Map returnResult, ExpectCommandResult commandResult) { - returnResult.put(Constants.STDOUT, commandResult.getStandardOutput()); - returnResult.put(Constants.VISUALIZED, commandResult.getExpectXmlOutputs()); - returnResult.put(Constants.OutputNames.RETURN_RESULT, commandResult.getStandardOutput()); - returnResult.put(Constants.OutputNames.RETURN_CODE, Constants.ReturnCodes.RETURN_CODE_SUCCESS); - } -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShellCommand.java b/score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShellCommand.java index ab2745c92..b534b6b6f 100644 --- a/score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShellCommand.java +++ b/score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShellCommand.java @@ -1,10 +1,6 @@ package org.openscore.content.ssh.services.actions; -import org.openscore.content.ssh.entities.CommandResult; -import org.openscore.content.ssh.entities.ConnectionDetails; -import org.openscore.content.ssh.entities.KeyFile; -import org.openscore.content.ssh.entities.KnownHostsFile; -import org.openscore.content.ssh.entities.SSHShellInputs; +import org.openscore.content.ssh.entities.*; import org.openscore.content.ssh.services.SSHService; import org.openscore.content.ssh.services.impl.SSHServiceImpl; import org.openscore.content.ssh.utils.Constants; @@ -107,7 +103,6 @@ private void handleSessionClosure(SSHShellInputs sshShellInputs, SSHService serv protected void cleanupService(SSHShellInputs sshShellInputs, SSHService service, String sessionId) { service.close(); service.removeFromCache(sshShellInputs.getSshGlobalSessionObject(), sessionId); -// service.removeFromCache(sshShellInputs.getSshSessionObject(), sessionId); //TODO session object } private void populateResult(Map returnResult, CommandResult commandResult) { diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShellLogOff.java b/score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShellLogOff.java deleted file mode 100644 index 05e5abbae..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShellLogOff.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.openscore.content.ssh.services.actions; - -import org.openscore.content.ssh.entities.SSHShellInputs; -import org.openscore.content.ssh.services.SSHService; -import org.openscore.content.ssh.utils.Constants; - -import java.util.HashMap; -import java.util.Map; - -/** - * Created by vranau on 11/5/2014. - */ -public class ScoreSSHShellLogOff extends SSHShellAbstract { - - public static final String SESSION_ID_NOT_IN_SESSION_CONTEXT_MESSAGE = "Could not find sessionId in the session context."; - - public Map execute(SSHShellInputs sshShellInputs) { - Map returnResult = new HashMap<>(); - try { - // get the cached SSH session - SSHService service = getFromCache(sshShellInputs, sshShellInputs.getSessionId()); // TODO SESSION OBJECT - if (service == null) { - throw new RuntimeException(SESSION_ID_NOT_IN_SESSION_CONTEXT_MESSAGE); - } - cleanupService(sshShellInputs, service); - - - returnResult.put(Constants.OutputNames.RETURN_CODE, Constants.ReturnCodes.RETURN_CODE_SUCCESS); - } catch (Exception e) { - populateResult(returnResult, e); - } - return returnResult; - } - - protected void cleanupService(SSHShellInputs sshShellInputs, SSHService service) { - // close the SSH session - service.close(); - service.removeFromCache(sshShellInputs.getSshGlobalSessionObject(), sshShellInputs.getSessionId()); -// service.removeFromCache(sshShellInputs.getSshSessionObject(), sshShellInputs.getSessionId()); TODO - } -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShellLogon.java b/score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShellLogon.java deleted file mode 100644 index aa8d15059..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/services/actions/ScoreSSHShellLogon.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.openscore.content.ssh.services.actions; - -import org.openscore.content.ssh.entities.ConnectionDetails; -import org.openscore.content.ssh.entities.KeyFile; -import org.openscore.content.ssh.entities.KnownHostsFile; -import org.openscore.content.ssh.entities.SSHShellInputs; -import org.openscore.content.ssh.services.SSHService; -import org.openscore.content.ssh.services.impl.SSHServiceImpl; -import org.openscore.content.ssh.utils.Constants; -import org.openscore.content.ssh.utils.StringUtils; - -import java.nio.file.Path; -import java.util.HashMap; -import java.util.Map; - -/** - * Created by ioanvranauhp on 11/5/2014. - */ -public class ScoreSSHShellLogon extends SSHShellAbstract { - - public Map execute(SSHShellInputs sshShellInputs) { - Map returnResult = new HashMap<>(); - boolean providerAdded = addSecurityProvider(); - - try { - // default values - int portNumber = StringUtils.toInt(sshShellInputs.getPort(), Constants.DEFAULT_PORT); - String knownHostsPolicy = StringUtils.toNotEmptyString(sshShellInputs.getKnownHostsPolicy(), Constants.DEFAULT_KNOWN_HOSTS_POLICY); - Path knownHostsPath = StringUtils.toPath(sshShellInputs.getKnownHostsPath(), Constants.DEFAULT_KNOWN_HOSTS_PATH); - - // configure ssh parameters - ConnectionDetails connection = new ConnectionDetails(sshShellInputs.getHost(), portNumber, sshShellInputs.getUsername(), sshShellInputs.getPassword()); - KeyFile keyFile = getKeyFile(sshShellInputs.getPrivateKeyFile(), sshShellInputs.getPassword()); - KnownHostsFile knownHostsFile = new KnownHostsFile(knownHostsPath, knownHostsPolicy); - - // get the cached SSH session - String sessionId = "sshSession:" + sshShellInputs.getHost() + "-" + portNumber + "-" + sshShellInputs.getUsername(); - synchronized (sessionId) { - SSHService service = getFromCache(sshShellInputs, sessionId); - boolean saveSSHSession = false; - if (service == null || !service.isConnected() || !service.isExpectChannelConnected()) { - saveSSHSession = true; - service = new SSHServiceImpl(connection, keyFile, knownHostsFile, Constants.DEFAULT_CONNECT_TIMEOUT, true); - } - // save SSH session in the cache - if (saveSSHSession) { - boolean saved = saveToCache(sshShellInputs.getSshGlobalSessionObject(), service, sessionId); - if (!saved) { - throw new RuntimeException("The SSH session could not be saved in the given sessionParam."); - } - } - } - - // populate the results - populateResult(returnResult, sessionId); - } catch (Exception e) { - populateResult(returnResult, e); - } finally { - if (providerAdded) { - removeSecurityProvider(); - } - } - return returnResult; - } - - private void populateResult(Map returnResult, String sessionId) { - returnResult.put(Constants.SESSION_ID, sessionId); - returnResult.put(Constants.OutputNames.RETURN_RESULT, sessionId); - returnResult.put(Constants.OutputNames.RETURN_CODE, Constants.ReturnCodes.RETURN_CODE_SUCCESS); - } -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/services/impl/SSHServiceImpl.java b/score-ssh/src/main/java/org/openscore/content/ssh/services/impl/SSHServiceImpl.java index 9ba5a4caa..c2a09c636 100644 --- a/score-ssh/src/main/java/org/openscore/content/ssh/services/impl/SSHServiceImpl.java +++ b/score-ssh/src/main/java/org/openscore/content/ssh/services/impl/SSHServiceImpl.java @@ -1,28 +1,12 @@ package org.openscore.content.ssh.services.impl; import com.hp.oo.sdk.content.plugin.GlobalSessionObject; -import com.jcraft.jsch.Channel; -import com.jcraft.jsch.ChannelShell; -import com.jcraft.jsch.JSch; -import com.jcraft.jsch.JSchException; -import com.jcraft.jsch.Session; -import org.openscore.content.ssh.entities.CommandResult; -import org.openscore.content.ssh.entities.ConnectionDetails; -import org.openscore.content.ssh.entities.ExpectCommandResult; -import org.openscore.content.ssh.entities.KeyFile; -import org.openscore.content.ssh.entities.KnownHostsFile; -import org.openscore.content.ssh.entities.SSHConnection; +import com.jcraft.jsch.*; +import org.openscore.content.ssh.entities.*; import org.openscore.content.ssh.services.SSHService; import org.openscore.content.ssh.utils.CacheUtils; -import org.openscore.content.ssh.utils.Constants; -import org.openscore.content.ssh.utils.simulator.ShellSimulator; -import org.openscore.content.ssh.utils.simulator.visualization.IShellVisualizer; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; + +import java.io.*; import java.util.Locale; import java.util.Map; @@ -157,51 +141,6 @@ public CommandResult runShellCommand(String command, String characterSet, boolea } } - @Override - public ExpectCommandResult runExpectCommand(String commandList, String characterSet, String newline, int writeCharacterTimeout, int connectTimeout, int commandTimeout) { - try { - if (shellChannel == null || !shellChannel.isConnected()) { - // create shell channel - shellChannel = session.openChannel(SHELL_CHANNEL); - - // connect to the channel and run the command(s) - shellChannel.connect(connectTimeout); - } - - ShellSimulator simulator = new ShellSimulator( - commandList, - Constants.DEFAULT_MATCH_TIMEOUT, - Constants.DEFAULT_READ_TIMEOUT, - Constants.DEFAULT_IDLE_TIMEOUT, - writeCharacterTimeout, - newline.toCharArray(), - characterSet, - false); - simulator.setStreams(shellChannel.getInputStream(), shellChannel.getOutputStream()); - IShellVisualizer visualizer = simulator.addVisualizer(BASIC_VISUALIZER); - - simulator.run(commandTimeout); - - String exception = simulator.getException(); - if (exception != null && exception.length() > 0) { - throw new RuntimeException(exception); - } - - // save the response - ExpectCommandResult result = new ExpectCommandResult(); - result.setStandardOutput(simulator.getOutput()); - if (visualizer != null) { - result.setExpectXmlOutputs(visualizer.getXMLSummary()); - } - - // The exit status is only available after the channel was closed (more exactly, just before the channel is closed). - result.setExitCode(shellChannel.getExitStatus()); - return result; - } catch (AssertionError | Exception e) { - throw new RuntimeException(e); - } - } - @Override public void createLocalTunnel(int localPort, String remoteHost, int remotePort) { try { @@ -216,11 +155,6 @@ public boolean isConnected() { return session.isConnected(); } - @Override - public boolean isExpectChannelConnected() { - return shellChannel != null && shellChannel.isConnected(); - } - @Override public void close() { if (shellChannel != null) { diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/CacheUtils.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/CacheUtils.java index 2b3f96487..0a41f28a8 100644 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/CacheUtils.java +++ b/score-ssh/src/main/java/org/openscore/content/ssh/utils/CacheUtils.java @@ -2,11 +2,11 @@ import com.hp.oo.sdk.content.plugin.GlobalSessionObject; import com.hp.oo.sdk.content.plugin.SessionResource; +import com.jcraft.jsch.Channel; +import com.jcraft.jsch.Session; import org.openscore.content.ssh.entities.SSHConnection; import org.openscore.content.ssh.services.SSHService; import org.openscore.content.ssh.services.impl.SSHServiceImpl; -import com.jcraft.jsch.Channel; -import com.jcraft.jsch.Session; import java.util.HashMap; import java.util.Map; @@ -61,7 +61,7 @@ private static Channel getSshChannel(SessionResource> */ public static boolean saveSshSessionAndChannel(Session session, Channel channel, GlobalSessionObject> sessionParam, String sessionId) { final SSHConnection sshConnection; - if( channel != null ) { + if (channel != null) { sshConnection = new SSHConnection(session, channel); } else { sshConnection = new SSHConnection(session); @@ -86,7 +86,7 @@ public static boolean saveSshSessionAndChannel(Session session, Channel channel, * @param sessionId The key to the session in the cache map. */ public static void removeSshSession(GlobalSessionObject> sessionParam, String sessionId) { - if(sessionParam != null) { + if (sessionParam != null) { SessionResource> resource = sessionParam.getResource(); if (resource != null) { Map tempMap = resource.get(); diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/SSHSessionResource.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/SSHSessionResource.java index 836cbb8f4..9d589e073 100644 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/SSHSessionResource.java +++ b/score-ssh/src/main/java/org/openscore/content/ssh/utils/SSHSessionResource.java @@ -1,9 +1,9 @@ package org.openscore.content.ssh.utils; import com.hp.oo.sdk.content.plugin.SessionResource; -import org.openscore.content.ssh.entities.SSHConnection; import com.jcraft.jsch.Channel; import com.jcraft.jsch.Session; +import org.openscore.content.ssh.entities.SSHConnection; import java.util.Collection; import java.util.Map; diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/IScriptRunner.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/IScriptRunner.java deleted file mode 100644 index 0697ba26f..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/IScriptRunner.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.openscore.content.ssh.utils.simulator; - -public interface IScriptRunner extends Runnable { - public String getOutput(); - - public int getCommandsLeft(); - - public boolean noMoreCommandsLeft(); - - public String getException(); - - public void setCaptureOutput(boolean enableCapture); -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/SafeMatcher.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/SafeMatcher.java deleted file mode 100644 index 530e3e3c1..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/SafeMatcher.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.openscore.content.ssh.utils.simulator; - -public class SafeMatcher extends Thread { - String toTest; - String regex; - boolean match; - - private SafeMatcher(String toTest, String regex) { - this.toTest = toTest; - this.regex = regex; - match = false; - } - - public void run() { - match = toTest.matches(regex); - } - - @SuppressWarnings("deprecation") - public static boolean match(String toTest, String regex, long timeOut) throws Exception { - SafeMatcher t = new SafeMatcher(toTest, regex); - long startTime = System.currentTimeMillis(); - t.start(); - while (t.isAlive() && (System.currentTimeMillis() - startTime) < timeOut) { - Thread.sleep(50); - } - if (t.isAlive()) { - t.stop(); - throw new Exception("match timed out after: " + (System.currentTimeMillis() - startTime) + "ms"); - } - return t.match; - } -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ScriptLines.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ScriptLines.java deleted file mode 100644 index 6e29076d4..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ScriptLines.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.openscore.content.ssh.utils.simulator; - -import java.util.ArrayList; - -public class ScriptLines { - String[] lines; - int index; - - public ScriptLines(String script) { - String[] currLines = script.trim().split("\n"); - ArrayList lines = new ArrayList<>(); - for (String currLine : currLines) - if (currLine.trim().length() > 0) - lines.add(currLine.trim()); - this.lines = lines.toArray(new String[lines.size()]); - index = 0; - } - - public String getCurrentLine() { - return lines[index]; - } - - public boolean nextLine() { - if (hasNext()) { - index++; - return true; - } else - return false; - } - - public boolean hasNext() { - return index + 1 < lines.length; - } - - public String peekNext() { - if (hasNext()) - return lines[index + 1]; - else - return null; - } - - public String toString() { - StringBuilder ret = new StringBuilder("Script:currently on line: " + (index + 1) + "\n"); - for (int count = 0; count < lines.length; count++) { - ret.append("").append(count + 1).append(" ").append(lines[count]); - } - return ret.toString(); - } -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ScriptModel.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ScriptModel.java deleted file mode 100644 index a8db99338..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ScriptModel.java +++ /dev/null @@ -1,110 +0,0 @@ -package org.openscore.content.ssh.utils.simulator; - -import org.openscore.content.ssh.utils.simulator.elements.AlwaysOn; -import org.openscore.content.ssh.utils.simulator.elements.Expect; -import org.openscore.content.ssh.utils.simulator.elements.ScriptElement; -import org.openscore.content.ssh.utils.simulator.elements.Send; - -import java.util.ArrayList; - -public class ScriptModel { - - private ArrayList commands; - private ArrayList continuousCommands; - - public ScriptModel(String script, char[] newLineCharacter) throws Exception { - commands = new ArrayList<>(); - continuousCommands = new ArrayList<>(); - if (script.length() > 0) - parseScript(new ScriptLines(script), newLineCharacter); - } - - public AlwaysOn checkAlwaysHandlers(String current, long matchTimeout) throws Exception { - for (AlwaysOn curr : continuousCommands) { - if (curr.match(current.trim(), matchTimeout)) { - return curr; - } - } - return null; - } - - public Expect IsExceptAllowed(String current, ScriptRunner scriptRunner, long matchTimeout) throws Exception { - if (commands.size() > 0 && commands.get(0) instanceof Expect) { - Expect expect = (Expect) commands.get(0); - if (expect.waitIfNeeded()) - scriptRunner.setReadTime(); - if (expect.match(current.trim(), matchTimeout)) { - commands.remove(0); - return expect; - } - } - return null; - } - - public Send IsSendAllowed() throws Exception { - if (commands.size() > 0 && commands.get(0) instanceof Send) { - return (Send) commands.remove(0); - } else - return null; - } - - public int getCommandsLeft() { - return commands.size(); - } - - private void parseScript(ScriptLines script, char[] newLineCharacter) throws Exception { - for (boolean running = true; running; running = script.nextLine()) { - String line = script.getCurrentLine(); - if (line.toLowerCase().startsWith("send")) { - commands.add(Send.getInstance(line, newLineCharacter)); - } else if (line.toLowerCase().startsWith("expect")) { - Expect curr = Expect.getInstance(line); - commands.add(curr); - String next = script.peekNext(); - if (next != null && next.toLowerCase().startsWith("erroron")) { - running = script.nextLine(); - curr.setError(Expect.getInstance(next.substring(next.indexOf(' ')))); - } - } else if (line.toLowerCase().startsWith("always")) - continuousCommands.add(AlwaysOn.getInstance(script, newLineCharacter)); - else if (line.toLowerCase().startsWith("wait")) { - parseWaitScript(script, newLineCharacter); - } else - throw new Exception("unsupported operation: " + script); - } - } - - private void parseWaitScript(ScriptLines script, char[] newLineCharacter) throws Exception { - String line = script.getCurrentLine(); - String on = ""; - if (line.toLowerCase().startsWith("wait")) { - String[] segments = line.split(" "); - long time; - try { - time = Long.parseLong(segments[1]); - } catch (NumberFormatException e) { - throw new NumberFormatException("Unable to process wait command. An exception occurred while parsing wait length." + e.getMessage()); - } - for (int count = 2; count < segments.length; count++) - if (count == 2) - on = segments[count]; - else - on += " " + segments[count]; - if (on.trim().length() == 0) { - if (!script.nextLine()) - throw new Exception("Wait found at end of script. Wait must be followed by a send or expect"); - else - on = script.getCurrentLine(); - } - if (on.startsWith("send")) { - Send op = Send.getInstance(on, newLineCharacter); - commands.add(op); - op.setWaitTime(time); - } else if (on.startsWith("expect")) { - Expect op = Expect.getInstance(on); - commands.add(op); - op.setWaitTime(time); - } else throw new Exception("unsupported operation: " + script); - } else throw new Exception("unsupported wait operation: " + script); - } -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ScriptRunner.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ScriptRunner.java deleted file mode 100644 index 4afbdac77..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ScriptRunner.java +++ /dev/null @@ -1,370 +0,0 @@ -package org.openscore.content.ssh.utils.simulator; - -import org.openscore.content.ssh.utils.simulator.elements.AlwaysOn; -import org.openscore.content.ssh.utils.simulator.elements.Expect; -import org.openscore.content.ssh.utils.simulator.elements.Send; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PipedOutputStream; -import java.util.ArrayList; -import java.util.List; - -class ScriptRunner extends Thread implements IScriptRunner { - - private static final String DEFAULT_CHARACTER_SET = "UTF-8"; - public InputStream in; - public OutputStream out; - ScriptModel parser; - boolean captureOutput; - private List stdout; - private List pipes; - private String current; - private char[] toSend; - private String exception; - private int postCompleteReads; - private long readTimeout; - private long lastReadTime; - private long matchTimeout; - private long sleepTime; - private long characterDelay; - private boolean closeStreams; - private String characterSet = DEFAULT_CHARACTER_SET; - - /** - * ScriptRunner Constructor - * - * @param script - * @param matchTimeout - * @param readTimeout - * @param sleepTimeout - * @param characterDelay - * @param newLineCharacter - * @throws Exception - */ - public ScriptRunner(String script, long matchTimeout, long readTimeout, long sleepTimeout, long characterDelay, char[] newLineCharacter) throws Exception { - parser = new ScriptModel(script, newLineCharacter); - stdout = new ArrayList<>(); - pipes = new ArrayList<>(); - current = ""; - toSend = new char[0]; - postCompleteReads = 0; - this.readTimeout = readTimeout; - this.matchTimeout = matchTimeout; - sleepTime = sleepTimeout; - this.characterDelay = characterDelay; - exception = ""; - captureOutput = true; - closeStreams = true; - this.characterSet = DEFAULT_CHARACTER_SET; - } - - /** - * constructor to allow user's characterSet - * - * @param script the command - * @param matchTimeout - * @param readTimeout - * @param sleepTimeout - * @param characterDelay delay in milseconds for user input - * @param newLineCharacter - * @param charSet input character set name, for example UTF-8, SJIS - * @throws Exception - */ - public ScriptRunner(String script, - long matchTimeout, - long readTimeout, - long sleepTimeout, - long characterDelay, - char[] newLineCharacter, - String charSet) throws Exception { - this(script, - matchTimeout, - readTimeout, - sleepTimeout, - characterDelay, - newLineCharacter); - this.characterSet = charSet; - } - - /** - * @param script - * @param matchTimeout - * @param readTimeout - * @param sleepTimeout - * @param characterDelay - * @param newLineCharacter - * @param charset input character set name, for example UTF-8, SJIS - * @param closeStreams If using a cached shell channel, closing the streams would cause the channel to close. - * @throws Exception - */ - public ScriptRunner(String script, long matchTimeout, long readTimeout, long sleepTimeout, long characterDelay, char[] newLineCharacter, String charset, boolean closeStreams) throws Exception { - this(script, matchTimeout, readTimeout, sleepTimeout, characterDelay, newLineCharacter, charset); - this.closeStreams = closeStreams; - } - - public void addPipe(java.io.PipedInputStream in) throws IOException { - if( in != null ) { - pipes.add(new PipedOutputStream(in)); - } - } - - private void pipe(byte[] read, int offset, int length) throws IOException { - for (PipedOutputStream pipe : pipes) { - pipe.write(read, offset, length); - } - } - - public String getOutput() { - StringBuilder output = new StringBuilder(); - while (stdout.size() > 0) { - output.append(stdout.remove(0)); - } - return output.toString(); - } - - public void setCaptureOutput(boolean enableCapture) { - this.captureOutput = enableCapture; - } - - /** - * Returns the number of commands left in the ScriptModel (which parses the script) - */ - public int getCommandsLeft() { - return parser.getCommandsLeft(); - } - - /** - * @return true if no more commands are left for the ScriptModel to process - */ - public boolean noMoreCommandsLeft() { - return getCommandsLeft() <= 0; - } - - /** - * @return a string of all the exceptions that occurred while running the script - */ - public String getException() { - return exception.trim(); - } - - /** - * @param exception - */ - private synchronized void addException(Exception exception) { - //exception.printStackTrace(); - this.exception += "\n" + exception + "\n Instructions left: " + getCommandsLeft() + "\n"; - } - - private synchronized void clearMatchExceptions() { - String[] split = exception.split("\n"); - exception = ""; - for (String aSplit : split) { - if (!aSplit.contains("match") && aSplit.length() > 0) - exception += aSplit; - } - this.exception = ""; - } - - public void terminate() { - addException(new Exception("timedOut")); - for (int count = 0; count < 10; count++) { - incrementPostCompleteReads(); - } - } - - private synchronized void incrementPostCompleteReads() { - postCompleteReads++; - } - - private synchronized void resetPostCompleteReads() { - postCompleteReads = 0; - } - - public synchronized long getDeltaT() { - return System.currentTimeMillis() - lastReadTime; - } - - public void run() { - long deltaT = 0; - setReadTime(); - try { - while (postCompleteReads < 5 && (deltaT = getDeltaT()) <= readTimeout) { - boolean updated; - updated = process(); - - if (noMoreCommandsLeft()) { - clearMatchExceptions(); - incrementPostCompleteReads(); - if (updated) - resetPostCompleteReads(); - try { - Thread.sleep(100); - } catch (InterruptedException e) { - //don't care if we are interrupted. - } - } - - } - //if this is used for SSH shell ops, closing the output stream will close the SHELL channel - //This isn't desired if multiple SSH Shell Operations are sharing the same SHELL channel. - if (closeStreams) { - if(in != null) { - in.close(); - } - if(out != null) { - out.close(); - } - } - } catch (Exception e) { - addException(e); - } - if (!noMoreCommandsLeft() && deltaT >= readTimeout) - addException(new Exception("readTimeout at: " + deltaT + "ms")); - if (captureOutput) - this.stdout.add(current); - current = ""; - } - - public boolean checkAlwaysHandlers() { - try { - AlwaysOn curr = parser.checkAlwaysHandlers(current, matchTimeout); - if (curr != null) { - if (captureOutput) - this.stdout.add(current); - current = ""; - toSend = curr.get(); - clearMatchExceptions(); - return true; - } else - return false; - } catch (Exception ex) { - addException(ex); - return false; - } - } - - boolean sendable() throws Exception { - if (toSend != null && toSend.length > 0) //there are commands to send. - return true; - if (noMoreCommandsLeft()) - return false; - try { - Expect e = parser.IsExceptAllowed(current, this, matchTimeout); - if (e != null) { - if (e.match(current.trim(), matchTimeout)) { - if (captureOutput) - this.stdout.add(current); - current = ""; - clearMatchExceptions(); - return sendable(); - } - } - } catch (Exception ex) { - if (checkAlwaysHandlers()) - return true; - else - addException(ex); - } - Send s = parser.IsSendAllowed(); - if (s != null) { - if (s.waitIfNeeded()) - setReadTime(); - toSend = s.get(); - return true; - } - return checkAlwaysHandlers(); - } - - /** - * updates the last time the ScriptRunner has performed a read to current time. - */ - public synchronized void setReadTime() { - lastReadTime = System.currentTimeMillis(); - } - - /** - * @param in - * @return - */ - public String removeAsciiEscapes(String in) { - String out = in.replaceAll("" + (char) 27 + "\\[.*?m", "");//color codes - //out = out.replaceAll(""+(char)27+"\\[\\d+;\\d+?H", "");//from windows terminal - return out; - } - - /** - * @return - * @throws Exception - */ - public boolean process() throws Exception { - boolean wasRead = false; - if(in == null) { - return false; - } - while (in.available() > 0) { - wasRead = true; - byte[] buff = new byte[in.available()]; //this is max size of buffer to avoid boundery condition - int read; - try { - read = in.read(buff); - } catch (java.net.SocketException e) {//telnet stream throws one on first read after stream is closed remotely. - if (noMoreCommandsLeft()) - read = in.read(buff); - else - throw e; - } - if (read > 0) { - //TODO: this should use a CharsetDecoder and a ByteBuffer instead. - // A common helper method that does this is not tested and ready yet. - String cleanString = removeAsciiEscapes(new String(buff, 0, read, this.characterSet)); - current += cleanString; - - if (captureOutput && cleanString != null) { - byte[] outPipeToVisualizer = cleanString.getBytes("UTF-8"); - if (outPipeToVisualizer != null && outPipeToVisualizer.length != 0) { - pipe(outPipeToVisualizer, 0, outPipeToVisualizer.length); - //pipe(buff, 0, read); - } - } - } - - } - boolean sent = false; - while (sendable()) { - sent = true; - byte[] bytes = new String(toSend).getBytes(this.characterSet); - if (characterDelay > 0) { - //delay each character write by sleepTime - for (int i = 0; i < toSend.length; i++) { - out.write(bytes, i, 1); - out.flush(); - try { - Thread.sleep(characterDelay); - } catch (InterruptedException e) { - //don't care if we are interrupted. - } - } - } else { - //no delay - out.write(bytes); - out.flush(); - } - - toSend = new char[0]; - } - - if (wasRead || sent) { - setReadTime(); - return true; - } else { - try { - Thread.sleep(sleepTime); - } catch (InterruptedException e) { - //don't care if we are interrupted. - } - return false; - } - } -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ShellSimulator.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ShellSimulator.java deleted file mode 100644 index 892e30154..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/ShellSimulator.java +++ /dev/null @@ -1,219 +0,0 @@ -package org.openscore.content.ssh.utils.simulator; - -import org.openscore.content.ssh.utils.simulator.visualization.IShellVisualizer; -import org.openscore.content.ssh.utils.simulator.visualization.ScreenEmulator; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PipedInputStream; -import java.util.HashMap; -import java.util.Iterator; - -public class ShellSimulator { - ScriptRunner simulator; - String exception; - HashMap visualizers; - - /** - * @param script - * @param matchTimeout - * @param readTimeout - * @param sleepTimeout - * @param characterDelay - * @param newLineCharacter - * @throws Exception - */ - public ShellSimulator(String script, - long matchTimeout, - long readTimeout, - long sleepTimeout, - long characterDelay, - char[] newLineCharacter) - throws Exception { - simulator = new ScriptRunner(script, - matchTimeout, - readTimeout, - sleepTimeout, - characterDelay, - newLineCharacter); - exception = ""; - visualizers = new HashMap<>(); - } - - - /** - * constructor - * - * @param script command - * @param matchTimeout - * @param readTimeout - * @param sleepTimeout - * @param characterDelay delay in milseconds for user input - * @param newLineCharacter - * @param charSet a characterSet name , for example UTF-8, SJIS - * @throws Exception - */ - public ShellSimulator(String script, - long matchTimeout, - long readTimeout, - long sleepTimeout, - long characterDelay, - char[] newLineCharacter, - String charSet) - throws Exception { - simulator = new ScriptRunner(script, - matchTimeout, - readTimeout, - sleepTimeout, - characterDelay, - newLineCharacter, - charSet); - exception = ""; - visualizers = new HashMap(); - } - - /** - * @param script - * @param matchTimeout - * @param readTimeout - * @param sleepTimeout - * @param characterDelay - * @throws Exception - */ - public ShellSimulator(String script, long matchTimeout, long readTimeout, long sleepTimeout, long characterDelay) throws Exception { - this(script, matchTimeout, readTimeout, sleepTimeout, characterDelay, new char[]{'\n'}); - } - - /** - * @param script - * @param matchTimeout - * @param readTimeout - * @param sleepTimeout - * @param characterDelay - * @param newLineCharacter - * @param charset input character set name, for example UTF-8, SJIS - * @param closeStreams Set to false if using a cached SSH shell channel - * @throws Exception - */ - public ShellSimulator(String script, long matchTimeout, long readTimeout, long sleepTimeout, long characterDelay, char[] newLineCharacter, String charset, boolean closeStreams) throws Exception { - simulator = new ScriptRunner(script, - matchTimeout, - readTimeout, - sleepTimeout, - characterDelay, - newLineCharacter, - charset, - closeStreams); - exception = ""; - visualizers = new HashMap(); - } - - /** - * @param script - * @param matchTimeout - * @param readTimeout - * @param sleepTimeout - * @param characterDelay - * @param charset input character set name, for example UTF-8, SJIS - * @param closeStreams Set to false if using a cached SSH shell channel - * @throws Exception - */ - public ShellSimulator(String script, long matchTimeout, long readTimeout, long sleepTimeout, long characterDelay, String charset, boolean closeStreams) throws Exception { - this(script, matchTimeout, readTimeout, sleepTimeout, characterDelay, new char[]{'\n'}, charset, closeStreams); - } - - public IShellVisualizer addVisualizer(String name) throws Exception { - IShellVisualizer vis; - if (name == null || name.length() == 0 || name.toLowerCase().equals("basic")) - vis = new ScreenEmulator(); - else if (name.toLowerCase().equals("none")) - return null; - else - throw new Exception("The specified visualizer is of unknown type"); - addVisualizer(vis); - return vis; - } - - private PipedInputStream registerVisualizer(final IShellVisualizer vis) throws IOException { - final PipedInputStream in = new PipedInputStream(); - simulator.addPipe(in); - return in; - } - - public void addVisualizer(final IShellVisualizer visualizer) throws IOException { - visualizers.put(visualizer, registerVisualizer(visualizer)); - } - - public void setStreams(InputStream in, OutputStream out) { - simulator.in = in; - simulator.out = out; - } - - public String getOutput() { - return simulator.getOutput(); - } - - public String getException() { - exception += simulator.getException(); - if (!simulator.noMoreCommandsLeft()) - exception = "Script did not fully finish, had: " + simulator.getCommandsLeft() + " commands left " + exception; - return exception; - } - - public boolean noMoreCommandsLeft() { - return simulator.noMoreCommandsLeft(); - } - - public void run(long timeout) { - long startTime = System.currentTimeMillis(); - simulator.start(); - // connect channel to host - Iterator visuals = visualizers.keySet().iterator(); - while (visuals.hasNext()) { - final IShellVisualizer curr = visuals.next(); - Thread t = new Thread("Visualizer Thread") { - public void run() { - try { - curr.run(visualizers.get(curr)); - } finally { - try { - visualizers.get(curr).close(); - } catch (IOException e) { - } - } - } - }; - t.start(); - } - while (simulator.isAlive()) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - } - long time = System.currentTimeMillis(); - if (time - startTime > timeout) { - exception += "timeout after: " + (time - startTime) + "ms\n"; - simulator.terminate(); - break; - } - } - while (simulator.isAlive()) - try { - Thread.sleep(50); - } catch (InterruptedException e) { - } finally { - visuals = visualizers.keySet().iterator(); - while (visuals.hasNext()) { - IShellVisualizer curr = visuals.next(); - try { - visualizers.get(curr).close(); - } catch (IOException e) { - } - } - } - } -} - - - diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/AlwaysOn.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/AlwaysOn.java deleted file mode 100644 index 8d34f9098..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/AlwaysOn.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -import org.openscore.content.ssh.utils.simulator.ScriptLines; - -public class AlwaysOn { - Expect expect; - Send send; - - public static AlwaysOn getInstance(ScriptLines script, char[] newLineCharacter) throws Exception { - AlwaysOn command = new AlwaysOn(); - if(script != null) { - String line = script.getCurrentLine(); - line = line.substring(line.indexOf(" ")); - command.setCommand(Send.getInstance(line, newLineCharacter)); - - if (!script.nextLine()) - throw new Exception("Always statement started on last line: always statements must have 'on' starting the next line"); - line = script.getCurrentLine(); - if (!line.startsWith("on")) - throw new Exception("always statements must have 'on' starting the next line"); - line = line.substring(line.indexOf(" ")); - command.setExpect(Expect.getInstance(line)); - } - return command; - } - - public void setCommand(Send command) { - this.send = command; - } - - public char[] get() { - if(send != null ) { - return send.get(); - } else { - return new char[]{}; - } - } - - public boolean match(String toMatch, long timeout) throws Exception { - return expect != null && expect.match(toMatch, timeout); - } - - public void setExpect(Expect command) { - this.expect = command; - } -} \ No newline at end of file diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/Expect.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/Expect.java deleted file mode 100644 index 51fd9c686..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/Expect.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -import org.openscore.content.ssh.utils.simulator.SafeMatcher; - -import java.util.HashMap; - -public class Expect extends ScriptElement { - public static final String FLAG_EXPECT = "expect"; - public static final String FLAG_EXPECT_ENDS_WITH = "expectendswith"; - public static final String FLAG_EXPECT_LAST_LINE = "expectlastline"; - public static HashMap> expects = new HashMap<>(); - - static { - expects.put(FLAG_EXPECT, Expect.class); - expects.put(FLAG_EXPECT_ENDS_WITH, ExpectEndsWith.class); - expects.put(FLAG_EXPECT_LAST_LINE, ExpectLastLine.class); - } - - protected String command; - // safeMatch.match(current.trim(),, matchTimeout)){ - long toWait; - Expect error; - - public static Expect getInstance(String line) throws Exception { - Expect parsed; - String flag = getKey(line); - if (expects.containsKey(flag)) { - parsed = expects.get(flag).newInstance(); - } else - throw new Exception("unsupported expect operation: " + line + " flag was: " + flag); - parsed.setCommand(line, flag); - return parsed; - } - - public void matchError(String toMatch, long timeout) throws Exception { - if (error != null) - if (error.match(toMatch, timeout)) - throw new Exception("Error condition matched: " + error.command + " to: " + toMatch); - } - - public boolean match(String toMatch, long timeout) throws Exception { - matchError(toMatch, timeout); - return SafeMatcher.match(toMatch, command, timeout); - } - - public void set(String command) { - if(command != null) { - this.command = command.trim(); - }else { - this.command = ""; - } - } - - public void setError(Expect error) { - this.error = error; - } - - public void setWaitTime(long ToWait) { - this.toWait = ToWait; - } - - public boolean waitIfNeeded() throws InterruptedException { - if (toWait != 0) { - Thread.sleep(toWait); - toWait = 0; - return true; - } - return false; - } -} \ No newline at end of file diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/ExpectEndsWith.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/ExpectEndsWith.java deleted file mode 100644 index 6d37b84c3..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/ExpectEndsWith.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -public class ExpectEndsWith extends Expect { - - public boolean match(String toMatch, long timeout) throws Exception { - if(toMatch != null) { - matchError(toMatch, timeout); - return toMatch.trim().endsWith(command); - } else { - return false; - } - } - -} \ No newline at end of file diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/ExpectLastLine.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/ExpectLastLine.java deleted file mode 100644 index 7b179db6d..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/ExpectLastLine.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -import org.openscore.content.ssh.utils.simulator.SafeMatcher; - -public class ExpectLastLine extends Expect { - - public boolean match(String toMatch, long timeout) throws Exception { - if( toMatch != null ) { - toMatch = toMatch.replace("\r", "\n"); - String[] lines = toMatch.trim().split("\n"); - toMatch = lines[lines.length - 1]; - matchError(toMatch, timeout); - return SafeMatcher.match(toMatch, command, timeout); - } else { - return false; - } - } - -} \ No newline at end of file diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/ScriptElement.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/ScriptElement.java deleted file mode 100644 index 9e643de1d..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/ScriptElement.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -public abstract class ScriptElement { - - protected static String getKey(String line) { - line = line.trim(); - if (!line.contains(" ")) - return line.toLowerCase(); - return line.substring(0, line.indexOf(' ')).toLowerCase(); - } - - public abstract void set(String s); - - protected void setCommand(String line, String flag) { - String toSet = line.trim().substring(flag.length()); - set(toSet); - } -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/Send.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/Send.java deleted file mode 100644 index f918451bc..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/Send.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -import java.util.Arrays; -import java.util.HashMap; - -public class Send extends ScriptElement { - public static final String FLAG_SEND = "send"; - public static final String FLAG_SEND_CHAR = "sendchar"; - public static HashMap> sends = new HashMap<>(); - - static { - sends.put(FLAG_SEND, Send.class); - sends.put(FLAG_SEND_CHAR, SendChar.class); - } - - protected char[] command; - long toWait; - char[] newLineCharacters; - - public static Send getInstance(String line, char[] newLineCharacters) throws Exception { - Send parsed; - String flag = getKey(line); - if (sends.containsKey(flag)) { - parsed = sends.get(flag).newInstance(); - } else - throw new Exception("unsupported send operation: " + line + " flag was: " + flag); - if (newLineCharacters == null) { - parsed.newLineCharacters = new char[0]; - } else { - parsed.newLineCharacters = Arrays.copyOf(newLineCharacters, newLineCharacters.length); - } - parsed.setCommand(line, flag); - return parsed; - } - - public void set(String command) { - if (newLineCharacters == null) - newLineCharacters = new char[]{'\n'}; - this.command = (command.trim() + new String(newLineCharacters)).toCharArray(); - } - - public char[] get() { - return command; - } - - public void setWaitTime(long ToWait) { - this.toWait = ToWait; - } - - public boolean waitIfNeeded() throws InterruptedException { - if (toWait != 0) { - Thread.sleep(toWait); - toWait = 0; - return true; - } - return false; - } -} \ No newline at end of file diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/SendChar.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/SendChar.java deleted file mode 100644 index 1b38f6cb2..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/SendChar.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -public class SendChar extends Send { - - /** - * This method sets a command in a char format. If a bad char is provided - * then an empty char will be set. - * @param command - */ - public void set(String command) { - int i = 0; - if( command!= null ) { - try { - i = Integer.parseInt(command.trim()); - } catch (NumberFormatException ex) { - i = 0; - } - } - this.command = new char[]{(char) i}; - } -} \ No newline at end of file diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/SetSimulatorCapture.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/SetSimulatorCapture.java deleted file mode 100644 index 381caaa3b..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/SetSimulatorCapture.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -public class SetSimulatorCapture extends SimulatorModificationCommand { - - boolean enable; - - @Override - public void execute() { - } - - @Override - public void set(String s) { - enable = Boolean.parseBoolean(s); - } - -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/SimulatorModificationCommand.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/SimulatorModificationCommand.java deleted file mode 100644 index 4fc71289f..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/elements/SimulatorModificationCommand.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -import org.openscore.content.ssh.utils.simulator.IScriptRunner; - -import java.util.HashMap; - -public abstract class SimulatorModificationCommand extends ScriptElement { - - public static final String FLAG_CAPTURE = "captureOutput"; - public static HashMap> sends = new HashMap>(); - - static { - sends.put(FLAG_CAPTURE.toLowerCase(), SetSimulatorCapture.class); - } - - protected IScriptRunner runner; - - public static SimulatorModificationCommand getInstance(String line, IScriptRunner simulator) throws Exception { - SimulatorModificationCommand command; - - String flag = getKey(line); - if (sends.containsKey(flag)) { - command = sends.get(flag).newInstance(); - } else - throw new Exception("unsupported send operation: " + line + " flag was: " + flag); - - command.runner = simulator; - command.setCommand(line, flag); - - return command; - } - - public abstract void execute(); -} \ No newline at end of file diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/ByteWrapper.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/ByteWrapper.java deleted file mode 100644 index a4eaa9294..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/ByteWrapper.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.visualization; - -public class ByteWrapper { - private byte value; - private boolean isChanged; - private ScreenEmulator screenEmulator; - - ByteWrapper(ScreenEmulator aEmu) { - char empty = ' '; - screenEmulator = aEmu; - value = (byte) (empty & 0xFF); - } - - public byte getValue() { - return value; - } - - public void setValue(byte aByteVal) { - if (isChanged) { - screenEmulator.snapshotBuffer(true); - } - value = aByteVal; - isChanged = true; - } - - void clearChanged() { - isChanged = false; - } - - /** - * reset the value to empty, indicate if it is changed or not - */ - public void clear() { - char empty = ' '; - if (value != (byte) (empty & 0xFF)) { - if (isChanged) - setValue((byte) (empty & 0xFF)); - else - value = (byte) (empty & 0xFF); - } else { - isChanged = false; - } - } -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/IShellVisualizer.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/IShellVisualizer.java deleted file mode 100644 index b9ca8d90e..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/IShellVisualizer.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.visualization; - -import java.io.InputStream; - -public interface IShellVisualizer { - - public void run(InputStream in); - - public String getXMLSummary(); -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/LinearUpdateTask.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/LinearUpdateTask.java deleted file mode 100644 index f6b950998..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/LinearUpdateTask.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.visualization; - -public abstract class LinearUpdateTask extends ScreenTask { - int maxOffset; - int offsetIndex; - boolean completed; - boolean nextLine; - int newlines; - - public LinearUpdateTask(int length) { - this.maxOffset = length; - completed = false; - nextLine = false; - newlines = 0; - offsetIndex = 0; - } - - public abstract byte process(int offset); - - public final void process(int x, int y, ByteWrapper val) { - nextLine = false; - byte read = process(offsetIndex); - - if (read == (byte) ('\r' & 0xFF) || (read == (byte) ('\n' & 0xFF) - && process(offsetIndex - 1) != (byte) ('\r' & 0xFF))) { - nextLine = true; - } else { - val.setValue(read); - } - offsetIndex++; - if (offsetIndex >= maxOffset) - completed = true; - } - - public boolean completed() { - return completed; - } - - public boolean nextLine() { - return nextLine || completed; - } - -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/ScreenEmulator.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/ScreenEmulator.java deleted file mode 100644 index 1cf66223c..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/ScreenEmulator.java +++ /dev/null @@ -1,351 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.visualization; - -import com.jcraft.jcterm.Connection; -import com.jcraft.jcterm.Emulator; -import com.jcraft.jcterm.EmulatorVT100; -import com.jcraft.jcterm.Term; -import org.dom4j.DocumentFactory; -import org.dom4j.Element; - -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; - - -public class ScreenEmulator implements Term, IShellVisualizer { - public static final String STR_FRAME = "Frame"; - ByteWrapper[][] buffer; - final ArrayList frames; - - public ScreenEmulator() { - initBuffer(); - frames = new ArrayList<>(); - } - - public void run(final InputStream in) { - start(new Connection() { - - public InputStream getInputStream() { - return in; - } - - public java.io.OutputStream getOutputStream() { - return null; - } - - public void requestResize(Term term) { - - } - - public void close() { - - } - }); - } - - public String getXMLSummary() { - this.snapshotBuffer(true); - Element d = DocumentFactory.getInstance().createElement("Frames"); - d.setText("\n"); - - synchronized (frames) { - for (Element curr : frames) { - d.add(curr); - d.addText("\n"); - } - } - return d.asXML(); - } - - private void initBuffer() { - buffer = new ByteWrapper[24][80]; - for (int row = 0; row < buffer.length; row++) - for (int col = 0; col < buffer[0].length; col++) { - buffer[row][col] = new ByteWrapper(this); - } - } - - /** - * It will transfer the buffer which gets the PipedInputStream from Emulator - * into a string separated by "\n". buffer is a 2 dementional array. each row - * represents one part of the string. For example, the string is like - * "string for row[0]\n string from row[1]\n string from row[2]...." - * Emulator updates the buffer[24][80] into a VT100 screen displayable format - * each cell in buffer is a object ByteWrapper - * - * @param clearChanges indicate whether need to clear changes - * @return a converted string which represents the stream ni a VT100 screen - * displayable format. - */ - public String bufferAsString(boolean clearChanges) { - String s = null; - byte[][] byteArray = toByteArray(clearChanges); - for (byte[] curr : byteArray) { - try { - if (s == null) { - s = new String(curr, "UTF-8").trim(); - } else { - s += "\n" + new String(curr, "UTF-8").trim(); - } - } catch (UnsupportedEncodingException e) { - //do nothing - } - } - return s; - } - - String snapshotBuffer(boolean autoStore) { - String s = bufferAsString(autoStore); - if (s.trim().length() == 0) - return s; - if (frames.size() > 0 && frames.get(frames.size() - 1).getName().equals(STR_FRAME)) { - String old = frames.get(frames.size() - 1).getTextTrim(); - if (s.trim().equals(old) || old.trim().endsWith(s.trim()) || old.trim().startsWith(s.trim())) - return s; - } - if (autoStore) { - Element curr = DocumentFactory.getInstance().createElement(STR_FRAME); - curr.addAttribute("index", "" + (frames.size() + 1)); - curr.setText(s.trim()); - frames.add(curr); - } - return s; - } - - /** - * @return a 2 Dementional byte[24][80 array which is in screen presentable format - * based on buffer, buffer is a 2 demontional ByteWrapper array. - */ - private byte[][] toByteArray(final boolean resetChanges) { - final byte[][] converted = new byte[buffer.length][buffer[0].length]; - runTask(new ScreenTask() { - public void process(int row, int col, ByteWrapper val) { - converted[row][col] = val.getValue(); - if (resetChanges) - val.clearChanged(); - } - }, 0, 0, buffer.length, buffer[0].length); - return converted; - } - - private synchronized void runTask(ScreenTask task, int minrow, int mincol, int maxrow, int maxcol) { - runTask(task, minrow, mincol, maxrow, maxcol, false, false); - } - - private synchronized void runTask(ScreenTask task, int minrow, int mincol, int maxrow, int maxcol, boolean reverseRowOrder, boolean reverseColOrder) { - try { - int col = (reverseColOrder) ? maxcol - 1 : mincol; - int row = (reverseRowOrder) ? maxrow - 1 : minrow; - while (row < maxrow && row >= minrow) { - while (col < maxcol && col >= mincol) { - - task.process(row, col, buffer[row][col]); - if (task.nextLine()) { - break; - } - col = (reverseColOrder) ? col - 1 : col + 1; - } - col = 0; - if (task.completed()) { - break; - } - row = (reverseRowOrder) ? row - 1 : row + 1; - } - } catch (Throwable t) { - t.printStackTrace(); - } - } - - private void runTask(ScreenTask task, int minrow, int mincol) { - runTask(task, minrow, mincol, buffer.length, buffer[0].length); - } - - private byte get(int row, int col) { - return buffer[row][col].getValue(); - } - - //All the following methods are implementation for interface Term - public void beep() { - snapshotBuffer(true); - Element curr = DocumentFactory.getInstance().createElement("Beep"); - curr.addAttribute("lastFrameIndex", "" + frames.size()); - frames.add(curr); - } - - public void clear() { - this.snapshotBuffer(true); - initBuffer(); - } - - public void clear_area(int col, int row, int maxCol, int maxRow) { - runTask(new ScreenTask() { - public void process(int row, int col, ByteWrapper val) { - val.clear(); - } - }, row, col, maxRow - 1, maxCol); - } - - /** - * drawBytes will be called when Emulator determines the bytes from offset - * till offset + length are ascii. - * - * @param arg0, byte[1024] array from Emulator, - * @param offset will tell where is the starting byte in the arg0 - * @param length length indicates how long the string will be. - * @param mincol is equivalent to x in Emulator , meaning starting col - * @param minrow is equivalent to y in Emulator, meaning starting row - */ - public void drawBytes(final byte[] arg0, final int offset, int length, int mincol, int minrow) { - //minrow equivalent to y in Emulator.java, however the y starts with 1 - //so minus 1 to make row starting from 0 for buffer - minrow--; - int maxRow = (mincol + length) / buffer[0].length + minrow + 1; - int maxCol = mincol + length; - - runTask - ( - new LinearUpdateTask(length) { - public byte process(int col) { - return (byte) (arg0[col + offset]); - } - }, minrow, mincol, maxRow, maxCol - ); - } - - /** - * drawString will be called when Emulator determines the bytes are minus bytes - * non-ascii. It is called for each multi-bytes char. - * - * @param arg0, a UTF-8 encoded string from Emulator. Usually the string is - * multiple bytes. For example 3 bytes JP char. - * @param col is equivalent to x in Emulator , meaning starting col - * @param row is equivalent to y in Emulator, meaning starting row - */ - public void drawString(final String arg0, int col, int row) { - //row equivalent to y in Emulator.java, however the y starts with 1 - //so minus 1 to make row starting from 0 for buffer - row--; - byte[] argBytes = null; - try { - argBytes = arg0.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - //do nothing; - } - final byte[] argBytesFinal = argBytes; - - runTask - (new LinearUpdateTask(argBytesFinal.length) { - public byte process(int offset) { - return argBytesFinal[offset]; - } - }, row, col); - } - - public void draw_cursor() { - //NOT IMPLEMENTED - } - - public int getCharHeight() { - return 1; - } - - public int getCharWidth() { - return 1; - } - - public Object getColor(int arg0) { - return null; - } - - public int getColumnCount() { - return buffer[0].length; - } - - public int getRowCount() { - return buffer.length; - } - - public int getTermHeight() { - return getCharHeight() * getRowCount(); - } - - public int getTermWidth() { - return getCharWidth() * getColumnCount(); - } - - public void redraw(int arg0, int arg1, int arg2, int arg3, final boolean isSnapshot) { - //NOT IMPLEMENTED - } - - public void redraw(int arg0, int arg1, int arg2, int arg3) { - //redraw(arg0, arg1, arg2, arg3, false); - } - - public void resetAllAttributes() { - } - - public void scroll_area(int icol, int irow, int w, int h, final int dcol, final int drow) { - final ScreenEmulator emu = this; - runTask(new ScreenTask() { - public void process(int row, int col, ByteWrapper val) { - int orow = row - drow; - int ocol = col - dcol; - if (emu.getColumnCount() > ocol && - emu.getRowCount() > orow && orow >= 0 && ocol >= 0) { - val.setValue(get(orow, ocol)); - } - } - }, irow, icol, irow + h, icol + w, drow > 0, dcol > 0); - runTask(new ScreenTask() { - public void process(int row, int col, ByteWrapper val) { - char empty = ' '; - int orow = row + drow; - int ocol = col + dcol; - if (emu.getColumnCount() <= ocol || emu.getRowCount() <= orow - || ocol < 0 || orow < 0) { - val.setValue((byte) (empty & 0xFF)); - } - } - }, irow, icol, irow + h, icol + w, drow > 0, dcol > 0); - } - - public void setBackGround(Object arg0) { - //NOT IMPLEMENTED - } - - public void setBold() { - //NOT IMPLEMENTED - } - - public void setCursor(int arg0, int arg1) { - //NOT IMPLEMENTED - } - - public void setDefaultBackGround(Object arg0) { - //NOT IMPLEMENTED - } - - public void setDefaultForeGround(Object arg0) { - //NOT IMPLEMENTED - } - - public void setForeGround(Object arg0) { - //NOT IMPLEMENTED - } - - public void setReverse() { - //NOT IMPLEMENTED - } - - public void setUnderline() { - //NOT IMPLEMENTED - } - - public void start(Connection connection) { - Emulator emulator = new EmulatorVT100(this, connection.getInputStream()); - emulator.reset(); - emulator.start(); - redraw(0, 0, getTermWidth(), getTermHeight()); - } - -} diff --git a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/ScreenTask.java b/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/ScreenTask.java deleted file mode 100644 index 6af863a5c..000000000 --- a/score-ssh/src/main/java/org/openscore/content/ssh/utils/simulator/visualization/ScreenTask.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.visualization; - - -public abstract class ScreenTask { - - public abstract void process(int x, int y, ByteWrapper val); - - public boolean completed() { - return false; - } - - public boolean nextLine() { - return false; - } -} diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/services/impl/SSHServiceImplTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/services/impl/SSHServiceImplTest.java index cceb67939..4ada8b52e 100644 --- a/score-ssh/src/test/java/org/openscore/content/ssh/services/impl/SSHServiceImplTest.java +++ b/score-ssh/src/test/java/org/openscore/content/ssh/services/impl/SSHServiceImplTest.java @@ -5,20 +5,16 @@ import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; -import org.openscore.content.ssh.entities.CommandResult; -import org.openscore.content.ssh.entities.ConnectionDetails; -import org.openscore.content.ssh.entities.ExpectCommandResult; -import org.openscore.content.ssh.entities.KeyFile; -import org.openscore.content.ssh.entities.KnownHostsFile; -import org.openscore.content.ssh.services.SSHService; -import org.openscore.content.ssh.services.impl.SSHServiceImpl; -import org.openscore.content.ssh.utils.simulator.ShellSimulator; -import org.openscore.content.ssh.utils.simulator.visualization.IShellVisualizer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; +import org.openscore.content.ssh.entities.CommandResult; +import org.openscore.content.ssh.entities.ConnectionDetails; +import org.openscore.content.ssh.entities.KeyFile; +import org.openscore.content.ssh.entities.KnownHostsFile; +import org.openscore.content.ssh.services.SSHService; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -39,7 +35,7 @@ public class SSHServiceImplTest { private static final String SHELL_PATH = "path"; private static final String PASS_PHRASE = "passPhrase"; - private static final Path KNOWN_HOSTS_PATH = Paths.get(System.getProperty("user.home"), ".ssh", "known_hosts");; + private static final Path KNOWN_HOSTS_PATH = Paths.get(System.getProperty("user.home"), ".ssh", "known_hosts"); private static final String KNOWN_HOSTS_POLICY = "allow"; private static final String OUTPUT = "output"; private static final String HOST = "host"; @@ -57,12 +53,7 @@ public class SSHServiceImplTest { private ChannelShell channelShellMock; @Mock private CommandResult commandResultMock; - @Mock - private ExpectCommandResult expectCommandResultMock; - @Mock - private ShellSimulator simulatorMock; - @Mock - private IShellVisualizer visualizerMock; + @Mock private JSch jSchMock; @@ -74,12 +65,6 @@ public void setUp() throws Exception { Mockito.doNothing().when(jSchMock).addIdentity(SHELL_PATH); PowerMockito.when(sessionMock.openChannel("shell")).thenReturn(channelShellMock); Mockito.doNothing().when(channelShellMock).connect(CONNECT_TIMEOUT); - - PowerMockito.whenNew(ShellSimulator.class).withAnyArguments().thenReturn(simulatorMock); - - PowerMockito.when(simulatorMock.getOutput()).thenReturn(OUTPUT); - PowerMockito.when(simulatorMock.addVisualizer("basic")).thenReturn(visualizerMock); - PowerMockito.when(visualizerMock.getXMLSummary()).thenReturn(XML_SUMMARY); } @Test @@ -134,38 +119,6 @@ public void testRunShellCommandInvalidEncoding() throws Exception { sshService.runShellCommand("", "test", true, CONNECT_TIMEOUT, COMMAND_TIMEOUT); } - @Test - public void testRunExpectCommand() throws Exception { - SSHService sshService = new SSHServiceImpl(sessionMock, channelShellMock); - ExpectCommandResult expectCommandResult = sshService.runExpectCommand("ls", "UTF-8", "\\n", 1000, CONNECT_TIMEOUT, COMMAND_TIMEOUT); - assertEquals(expectCommandResult.getExitCode(), 0); - assertEquals(expectCommandResult.getStandardError(), null); - assertEquals(expectCommandResult.getStandardOutput(), OUTPUT); - assertEquals(expectCommandResult.getExpectXmlOutputs(), XML_SUMMARY); - - sshService = new SSHServiceImpl(sessionMock, channelShellMock); - expectCommandResult = sshService.runExpectCommand("ls", "UTF-8", "\\n", 1000, 0, 0); - assertEquals(expectCommandResult.getExitCode(), 0); - assertEquals(expectCommandResult.getStandardError(), null); - assertEquals(expectCommandResult.getStandardOutput(), OUTPUT); - assertEquals(expectCommandResult.getExpectXmlOutputs(), XML_SUMMARY); - - sshService = new SSHServiceImpl(sessionMock, channelShellMock); - expectCommandResult = sshService.runExpectCommand("ls", "UTF-8", "test123!@#", 1000, 0, 0); - assertEquals(expectCommandResult.getExitCode(), 0); - assertEquals(expectCommandResult.getStandardError(), null); - assertEquals(expectCommandResult.getStandardOutput(), OUTPUT); - assertEquals(expectCommandResult.getExpectXmlOutputs(), XML_SUMMARY); - - sshService = new SSHServiceImpl(sessionMock, channelShellMock); - expectCommandResult = sshService.runExpectCommand("", "UTF-8", "\\n", 1000, 0, 0); - assertEquals(expectCommandResult.getExitCode(), 0); - assertEquals(expectCommandResult.getStandardError(), null); - assertEquals(expectCommandResult.getStandardOutput(), OUTPUT); - assertEquals(expectCommandResult.getExpectXmlOutputs(), XML_SUMMARY); - - } - @Test public void testCreateLocalTunnel() throws JSchException { SSHService sshService = new SSHServiceImpl(sessionMock, channelShellMock); @@ -174,24 +127,6 @@ public void testCreateLocalTunnel() throws JSchException { verify(sessionMock).setPortForwardingL(PORT, HOST, PORT); } - @Test - public void testIsConnected() { - SSHService sshService = new SSHServiceImpl(sessionMock, channelShellMock); - final boolean connected = sshService.isConnected(); - assertEquals(false, connected); - - verify(sessionMock).isConnected(); - } - - @Test - public void testIsExpectChannelConnected() { - SSHService sshService = new SSHServiceImpl(sessionMock, channelShellMock); - final boolean connected = sshService.isExpectChannelConnected(); - assertEquals(false, connected); - - verify(channelShellMock).isConnected(); - } - @Test public void testClose() { SSHService sshService = new SSHServiceImpl(sessionMock, channelShellMock); diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/SafeMacherTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/SafeMacherTest.java deleted file mode 100644 index a67af459c..000000000 --- a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/SafeMacherTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.openscore.content.ssh.utils.simulator; - -import org.junit.Test; -import org.openscore.content.ssh.utils.simulator.SafeMatcher; - -import static org.junit.Assert.assertEquals; - -/** - * Created by vranau on 11/25/2014. - */ -public class SafeMacherTest { - - @Test - public void testMatch() throws Exception { - assertEquals(false, SafeMatcher.match("toTest", "regex", 100)); - } -} \ No newline at end of file diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ScriptLinesTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ScriptLinesTest.java deleted file mode 100644 index 0ff0cb4a8..000000000 --- a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ScriptLinesTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.openscore.content.ssh.utils.simulator; - -import org.junit.Before; -import org.junit.Test; -import org.openscore.content.ssh.utils.simulator.ScriptLines; - -import static org.junit.Assert.*; - -/** - * Created by vranau on 11/25/2014. - */ -public class ScriptLinesTest { - - private ScriptLines scriptLines; - private String script = "send ls \nexpect ls"; - - @Before - public void setUp() throws Exception { - scriptLines = new ScriptLines(script); - } - - @Test - public void testPeekNext() { - assertEquals("expect ls", scriptLines.peekNext()); - ScriptLines scriptLinesNew = new ScriptLines(script) { - @Override - public boolean hasNext() { - return false; - } - }; - assertNull(scriptLinesNew.peekNext()); - } - - @Test - public void testToString() { - assertEquals("Script:currently on line: 1\n" + - "1 send ls2 expect ls", scriptLines.toString()); - } - - @Test - public void testNextLine() { - assertEquals(true, scriptLines.nextLine()); - ScriptLines scriptLinesNew = new ScriptLines(script) { - @Override - public boolean hasNext() { - return false; - } - }; - assertFalse(scriptLinesNew.nextLine()); - } -} \ No newline at end of file diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ScriptModelTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ScriptModelTest.java deleted file mode 100644 index 62ca9cf3e..000000000 --- a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ScriptModelTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.openscore.content.ssh.utils.simulator; - -import org.openscore.content.ssh.utils.simulator.ScriptLines; -import org.openscore.content.ssh.utils.simulator.ScriptModel; -import org.openscore.content.ssh.utils.simulator.ScriptRunner; -import org.openscore.content.ssh.utils.simulator.elements.AlwaysOn; -import org.openscore.content.ssh.utils.simulator.elements.Expect; -import org.openscore.content.ssh.utils.simulator.elements.Send; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import static org.junit.Assert.*; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * Created by vranau on 11/25/2014. - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({ScriptModel.class, AlwaysOn.class}) -public class ScriptModelTest { - - - @Mock - private AlwaysOn alwaysOnMock; - @Mock - private ScriptRunner scriptRunnerMock; - - private ScriptModel scriptModel; - private String script = "wait 1000\nexpect 1000\nsend ls \n always"; - private String newLine = "\n"; - private long matchTimeout = 1000L; - - - @Before - public void setUp() throws Exception { - mockStatic(AlwaysOn.class); - when(AlwaysOn.getInstance(Matchers.anyObject(), Matchers.anyObject())).thenReturn(alwaysOnMock); - scriptModel = new ScriptModel(script, newLine.toCharArray()); - } - - @Test - public void testCheckAlwaysHandlers() throws Exception { - - AlwaysOn alwaysOn = scriptModel.checkAlwaysHandlers("", matchTimeout); - assertNull(alwaysOn); - when(alwaysOnMock.match("", matchTimeout)).thenReturn(true); - alwaysOn = scriptModel.checkAlwaysHandlers("", matchTimeout); - assertEquals(this.alwaysOnMock, alwaysOn); - } - - @Test - public void testIsExceptAllowed() throws Exception { - Expect expect = scriptModel.IsExceptAllowed("1000", scriptRunnerMock, matchTimeout); - assertNotNull(expect); - expect = scriptModel.IsExceptAllowed("", scriptRunnerMock, matchTimeout); - assertNull(expect); - } - - @Test - public void testIsSendAllowed() throws Exception { - Send send = scriptModel.IsSendAllowed(); - assertNull(send); - ScriptModel scriptModelnew = new ScriptModel("send ls", newLine.toCharArray()); - send = scriptModelnew.IsSendAllowed(); - assertNotNull(send); - assertFalse(send.waitIfNeeded()); - assertEquals("ls" + newLine, String.valueOf(send.get())); - } - - @Test - public void testGetCommandsLeft() { - assertEquals(2, scriptModel.getCommandsLeft()); - } -} diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ScriptRunnerTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ScriptRunnerTest.java deleted file mode 100644 index 3e4b7e045..000000000 --- a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ScriptRunnerTest.java +++ /dev/null @@ -1,161 +0,0 @@ -package org.openscore.content.ssh.utils.simulator; - -import org.openscore.content.ssh.utils.simulator.ScriptModel; -import org.openscore.content.ssh.utils.simulator.ScriptRunner; -import org.openscore.content.ssh.utils.simulator.ShellSimulator; -import org.openscore.content.ssh.utils.simulator.elements.AlwaysOn; -import org.openscore.content.ssh.utils.simulator.elements.Expect; -import org.openscore.content.ssh.utils.simulator.elements.Send; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.io.InputStream; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; - -import static junit.framework.Assert.*; -import static org.powermock.api.mockito.PowerMockito.*; - -/** - * Created by vranau on 11/24/2014. - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({ScriptRunner.class}) -public class ScriptRunnerTest { - private String script = "send ls \nexpect ls"; - private long matchTimeout = 1000L; - private long readTimeout = 1000L; - private long sleepTimeout = 1000L; - private long characterDelay = 1000L; - private String newLine = "\n"; - private ScriptRunner scriptRunner; - - @Mock - private PipedInputStream pipedInputStreamMock; - @Mock - private ShellSimulator shellSimulatorMock; - @Mock - private PipedOutputStream pipedOutputStreamMock; - @Mock - private ScriptModel parserMock; - @Mock - private AlwaysOn alwaysOnMock; - @Mock - private Expect expectMock; - @Mock - private Send sendMock; - @Mock - private InputStream inputStreamMock; - - @Before - public void setUp() throws Exception { - whenNew(ScriptModel.class).withAnyArguments().thenReturn(parserMock); - scriptRunner = new ScriptRunner(script, matchTimeout, readTimeout, sleepTimeout, characterDelay, newLine.toCharArray()); - } - - @Test - public void testAddPipe() throws Exception { - - whenNew(PipedOutputStream.class).withArguments(pipedInputStreamMock).thenReturn(pipedOutputStreamMock); - scriptRunner.addPipe(pipedInputStreamMock); - shellSimulatorMock.getException(); - verifyNew(PipedOutputStream.class).withArguments(pipedInputStreamMock); - scriptRunner.addPipe(null); - verifyZeroInteractions(pipedInputStreamMock, pipedOutputStreamMock); - } - - @Test - public void testGetOutput() { - String output = scriptRunner.getOutput(); - assertEquals("", output); - } - - @Test - public void testSetCaptureOutput() { - scriptRunner.setCaptureOutput(true); - scriptRunner.setCaptureOutput(false); - boolean captureOutput = Boolean.parseBoolean(null); - scriptRunner.setCaptureOutput(captureOutput); - } - - @Test - public void testGetCommandsLeft() { - when(parserMock.getCommandsLeft()).thenReturn(10); - assertEquals(10, scriptRunner.getCommandsLeft()); - } - - @Test - public void testNoMoreCommandsLeft() { - when(parserMock.getCommandsLeft()).thenReturn(10); - assertEquals(false, scriptRunner.noMoreCommandsLeft()); - - when(parserMock.getCommandsLeft()).thenReturn(0); - assertEquals(true, scriptRunner.noMoreCommandsLeft()); - } - - @Test - public void testTerminate() { - scriptRunner.terminate(); - } - - @Test - public void testGetDeltaT() { - final long deltaT = scriptRunner.getDeltaT(); - assertTrue(deltaT > 0); - } - - @Test - public void testRun() throws Exception { - - scriptRunner = new ScriptRunner(script, matchTimeout, readTimeout, sleepTimeout, characterDelay, newLine.toCharArray()); - when(parserMock.getCommandsLeft()).thenReturn(10); - scriptRunner.run(); - final String exception = scriptRunner.getException().toLowerCase(); - assertTrue(exception.contains("readTimeout at:".toLowerCase())); - } - - @Test - public void checkAlwaysHandlers() throws Exception { - boolean checkAlwaysHandlers = scriptRunner.checkAlwaysHandlers(); - assertEquals(false, checkAlwaysHandlers); - - when(parserMock.checkAlwaysHandlers("", matchTimeout)).thenReturn(alwaysOnMock); - checkAlwaysHandlers = scriptRunner.checkAlwaysHandlers(); - assertEquals(true, checkAlwaysHandlers); - - when(parserMock.checkAlwaysHandlers("", matchTimeout)).thenThrow(new Exception("test exception")); - checkAlwaysHandlers = scriptRunner.checkAlwaysHandlers(); - assertEquals(false, checkAlwaysHandlers); - assertTrue(scriptRunner.getException().contains("test exception")); - } - - @Test - public void testSendable() throws Exception { - boolean sendable = scriptRunner.sendable(); - assertFalse(sendable); - - when(parserMock.getCommandsLeft()).thenReturn(10); - sendable = scriptRunner.sendable(); - assertFalse(sendable); - - when(parserMock.IsExceptAllowed("", scriptRunner, matchTimeout)).thenReturn(expectMock); - when(parserMock.IsSendAllowed()).thenReturn(sendMock); - sendable = scriptRunner.sendable(); - assertTrue(sendable); - } - - @Test - public void testProcess() throws Exception { - boolean process = scriptRunner.process(); - assertFalse(process); - scriptRunner.in = inputStreamMock; - process = scriptRunner.process(); - assertFalse(process); - scriptRunner.in = null; - } - -} diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ShellSimulatorTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ShellSimulatorTest.java deleted file mode 100644 index 202fab0fd..000000000 --- a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/ShellSimulatorTest.java +++ /dev/null @@ -1,155 +0,0 @@ -package org.openscore.content.ssh.utils.simulator; - -import org.openscore.content.ssh.utils.simulator.ScriptRunner; -import org.openscore.content.ssh.utils.simulator.ShellSimulator; -import org.openscore.content.ssh.utils.simulator.visualization.IShellVisualizer; -import org.openscore.content.ssh.utils.simulator.visualization.ScreenEmulator; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.io.InputStream; -import java.io.OutputStream; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.powermock.api.mockito.PowerMockito.whenNew; - -/** - * Created by vranau on 11/24/2014. - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({ShellSimulator.class, ScriptRunner.class}) -public class ShellSimulatorTest { - - private String script = "send ls \nexpect ls"; - private long matchTimeout = 1000L; - private long readTimeout = 1000L; - private long sleepTimeout = 1000L; - private long characterDelay = 1000L; - private String newLine = "\n"; - final String errorMessage = "Script did not fully finish, had: 0 commands left "; - - ShellSimulator shellSimulator; - - @Mock - private ScriptRunner simulatorMock; - - @Mock - private ScreenEmulator screenEmulatorMock; - - @Mock - private InputStream inputStreamMock; - - @Mock - private OutputStream outputStreamMock; - - @Before - public void setUp() throws Exception { - whenNew(ScriptRunner.class).withAnyArguments().thenReturn(simulatorMock); - when(simulatorMock.getException()).thenReturn(""); - whenNew(ScreenEmulator.class).withAnyArguments().thenReturn(screenEmulatorMock); - - - shellSimulator = new ShellSimulator(script, matchTimeout, readTimeout, sleepTimeout, characterDelay); - } - - @Test - public void testConstructors() throws Exception { - final String defaultCharset = "UTF-8"; - - ShellSimulator shellSimulator = new ShellSimulator(script, matchTimeout, readTimeout, sleepTimeout, characterDelay, newLine.toCharArray()); - assertEquals(shellSimulator.getException(), errorMessage); - - shellSimulator = new ShellSimulator(script, matchTimeout, readTimeout, sleepTimeout, characterDelay); - assertEquals(shellSimulator.getException(), errorMessage); - - shellSimulator = new ShellSimulator(script, matchTimeout, readTimeout, sleepTimeout, characterDelay, newLine.toCharArray(), defaultCharset); - assertEquals(shellSimulator.getException(), errorMessage); - - shellSimulator = new ShellSimulator(script, matchTimeout, readTimeout, sleepTimeout, characterDelay, newLine.toCharArray(), ""); - assertEquals(shellSimulator.getException(), errorMessage); - - shellSimulator = new ShellSimulator(script, matchTimeout, readTimeout, sleepTimeout, characterDelay, defaultCharset, true); - assertEquals(shellSimulator.getException(), errorMessage); - - shellSimulator = new ShellSimulator(script, matchTimeout, readTimeout, sleepTimeout, characterDelay, newLine.toCharArray(), defaultCharset, false); - assertEquals(shellSimulator.getException(), errorMessage); - } - - @Test - public void testAddVisualizer() throws Exception { - - IShellVisualizer iShellVisualizer = shellSimulator.addVisualizer("basic"); - assertEquals(true, iShellVisualizer instanceof ScreenEmulator); - - iShellVisualizer = shellSimulator.addVisualizer(""); - assertEquals(true, iShellVisualizer instanceof ScreenEmulator); - - String name = null; - iShellVisualizer = shellSimulator.addVisualizer(name); - assertEquals(true, iShellVisualizer instanceof ScreenEmulator); - - iShellVisualizer = shellSimulator.addVisualizer("none"); - assertNull(iShellVisualizer); - - shellSimulator.addVisualizer(screenEmulatorMock); - } - - @Test - public void testAddVisualizerWithException() throws Exception { - - String exceptionMessage = ""; - try { - shellSimulator.addVisualizer("test"); - } catch (Exception ex) { - exceptionMessage = ex.getMessage(); - } - assertEquals("The specified visualizer is of unknown type", exceptionMessage); - } - - @Test - public void testSetStreams() throws Exception { - - shellSimulator.setStreams(inputStreamMock, outputStreamMock); - assertEquals(inputStreamMock, simulatorMock.in); - assertEquals(outputStreamMock, simulatorMock.out); - } - - @Test - public void testGetOutput() { - when(simulatorMock.getOutput()).thenReturn("output"); - final String output = shellSimulator.getOutput(); - assertEquals("output", output); - } - - @Test - public void testGetException() throws Exception { - - when(simulatorMock.noMoreCommandsLeft()).thenReturn(true); - String exception = shellSimulator.getException(); - assertEquals("", exception); - - when(simulatorMock.noMoreCommandsLeft()).thenReturn(false); - exception = shellSimulator.getException(); - assertEquals(errorMessage, exception); - } - - @Test - public void testNoMoreCommandsLeft() { - assertEquals(false, shellSimulator.noMoreCommandsLeft()); - when(simulatorMock.noMoreCommandsLeft()).thenReturn(true); - assertEquals(true, shellSimulator.noMoreCommandsLeft()); - } - - @Test - public void testRun() throws Exception { - - when(simulatorMock.isAlive()).thenReturn(false); - shellSimulator.run(-1L); - } -} diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/AlwaysOnTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/AlwaysOnTest.java deleted file mode 100644 index 99cbf1649..000000000 --- a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/AlwaysOnTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -import junit.framework.Assert; -import org.openscore.content.ssh.utils.simulator.ScriptLines; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.openscore.content.ssh.utils.simulator.elements.AlwaysOn; -import org.openscore.content.ssh.utils.simulator.elements.Expect; -import org.openscore.content.ssh.utils.simulator.elements.Send; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.util.Arrays; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.anyString; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * Created by vranau on 11/25/2014. - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({AlwaysOn.class, Send.class}) -public class AlwaysOnTest { - - private String script = "send ls always\n on expect"; - private String newLine = "\n"; - private ScriptLines scriptLines = new ScriptLines(script); - @Mock - private Send sendMock; - - @Test - public void testGetInstance() throws Exception { - mockStatic(Send.class); - when(Send.getInstance(anyString(), Matchers.anyObject())).thenReturn(sendMock); - AlwaysOn instance = AlwaysOn.getInstance(scriptLines, newLine.toCharArray()); - Assert.assertNotNull(instance); - - instance = AlwaysOn.getInstance(null, null); - Assert.assertNotNull(instance); - } - - @Test - public void testMatch() throws Exception { - AlwaysOn alwaysOn = new AlwaysOn(); - final Expect command = new Expect(); - command.set("ls"); - alwaysOn.setExpect(command); - assertEquals(true, alwaysOn.match("ls", 10)); - alwaysOn = new AlwaysOn(); - assertEquals(false, alwaysOn.match("ls", 10)); - } - - @Test - public void testGet() { - AlwaysOn alwaysOn = new AlwaysOn(); - assertEquals("[]", Arrays.toString(alwaysOn.get())); - final Send command = new Send(); - command.set("ls"); - alwaysOn.setCommand(command); - assertEquals("[l, s, \n]", Arrays.toString(alwaysOn.get())); - - alwaysOn.setCommand(null); - assertEquals("[]", Arrays.toString(alwaysOn.get())); - } - - -} \ No newline at end of file diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/ExpectEndsWithTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/ExpectEndsWithTest.java deleted file mode 100644 index 2b95be6d5..000000000 --- a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/ExpectEndsWithTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -import org.junit.Test; -import org.openscore.content.ssh.utils.simulator.elements.ExpectEndsWith; - -import static org.junit.Assert.assertEquals; - -/** - * Created by vranau on 11/25/2014. - */ -public class ExpectEndsWithTest { - - @Test - public void testMatch() throws Exception { - ExpectEndsWith expectEndsWith = new ExpectEndsWith(); - expectEndsWith.set("ls"); - assertEquals(true, expectEndsWith.match("ls", 10)); - - expectEndsWith.set(""); - assertEquals(true, expectEndsWith.match("", 10)); - expectEndsWith.set(null); - assertEquals(true, expectEndsWith.match("", 10)); - - expectEndsWith.set("ls"); - assertEquals(false, expectEndsWith.match("", 10)); - - expectEndsWith.set("ls"); - assertEquals(false, expectEndsWith.match(null, 10)); - - expectEndsWith.set("ls"); - assertEquals(false, expectEndsWith.match(null, 0)); - - expectEndsWith.set("ls"); - assertEquals(false, expectEndsWith.match(null, -3453)); - } -} \ No newline at end of file diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/ExpectLastLineTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/ExpectLastLineTest.java deleted file mode 100644 index a9629d59e..000000000 --- a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/ExpectLastLineTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -import org.junit.Test; -import org.openscore.content.ssh.utils.simulator.elements.ExpectLastLine; - -import static org.junit.Assert.assertEquals; - -/** - * Created by vranau on 11/25/2014. - */ -public class ExpectLastLineTest { - - @Test - public void testMatch() throws Exception { - ExpectLastLine expectLastLine = new ExpectLastLine(); - expectLastLine.set("ls"); - assertEquals(true, expectLastLine.match("ls", 10)); - - expectLastLine.set(""); - assertEquals(true, expectLastLine.match("", 10)); - expectLastLine.set(null); - assertEquals(true, expectLastLine.match("", 10)); - - expectLastLine.set("ls"); - assertEquals(false, expectLastLine.match("", 10)); - - expectLastLine.set("ls"); - assertEquals(false, expectLastLine.match(null, 10)); - - expectLastLine.set("ls"); - assertEquals(false, expectLastLine.match(null, 0)); - - expectLastLine.set("ls"); - assertEquals(false, expectLastLine.match(null, -3453)); - } - -} \ No newline at end of file diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/SendCharTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/SendCharTest.java deleted file mode 100644 index 607258fe6..000000000 --- a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/SendCharTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -import org.junit.Test; -import org.openscore.content.ssh.utils.simulator.elements.SendChar; - -import java.util.Arrays; - -import static org.junit.Assert.assertEquals; - -/** - * Created by vranau on 11/25/2014. - */ -public class SendCharTest { - - @Test - public void testSet() { - SendChar sendChar = new SendChar(); - sendChar.set("ls"); - assertEquals("[\u0000]", Arrays.toString(sendChar.get())); - - sendChar.set("0"); - assertEquals("[\u0000]", Arrays.toString(sendChar.get())); - - sendChar.set("32"); - assertEquals("[ ]", Arrays.toString(sendChar.get())); - - sendChar.set("89"); - assertEquals("[Y]", Arrays.toString(sendChar.get())); - - sendChar.set(null); - assertEquals("[\u0000]", Arrays.toString(sendChar.get())); - } - -} \ No newline at end of file diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/SetSimulatorCaptureTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/SetSimulatorCaptureTest.java deleted file mode 100644 index e7ca034b1..000000000 --- a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/SetSimulatorCaptureTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -import org.junit.Test; -import org.openscore.content.ssh.utils.simulator.elements.SetSimulatorCapture; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -/** - * Created by vranau on 11/25/2014. - */ -public class SetSimulatorCaptureTest { - - @Test - public void testSet() { - SetSimulatorCapture setSimulatorCapture = new SetSimulatorCapture(); - setSimulatorCapture.set("test"); - assertFalse(setSimulatorCapture.enable); - - setSimulatorCapture.set(""); - assertFalse(setSimulatorCapture.enable); - - setSimulatorCapture.set(null); - assertFalse(setSimulatorCapture.enable); - - setSimulatorCapture.set("1"); - assertFalse(setSimulatorCapture.enable); - - setSimulatorCapture.set("true"); - assertEquals(true, setSimulatorCapture.enable); - - setSimulatorCapture.execute(); - } - -} \ No newline at end of file diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/SimulatorModificationCommandTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/SimulatorModificationCommandTest.java deleted file mode 100644 index b5bacf7a2..000000000 --- a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/elements/SimulatorModificationCommandTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.elements; - -import org.openscore.content.ssh.utils.simulator.IScriptRunner; -import org.openscore.content.ssh.utils.simulator.ScriptModel; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.openscore.content.ssh.utils.simulator.elements.SimulatorModificationCommand; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import static org.junit.Assert.assertNotNull; - -/** - * Created by vranau on 11/25/2014. - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({SimulatorModificationCommand.class}) -public class SimulatorModificationCommandTest { - - private ScriptModel scriptModel; - private String script = "send ls \nexpect ls"; - private String newLine = "\n"; - - @Mock - private IScriptRunner simulator; - - @Test - public void testGetInstance() throws Exception { - final SimulatorModificationCommand simulatorModificationCommand = SimulatorModificationCommand.getInstance("captureOutput", simulator); - assertNotNull(simulatorModificationCommand); - - } - -} \ No newline at end of file diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/visualization/ByteWrapperTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/visualization/ByteWrapperTest.java deleted file mode 100644 index d86fc6bea..000000000 --- a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/visualization/ByteWrapperTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.visualization; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.openscore.content.ssh.utils.simulator.visualization.ByteWrapper; -import org.openscore.content.ssh.utils.simulator.visualization.ScreenEmulator; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import static org.junit.Assert.assertEquals; - -/** - * Created by vranau on 11/25/2014. - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({ScreenEmulator.class}) -public class ByteWrapperTest { - - private ByteWrapper byteWrapper; - - @Mock - private ScreenEmulator screenEmulator; - - @Before - public void setUp() throws Exception { - byteWrapper = new ByteWrapper(screenEmulator); - } - - @Test - public void testGetValue() { - assertEquals(32, byteWrapper.getValue()); - } - - @Test - public void testSetValue() { - byte byteValue = 3; - byteWrapper.setValue(byteValue); - assertEquals(3, byteWrapper.getValue()); - byteWrapper.setValue(byteValue); - assertEquals(3, byteWrapper.getValue()); - Mockito.verify(screenEmulator).snapshotBuffer(true); - } - - @Test - public void testClearChanged() { - byte byteValue = 3; - byteWrapper.setValue(byteValue); - assertEquals(3, byteWrapper.getValue()); - byteWrapper.clearChanged(); - byteWrapper.setValue(byteValue); - assertEquals(3, byteWrapper.getValue()); - Mockito.verifyZeroInteractions(screenEmulator); - } - - @Test - public void testClear() { - assertEquals(32, byteWrapper.getValue()); - byteWrapper.clear(); - assertEquals(32, byteWrapper.getValue()); - byte byteValue = 3; - byteWrapper.setValue(byteValue); - assertEquals(3, byteWrapper.getValue()); - byteWrapper.clear(); - assertEquals(32, byteWrapper.getValue()); - byteWrapper.setValue(byteValue); - assertEquals(3, byteWrapper.getValue()); - byteWrapper.clearChanged(); - assertEquals(3, byteWrapper.getValue()); - byteWrapper.clear(); - assertEquals(32, byteWrapper.getValue()); - } - - @Test - public void t() { - - } -} \ No newline at end of file diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/visualization/LinearUpdateTaskTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/visualization/LinearUpdateTaskTest.java deleted file mode 100644 index 4e6097ba0..000000000 --- a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/visualization/LinearUpdateTaskTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.visualization; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.openscore.content.ssh.utils.simulator.visualization.ByteWrapper; -import org.openscore.content.ssh.utils.simulator.visualization.LinearUpdateTask; -import org.openscore.content.ssh.utils.simulator.visualization.ScreenEmulator; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import static org.junit.Assert.assertEquals; - -/** - * Created by vranau on 11/25/2014. - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({ScreenEmulator.class}) -public class LinearUpdateTaskTest { - - private LinearUpdateTask linearUpdateTask; - @Mock - private ScreenEmulator screenEmulator; - - @Test - public void testProcess() { - int length = 10; - linearUpdateTask = new LinearUpdateTask(length) { - @Override - public byte process(int offset) { - return 0; - } - }; - linearUpdateTask.process(1, 6, new ByteWrapper(screenEmulator)); - assertEquals(false, linearUpdateTask.completed()); - assertEquals(false, linearUpdateTask.nextLine()); - - linearUpdateTask = new LinearUpdateTask(length) { - @Override - public byte process(int offset) { - return 10; - } - }; - linearUpdateTask.process(1, 6, new ByteWrapper(screenEmulator)); - assertEquals(false, linearUpdateTask.completed()); - assertEquals(true, linearUpdateTask.nextLine()); - - linearUpdateTask = new LinearUpdateTask(0) { - @Override - public byte process(int offset) { - return 10; - } - }; - linearUpdateTask.process(1, 6, new ByteWrapper(screenEmulator)); - assertEquals(true, linearUpdateTask.completed()); - assertEquals(true, linearUpdateTask.nextLine()); - - - linearUpdateTask = new LinearUpdateTask(0) { - @Override - public byte process(int offset) { - return 10; - } - }; - linearUpdateTask.process(-345435341, 5464436, new ByteWrapper(screenEmulator)); - assertEquals(true, linearUpdateTask.completed()); - assertEquals(true, linearUpdateTask.nextLine()); - - linearUpdateTask = new LinearUpdateTask(0) { - @Override - public byte process(int offset) { - return 10; - } - }; - linearUpdateTask.process(345435341, -5464436, new ByteWrapper(screenEmulator)); - assertEquals(true, linearUpdateTask.completed()); - assertEquals(true, linearUpdateTask.nextLine()); - } -} \ No newline at end of file diff --git a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/visualization/ScreenEmulatorTest.java b/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/visualization/ScreenEmulatorTest.java deleted file mode 100644 index a720c86a2..000000000 --- a/score-ssh/src/test/java/org/openscore/content/ssh/utils/simulator/visualization/ScreenEmulatorTest.java +++ /dev/null @@ -1,136 +0,0 @@ -package org.openscore.content.ssh.utils.simulator.visualization; - -import com.jcraft.jcterm.Connection; -import com.jcraft.jcterm.EmulatorVT100; -import org.dom4j.IllegalAddException; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.openscore.content.ssh.utils.simulator.visualization.ScreenEmulator; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.io.InputStream; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.whenNew; - -/** - * Created by vranau on 11/25/2014. - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({ScreenEmulator.class}) -public class ScreenEmulatorTest { - - private ScreenEmulator screenEmulator; - @Mock - private InputStream inputStream; - @Mock - private Connection connection; - @Mock - private EmulatorVT100 emulator; - - @Before - public void setUp() throws Exception { - screenEmulator = new ScreenEmulator(); - } - - @Test - public void testRun() throws Exception { - whenNew(EmulatorVT100.class).withAnyArguments().thenReturn(emulator); - screenEmulator.run(inputStream); - verify(emulator).reset(); - verify(emulator).start(); - } - - @Test - public void testGetXmlSummary() { - assertEquals("\n", screenEmulator.getXMLSummary()); - screenEmulator.beep(); - assertEquals("\n" + - "\n" + - "", screenEmulator.getXMLSummary()); - ScreenEmulator screenEmulatorNew = new ScreenEmulator(); - screenEmulatorNew.snapshotBuffer(true); - assertEquals("\n", screenEmulatorNew.getXMLSummary()); - } - - @Test - public void testBufferAsString() { - String bufferAsString = screenEmulator.bufferAsString(true); - assertEquals("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", bufferAsString); - - bufferAsString = screenEmulator.bufferAsString(false); - assertEquals("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", bufferAsString); - } - - @Test - public void testSnapshotBuffer() { - String snapshotBuffer = screenEmulator.snapshotBuffer(true); - assertEquals("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", snapshotBuffer); - - snapshotBuffer = screenEmulator.snapshotBuffer(false); - assertEquals("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", snapshotBuffer); - - ScreenEmulator screenEmulatorNew = new ScreenEmulator() { - @Override - public String bufferAsString(boolean clearChanges) { - return "Frame"; - } - }; - snapshotBuffer = screenEmulatorNew.snapshotBuffer(true); - assertEquals("Frame", snapshotBuffer); - snapshotBuffer = screenEmulatorNew.snapshotBuffer(true); - assertEquals("Frame", snapshotBuffer); - } - - @Test - public void testBeep() { - screenEmulator.beep(); - assertEquals("\n\n", screenEmulator.getXMLSummary()); - } - - @Test(expected = IllegalAddException.class) - public void testBeepWithException() { - screenEmulator.beep(); - assertEquals("\n\n", screenEmulator.getXMLSummary()); - screenEmulator.beep(); - assertEquals("\n\n", screenEmulator.getXMLSummary()); - - } - - @Test - public void testClear() { - assertEquals("\n", screenEmulator.getXMLSummary()); - screenEmulator.clear(); - assertEquals("\n", screenEmulator.getXMLSummary()); - } - - @Test - public void testClearArea() { - screenEmulator.clear_area(2, 1, 10, 10); - } - - @Test - public void testDrawString() { - screenEmulator.drawString("string", 2, 3); - } - - @Test - public void testGetters() { - assertEquals(1, screenEmulator.getCharHeight()); - assertEquals(1, screenEmulator.getCharWidth()); - assertEquals(null, screenEmulator.getColor(333)); - assertEquals(80, screenEmulator.getColumnCount()); - assertEquals(24, screenEmulator.getRowCount()); - assertEquals(24, screenEmulator.getTermHeight()); - assertEquals(80, screenEmulator.getTermWidth()); - } - - @Test - public void testScrollArea() { - screenEmulator.scroll_area(0, 0, 0, 0, 0, 0); - } -} \ No newline at end of file