From b044fcc906fe8c4f9e0911e98b948ba2fbd27ec1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Mih=C3=A1lek?= Date: Thu, 15 Sep 2016 13:03:47 +0200 Subject: [PATCH 01/11] Migrate project structure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Divide project into submodules: jrobot-remote-server -> Core project jrobot-feaures -> Feature definition jrobot-karaf -> Minimal karaf distribution jrobot-test-library -> Deployment test Add acceptnce tests: single-feature-tests Signed-off-by: Martin Mihálek --- .gitignore | 2 +- atest/libs/pom.xml | 41 - .../examplelib/FullDynamic.java | 40 - .../robotframework/examplelib/MinDynamic.java | 14 - .../examplelib/MinDynamicKwargs.java | 33 - .../org/robotframework/examplelib/Static.java | 8 - .../examplelib/impl/Keywords.java | 858 ------------------ .../examplelib/impl/MyException.java | 9 - .../examplelib/impl/MyObject.java | 14 - .../examplelib/impl/SpecialException.java | 15 - .../impl/SpecificSuppressedNameException.java | 6 - .../impl/SuppressedNameException.java | 11 - atest/run.py | 77 -- atest/servercontroller.py | 113 --- atest/statuschecker.py | 190 ---- atest/tests/ProxyableRemote.py | 43 - atest/tests/Z_LAST__special_failures.txt | 26 - atest/tests/argument_counts.txt | 36 - atest/tests/argument_types.txt | 79 -- atest/tests/basic_communication.txt | 31 - atest/tests/failures.txt | 40 - atest/tests/finding_keywords.txt | 11 - atest/tests/invalid_argument_counts.txt | 29 - atest/tests/kwargs.txt | 8 - atest/tests/logging.txt | 44 - atest/tests/resource.txt | 16 - atest/tests/return_values.txt | 139 --- atest/tests/traceback.txt | 18 - atest/tests/variables.py | 29 - examples/AnnotationLibrary/README.txt | 29 - examples/AnnotationLibrary/pom.xml | 114 --- .../java/com/example/MyRemoteLibrary.java | 46 - .../com/example/keywords/QueueManager.java | 59 -- .../main/resources/com/example/__intro__.txt | 5 - .../com/example/MyRemoteLibraryLauncher.java | 9 - .../LibraryDocumentationGeneratorTest.java | 55 -- .../resources/robotframework/maven.properties | 5 - .../robotframework/tests/MyRemoteLibrary.txt | 31 - .../robotframework/tests/Resources/common.txt | 13 - .../robotframework/tests/TypeLibrary.py | 16 - jrobot-features/pom.xml | 88 ++ .../src/main/resources/features.xml | 11 + jrobot-karaf/pom.xml | 63 ++ .../acceptance/010_feature_tests.robot | 20 + .../test/robotframework/karaf_keywords.robot | 82 ++ jrobot-remote-server/pom.xml | 114 +++ .../remoteserver/RemoteServer.java | 0 .../remoteserver/RemoteServerImpl.java | 0 .../remoteserver/cli/CommandLineHelper.java | 0 .../context/RemoteServerContext.java | 0 .../remoteserver/javalib/KeywordOverload.java | 0 .../javalib/OverloadableKeyword.java | 0 .../javalib/SimpleKeywordExtractor.java | 0 .../javalib/SimpleKeywordFactory.java | 0 .../javalib/SingleClassLibrary.java | 0 .../library/DefaultRemoteLibraryFactory.java | 0 .../library/DynamicApiRemoteLibrary.java | 0 .../remoteserver/library/RemoteLibrary.java | 0 .../library/RemoteLibraryFactory.java | 0 .../library/StaticApiRemoteLibrary.java | 0 .../remoteserver/logging/Jetty2Log4J.java | 0 .../servlet/IllegalPathException.java | 0 ...eServerRequestProcessorFactoryFactory.java | 0 .../servlet/RemoteServerServlet.java | 0 .../remoteserver/servlet/ServerMethods.java | 0 .../xmlrpc/ByteArrayToStringParser.java | 0 .../xmlrpc/IterableSerializer.java | 0 .../remoteserver/xmlrpc/MapSerializer.java | 0 .../xmlrpc/ReflectiveHandlerMapping.java | 0 .../remoteserver/xmlrpc/StringSerializer.java | 0 .../remoteserver/xmlrpc/TypeFactory.java | 0 .../blueprint/jrobot-remote-server.xml | 12 + .../remoteserver/RemoteLibraryClient.java | 0 .../remoteserver/RemoteServerImplTest.java | 0 .../cli/CommandLineHelpertTest.java | 0 .../javalib/OverloadableKeywordTest.java | 0 .../javalib/SimpleKeywordExtractorTest.java | 0 .../javalib/SimpleKeywordFactoryTest.java | 0 .../javalib/SingleClassLibraryTest.java | 0 .../DefaultRemoteLibraryFactoryTest.java | 0 .../library/DynamicApiRemoteLibraryTest.java | 0 .../library/StaticApiRemoteLibraryTest.java | 0 .../servlet/AlternativeContainerTest.java | 0 .../servlet/RemoteServerServletTest.java | 0 .../ConflictingOverloadVariableArguments.java | 0 .../testlibraries/DuplicateKeywords.java | 0 .../DynamicOneRunKeywordKwargs.java | 0 .../DynamicOneRunKeywordKwargsList.java | 0 .../DynamicOneRunKeywordNoKwargs.java | 0 .../testlibraries/DynamicUsingLists.java | 0 .../testlibraries/OverloadedMethods.java | 0 .../remoteserver/testlibraries/StaticOne.java | 0 .../remoteserver/testlibraries/StaticTwo.java | 0 jrobot-test-library/pom.xml | 53 ++ .../org/robotframework/test/TestLibrary.java | 11 + .../blueprint/jrobot-test-library.xml | 10 + pom.xml | 319 +++---- .../OSGI-INF/blueprint/remote-server.xml | 11 - 98 files changed, 628 insertions(+), 2528 deletions(-) delete mode 100644 atest/libs/pom.xml delete mode 100644 atest/libs/src/main/java/org/robotframework/examplelib/FullDynamic.java delete mode 100644 atest/libs/src/main/java/org/robotframework/examplelib/MinDynamic.java delete mode 100644 atest/libs/src/main/java/org/robotframework/examplelib/MinDynamicKwargs.java delete mode 100644 atest/libs/src/main/java/org/robotframework/examplelib/Static.java delete mode 100644 atest/libs/src/main/java/org/robotframework/examplelib/impl/Keywords.java delete mode 100644 atest/libs/src/main/java/org/robotframework/examplelib/impl/MyException.java delete mode 100644 atest/libs/src/main/java/org/robotframework/examplelib/impl/MyObject.java delete mode 100644 atest/libs/src/main/java/org/robotframework/examplelib/impl/SpecialException.java delete mode 100644 atest/libs/src/main/java/org/robotframework/examplelib/impl/SpecificSuppressedNameException.java delete mode 100644 atest/libs/src/main/java/org/robotframework/examplelib/impl/SuppressedNameException.java delete mode 100644 atest/run.py delete mode 100644 atest/servercontroller.py delete mode 100644 atest/statuschecker.py delete mode 100644 atest/tests/ProxyableRemote.py delete mode 100644 atest/tests/Z_LAST__special_failures.txt delete mode 100644 atest/tests/argument_counts.txt delete mode 100644 atest/tests/argument_types.txt delete mode 100644 atest/tests/basic_communication.txt delete mode 100644 atest/tests/failures.txt delete mode 100644 atest/tests/finding_keywords.txt delete mode 100644 atest/tests/invalid_argument_counts.txt delete mode 100644 atest/tests/kwargs.txt delete mode 100644 atest/tests/logging.txt delete mode 100644 atest/tests/resource.txt delete mode 100644 atest/tests/return_values.txt delete mode 100644 atest/tests/traceback.txt delete mode 100644 atest/tests/variables.py delete mode 100644 examples/AnnotationLibrary/README.txt delete mode 100644 examples/AnnotationLibrary/pom.xml delete mode 100644 examples/AnnotationLibrary/src/main/java/com/example/MyRemoteLibrary.java delete mode 100644 examples/AnnotationLibrary/src/main/java/com/example/keywords/QueueManager.java delete mode 100644 examples/AnnotationLibrary/src/main/resources/com/example/__intro__.txt delete mode 100644 examples/AnnotationLibrary/src/test/java/com/example/MyRemoteLibraryLauncher.java delete mode 100644 examples/AnnotationLibrary/src/test/java/robotframework/LibraryDocumentationGeneratorTest.java delete mode 100644 examples/AnnotationLibrary/src/test/resources/robotframework/maven.properties delete mode 100644 examples/AnnotationLibrary/src/test/resources/robotframework/tests/MyRemoteLibrary.txt delete mode 100644 examples/AnnotationLibrary/src/test/resources/robotframework/tests/Resources/common.txt delete mode 100644 examples/AnnotationLibrary/src/test/resources/robotframework/tests/TypeLibrary.py create mode 100644 jrobot-features/pom.xml create mode 100644 jrobot-features/src/main/resources/features.xml create mode 100755 jrobot-karaf/pom.xml create mode 100644 jrobot-karaf/src/test/robotframework/acceptance/010_feature_tests.robot create mode 100644 jrobot-karaf/src/test/robotframework/karaf_keywords.robot create mode 100644 jrobot-remote-server/pom.xml rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/RemoteServer.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/RemoteServerImpl.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/cli/CommandLineHelper.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/context/RemoteServerContext.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/javalib/KeywordOverload.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/javalib/OverloadableKeyword.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractor.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactory.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/javalib/SingleClassLibrary.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactory.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibrary.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/library/RemoteLibrary.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/library/RemoteLibraryFactory.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/library/StaticApiRemoteLibrary.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/logging/Jetty2Log4J.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/servlet/IllegalPathException.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/servlet/RemoteServerRequestProcessorFactoryFactory.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/xmlrpc/ByteArrayToStringParser.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/xmlrpc/IterableSerializer.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/xmlrpc/MapSerializer.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/xmlrpc/ReflectiveHandlerMapping.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/xmlrpc/StringSerializer.java (100%) rename {src => jrobot-remote-server/src}/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java (100%) create mode 100644 jrobot-remote-server/src/main/resources/OSGI-INF/blueprint/jrobot-remote-server.xml rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/RemoteLibraryClient.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/RemoteServerImplTest.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/cli/CommandLineHelpertTest.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/javalib/OverloadableKeywordTest.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractorTest.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactoryTest.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/javalib/SingleClassLibraryTest.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactoryTest.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibraryTest.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/library/StaticApiRemoteLibraryTest.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/servlet/AlternativeContainerTest.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/servlet/RemoteServerServletTest.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/testlibraries/ConflictingOverloadVariableArguments.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/testlibraries/DuplicateKeywords.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargs.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargsList.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordNoKwargs.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/testlibraries/DynamicUsingLists.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/testlibraries/OverloadedMethods.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/testlibraries/StaticOne.java (100%) rename {src => jrobot-remote-server/src}/test/java/org/robotframework/remoteserver/testlibraries/StaticTwo.java (100%) create mode 100644 jrobot-test-library/pom.xml create mode 100644 jrobot-test-library/src/main/java/org/robotframework/test/TestLibrary.java create mode 100644 jrobot-test-library/src/main/resources/OSGI-INF/blueprint/jrobot-test-library.xml delete mode 100644 src/main/resources/OSGI-INF/blueprint/remote-server.xml diff --git a/.gitignore b/.gitignore index 34876ea..b9d4684 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,7 @@ test-output .project atest/results *.pyc -*.class .pydevproject /.idea/ /target/ +*.iml diff --git a/atest/libs/pom.xml b/atest/libs/pom.xml deleted file mode 100644 index 098b92b..0000000 --- a/atest/libs/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - 4.0.0 - org.robotframework - examplelib - 1.0 - jar - - UTF-8 - - - - org.robotframework - javalib-core - 1.2 - compile - - - - examplelib - - - maven-assembly-plugin - - - jar-with-dependencies - - - - - make-my-jar-with-dependencies - package - - single - - - - - - - diff --git a/atest/libs/src/main/java/org/robotframework/examplelib/FullDynamic.java b/atest/libs/src/main/java/org/robotframework/examplelib/FullDynamic.java deleted file mode 100644 index 17198bc..0000000 --- a/atest/libs/src/main/java/org/robotframework/examplelib/FullDynamic.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.robotframework.examplelib; - -import org.robotframework.javalib.library.AnnotationLibrary; - -public class FullDynamic { - public FullDynamic() { - lib = new AnnotationLibrary(); - lib.addKeywordPattern("org/robotframework/examplelib/impl/**.class"); - } - - public String[] getKeywordNames() { - return lib.getKeywordNames(); - } - - /* - * AnnotationLibrary re-throws all exceptions as RuntimeExceptions. Unwrap - * it to obtain the original exception. - */ - public Object runKeyword(String keywordName, Object[] args) throws Throwable { - try { - return lib.runKeyword(keywordName, args); - } catch (RuntimeException e) { - throw e.getCause(); - } - } - - public String[] getKeywordArguments(String keywordName) { - return lib.getKeywordArguments(keywordName); - } - - public String getKeywordDocumentation(String keywordName) { - if (keywordName.equals("__intro__")) - return "This is an example dyanmic API library."; - else - return lib.getKeywordDocumentation(keywordName); - } - - private AnnotationLibrary lib; - -} diff --git a/atest/libs/src/main/java/org/robotframework/examplelib/MinDynamic.java b/atest/libs/src/main/java/org/robotframework/examplelib/MinDynamic.java deleted file mode 100644 index 3c6a745..0000000 --- a/atest/libs/src/main/java/org/robotframework/examplelib/MinDynamic.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.robotframework.examplelib; - -public class MinDynamic{ - - private final FullDynamic lib = new FullDynamic(); - - public String[] getKeywordNames() { - return lib.getKeywordNames(); - } - - public Object runKeyword(String keywordName, Object[] args) throws Throwable { - return lib.runKeyword(keywordName, args); - } -} \ No newline at end of file diff --git a/atest/libs/src/main/java/org/robotframework/examplelib/MinDynamicKwargs.java b/atest/libs/src/main/java/org/robotframework/examplelib/MinDynamicKwargs.java deleted file mode 100644 index e71cb32..0000000 --- a/atest/libs/src/main/java/org/robotframework/examplelib/MinDynamicKwargs.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.robotframework.examplelib; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -public class MinDynamicKwargs { - - public String[] getKeywordNames() { - return new String[] { "getKwargValue" }; - } - - public Object runKeyword(String name, List args, Map kwargs) { - if (name.equals("getKwargValue")) { - assert(args.size() == 1); - return getKwargValue((String) args.get(0), kwargs); - } else { - throw new RuntimeException(); - } - } - - public List getKeywordArguments(String name) { - if (name.equals("getKwargValue")) { - return Arrays.asList(new String[] {"key", "**kwargs"}); - } - return null; - } - - private Object getKwargValue(String key, Map kwargs) { - return kwargs.get(key); - } - -} diff --git a/atest/libs/src/main/java/org/robotframework/examplelib/Static.java b/atest/libs/src/main/java/org/robotframework/examplelib/Static.java deleted file mode 100644 index e8b7898..0000000 --- a/atest/libs/src/main/java/org/robotframework/examplelib/Static.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.robotframework.examplelib; - -import org.robotframework.examplelib.impl.Keywords; - -public class Static extends Keywords { - public void inClass() { - } -} diff --git a/atest/libs/src/main/java/org/robotframework/examplelib/impl/Keywords.java b/atest/libs/src/main/java/org/robotframework/examplelib/impl/Keywords.java deleted file mode 100644 index b8015cc..0000000 --- a/atest/libs/src/main/java/org/robotframework/examplelib/impl/Keywords.java +++ /dev/null @@ -1,858 +0,0 @@ -package org.robotframework.examplelib.impl; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.PriorityQueue; -import java.util.Queue; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.concurrent.LinkedBlockingQueue; - -import org.robotframework.javalib.annotation.ArgumentNames; -import org.robotframework.javalib.annotation.RobotKeyword; -import org.robotframework.javalib.annotation.RobotKeywordOverload; -import org.robotframework.javalib.annotation.RobotKeywords; - -/* - * Various type declarations are used on purpose to provide more coverage - */ -@RobotKeywords -public class Keywords { - - private final String unicode = "Hyv\u00E4\u00E4 y\u00F6t\u00E4. " + "\u0421\u043F\u0430\u0441\u0438\u0431\u043E!"; - - // Common keywords - - @RobotKeyword("Documentation") - public void hasDocumentation() { - } - - @ArgumentNames({ "name" }) - public void hasArgumentDocumentation(String name) { - } - - @RobotKeyword - public String getServerLanguage() { - return "Java"; - } - - @RobotKeyword("This keyword passes.\n" + "\n" - + "See `Failing`, `Logging`, and `Returning` for other basic keywords.") - public void passing() { - } - - @RobotKeyword("This keyword fails with provided `message`") - @ArgumentNames({ "message" }) - public static void failing(String message) { - throw new AssertionError(message); - } - - @RobotKeyword("This keywords logs given `message` with given `level`\n" + "\n" + "Example:" - + "| Logging | Hello, world! | |" + "| Logging | Warning!!! | WARN |") - @ArgumentNames({ "message", "level=INFO" }) - public void logging(String message, String... args) { - String level = args.length > 0 ? args[0] : "INFO"; - System.out.println(String.format("*%s* %s", level, message)); - } - - @RobotKeyword("This keyword returns a string 'returned string'.") - public String returning() { - return "returned string"; - } - - // Logging - - @RobotKeyword - public void oneMessageWithoutLevel() { - System.out.println("Hello, world!"); - } - - @RobotKeyword - public void multipleMessagesWithDifferentLevels() { - System.out.println("Info message"); - System.out.println("*DEBUG* Debug message"); - System.out.println("*INFO* Second info"); - System.out.println("this time with two lines"); - System.out.println("*INFO* Third info"); - System.out.println("*TRACE* This is ignored"); - System.out.println("*WARN* Warning"); - } - - @RobotKeyword - public void logUnicode() { - System.out.println(unicode); - } - - @RobotKeyword - public static void loggingAndFailing() { - System.out.println("*INFO* This keyword will fail!"); - System.out.println("*WARN* Run for your lives!!"); - throw new RuntimeException("Too slow"); - } - - @RobotKeyword - public String loggingAndReturning() { - System.out.println("Logged message"); - return "Returned value"; - } - - @RobotKeyword - public void logControlChar() { - System.out.println("\u0123"); - } - - @RobotKeyword - @ArgumentNames({ "*varargs" }) - public void loggingBothToStdoutAndStderr(String... messages) { - for (int i = 0; i < messages.length; i++) { - if (i % 2 == 0) { - System.out.print(messages[i]); - } else { - System.err.print(messages[i]); - } - } - } - - // Failures - - @RobotKeyword - public static void baseException() throws Exception { - throw new Exception("My message"); - } - - @RobotKeyword - public static void exceptionWithoutMessage() throws Exception { - throw new Exception(); - } - - @RobotKeyword - public static void assertionError() { - throw new AssertionError("Failure message"); - } - - @RobotKeyword - public void runtimeError() { - throw new RuntimeException("Error message"); - } - - @RobotKeyword - public static void indexError() { - System.out.println(new String[] {}[0]); - } - - @RobotKeyword - public static void zeroDivision() { - System.out.println(1 / 0); - } - - @RobotKeyword - public static void customException() throws MyException { - throw new MyException("My message"); - } - - @RobotKeyword - @ArgumentNames({ "subClass" }) - public static void suppressedNameException(boolean subClass) throws SuppressedNameException { - if (subClass) { - throw new SpecificSuppressedNameException(); - } - throw new SuppressedNameException(); - } - - @RobotKeyword - @ArgumentNames({ "rounds=10" }) - public static void failureDeeper(Object... args) { - Integer rounds = args.length > 0 ? (Integer) args[0] : 10; - if (rounds == 1) - throw new RuntimeException("Finally failing"); - failureDeeper(rounds - 1); - } - - @RobotKeyword - public void errorMessageWithNonAsciiUnicode() { - throw new RuntimeException(unicode); - } - - @RobotKeyword - @ArgumentNames({ "message" }) - static public void notSpecial(String message) { - throw new SpecialException(message, false, false); - } - - @RobotKeyword - @ArgumentNames({ "message" }) - static public void continuable(String message) { - throw new SpecialException(message, true, false); - } - - @RobotKeyword - @ArgumentNames({ "message" }) - static public void fatal(String message) { - throw new SpecialException(message, false, true); - } - - // Arguments counts - - @RobotKeyword - public String noArguments() { - return "no arguments"; - } - - @RobotKeyword - @ArgumentNames("arg") - public Object oneArgument(Object arg) { - System.out.print(String.format("%s", arg)); // - return arg; - } - - @RobotKeyword - @ArgumentNames({ "arg1", "arg2" }) - public Object twoArguments(Object arg1, Object arg2) { - System.out.print(String.format("%s %s", arg1, arg2)); // - return String.format("%s %s", arg1, arg2); - } - - @RobotKeyword - @ArgumentNames({ "arg1", "arg2", "arg3", "arg4", "arg5", "arg6", "arg7" }) - public Object sevenArguments(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, - Object arg7) { - return String.format("%s %s %s %s %s %s %s", arg1, arg2, arg3, arg4, arg5, arg6, arg7); - } - - @RobotKeyword - @ArgumentNames({ "arg1", "arg2='2'", "arg3=3" }) - public Object argumentsWithDefaultValues(Object arg1) { - return argumentsWithDefaultValues(arg1, "2"); - } - - @RobotKeywordOverload - public Object argumentsWithDefaultValues(Object arg1, Object arg2) { - return argumentsWithDefaultValues(arg1, arg2, "3"); - } - - @RobotKeywordOverload - public Object argumentsWithDefaultValues(Object arg1, Object arg2, Object arg3) { - return String.format("%s %s %s", arg1, arg2, arg3); - } - - @RobotKeyword - @ArgumentNames("*args") - public String variableNumberOfArguments(Object... args) { - StringBuilder sb = new StringBuilder(); - boolean first = true; - for (Object arg : args) { - if (!first) - sb.append(" "); - first = false; - sb.append(arg.toString()); - } - return sb.toString(); - } - - @RobotKeyword - @ArgumentNames({ "req", "default='world", "*varargs" }) - public String requiredDefaultsAndVarargs(Object req, Object... varargs) { - Object deefault = varargs.length > 0 ? varargs[0] : "world"; - StringBuilder sb = new StringBuilder(); - sb.append(String.format("%s %s", req, deefault)); - for (int i = 1; i < varargs.length; i++) - sb.append(" " + varargs[i].toString()); - return sb.toString(); - } - - // Argument types - - @RobotKeyword - @ArgumentNames("arg") - public void stringAsArgument(Object arg) { - shouldBeEqual(returnString(), (String) arg); - } - - @RobotKeyword - @ArgumentNames("arg") - public void unicodeStringAsArgument(String arg) { - shouldBeEqual(arg, unicode); - } - - @RobotKeyword - @ArgumentNames("arg") - public void emptyStringAsArgument(Object arg) { - shouldBeEqual(arg, ""); - } - - @RobotKeyword - @ArgumentNames("arg") - public void controlCharAsArgument(String arg) { - shouldBeEqual(arg, "\1"); - } - - @RobotKeyword - @ArgumentNames("arg") - public void integerAsArgument(Object arg) { - shouldBeEqual(arg, returnInteger()); - } - - @RobotKeyword - @ArgumentNames("arg") - public int intAsArgument(int arg) { - return arg; - } - - @RobotKeyword - @ArgumentNames("arg") - public void negativeIntegerAsArgument(Integer arg) { - shouldBeEqual(arg, returnNegativeInteger()); - } - - @RobotKeyword - @ArgumentNames("arg") - public void doubleAsArgument(double arg) { - shouldBeEqual(arg, returnDouble()); - } - - @RobotKeyword - @ArgumentNames("arg") - public void doubleObjectAsArgument(Double arg) { - shouldBeEqual(arg, returnDoubleObject()); - } - - @RobotKeyword - @ArgumentNames("arg") - public void zeroAsArgument(Object arg) { - shouldBeEqual(arg, 0); - } - - @RobotKeyword - @ArgumentNames("arg") - public void booleanTrueAsArgument(Object arg) { - shouldBeEqual(arg, true); - } - - @RobotKeyword - @ArgumentNames("arg") - public void booleanFalseAsArgument(boolean arg) { - shouldBeEqual(arg, false); - } - - @RobotKeyword - @ArgumentNames("arg") - public void booleanObjectAsArgument(Boolean arg) { - shouldBeEqual(arg, false); - } - - @RobotKeyword - @ArgumentNames("arg") - public void nullAsArgument(Object arg) { - shouldBeEqual(arg, ""); - } - - @RobotKeyword - @ArgumentNames("arg") - public void objectAsArgument(Object arg) { - shouldBeEqual(arg, ""); - } - - @RobotKeyword - @ArgumentNames("arg") - public void listAsArgument(List arg) { - shouldBeEqual(arg, returnList()); - } - - @RobotKeyword - @ArgumentNames("arg") - public void emptyListAsArgument(List arg) { - shouldBeEqual(arg, new ArrayList()); - } - - @RobotKeyword - @ArgumentNames("arg") - public void listContainingNoneAsArgument(List arg) { - shouldBeEqual(arg, Arrays.asList("")); - } - - @RobotKeyword - @ArgumentNames("arg") - public void listContainingObjectsAsArgument(List arg) { - shouldBeEqual(arg, Arrays.asList("", "")); - } - - @RobotKeyword - @ArgumentNames("arg") - public void nestedListAsArgument(List arg) { - System.out.println(arg.getClass().getName() + arg); - List exp = new ArrayList(); - exp.add(Arrays.asList(true, false)); - List inner = new ArrayList(); - inner.add(Arrays.asList(1, "", "", new HashMap())); - exp.add(inner); - // exp.add(4); - shouldBeEqual(arg, exp); - } - - @RobotKeyword - @ArgumentNames({ "arg" }) - public void mapAsArgument(Map arg) { - shouldBeEqual(arg, returnMap()); - } - - @RobotKeyword - @ArgumentNames({ "arg" }) - public void emptyMapAsArgument(Map arg) { - shouldBeEqual(arg, new HashMap()); - } - - @RobotKeyword - @ArgumentNames({ "arg" }) - public void mapWithNonStringKeysAsArgument(Map arg) { - Map exp = new HashMap(); - exp.put("1", 2); - exp.put("", true); - shouldBeEqual(arg, exp); - } - - @RobotKeyword - @ArgumentNames({ "arg" }) - public void mapContainingNoneAsArgument(Map arg) { - Map exp = new HashMap(); - exp.put("As value", ""); - exp.put("", "As key"); - shouldBeEqual(arg, exp); - } - - @RobotKeyword - @ArgumentNames({ "arg" }) - public void mapContainingObjectsAsArgument(Map arg) { - Map exp = new HashMap(); - exp.put("As value", ""); - exp.put("", "As key"); - shouldBeEqual(arg, exp); - } - - @RobotKeyword - @ArgumentNames({ "arg" }) - public void nestedMapAsArgument(Object arg) { - Map exp = new HashMap(); - Map m1 = new HashMap(); - m1.put("", false); - exp.put("1", m1); - Map m2 = new HashMap(); - m2.put("n", ""); - m1 = new HashMap(); - m1.put("A", m2); - m2 = new HashMap(); - m2.put("o", ""); - m2.put("e", new HashMap()); - m1.put("B", m2); - exp.put("2", m1); - shouldBeEqual(arg, exp); - } - - @RobotKeyword - @ArgumentNames({ "nums", "sum" }) - public void arrayAsArgument(Object[] nums, Integer sum) { - Integer asum = 0; - for (Object num : nums) - asum += (Integer) num; - shouldBeEqual(sum, asum); - } - - // Return values - - @RobotKeyword - public String returnString() { - return "Hello, world!"; - } - - @RobotKeyword - public String returnUnicodeString() { - return unicode; - } - - @RobotKeyword - public String returnEmptyString() { - return ""; - } - - @RobotKeyword - public int returnInt() { - return 12; - } - - @RobotKeyword - public Integer returnInteger() { - return 42; - } - - @RobotKeyword - public Integer returnNegativeInteger() { - return -1; - } - - @RobotKeyword - public float returnFloat() { - return 3.14f; - } - - @RobotKeyword - public float returnNegativeFloat() { - return -0.5f; - } - - @RobotKeyword - public Float returnFloatObject() { - return 86.02f; - } - - @RobotKeyword - public int returnZero() { - return 0; - } - - @RobotKeyword - public boolean returnBooleanTrue() { - return true; - } - - @RobotKeyword - public boolean returnBooleanFalse() { - return false; - } - - @RobotKeyword - public Boolean returnBooleanObject() { - return false; - } - - @RobotKeyword - public void returnNothing() { - } - - @RobotKeyword - public Object returnNull() { - return null; - } - - @RobotKeyword - public Object returnObject() { - return new MyObject(""); - } - - @RobotKeyword - public List returnList() { - return Arrays.asList("One", -2, false); - } - - @RobotKeyword - public List returnEmptyList() { - return new ArrayList(); - } - - @RobotKeyword - public List returnListContainingNull() { - return Arrays.asList(new Object[] { null }); - } - - @RobotKeyword - public List returnListContainingObjects() { - return Arrays.asList(new MyObject("1"), new MyObject("2")); - } - - @RobotKeyword - public List returnNestedList() { - List outer = new ArrayList(); - List inner = Arrays.asList(new Object[] { true, false }); - outer.add(inner); - List inner2 = new ArrayList(Arrays.asList(new Object[] { 1, null, new MyObject(""), - new HashMap() })); - inner = new ArrayList(); - inner.add(inner2); - outer.add(inner); - return outer; - } - - @RobotKeyword - public Map returnMap() { - Map dic = new HashMap(); - dic.put("one", 1); - dic.put("spam", "eggs"); - return dic; - } - - @RobotKeyword - public Map returnEmptyMap() { - return new HashMap(); - } - - @RobotKeyword - public Map returnMapWithNonStringKeys() { - Map dic = new HashMap(); - dic.put(1, 2); - dic.put(null, true); - return dic; - } - - @RobotKeyword - public Map returnMapContainingNull() { - Map dic = new HashMap(); - dic.put("As value", null); - dic.put(null, "As key"); - return dic; - } - - @RobotKeyword - public Map returnMapContainingObjects() { - Map dic = new HashMap(); - dic.put("As value", new MyObject("1")); - dic.put(new MyObject("2"), "As key"); - return dic; - } - - @RobotKeyword - public Map returnNestedMap() { - Map ret = new HashMap(); - Map inner = new HashMap(); - inner.put(null, false); - ret.put(1, inner); - inner = new HashMap(); - Map inner2 = new HashMap(); - inner2.put("n", null); - inner.put("A", inner2); - inner2 = new HashMap(); - inner2.put("o", new MyObject("")); - inner2.put("e", new HashMap()); - inner.put("B", inner2); - ret.put(2, inner); - return ret; - } - - @RobotKeyword - public String returnControlChar() { - return "\1"; - } - - @RobotKeyword - public char returnChar() { - return 'R'; - } - - @RobotKeyword - public Object[] returnArrayContainingStrings() { - return new Object[] { "spam", "eggs" }; - } - - @RobotKeyword - public Double returnDouble() { - return 9.34; - } - - @RobotKeyword - public Double returnDoubleObject() { - return 4.2; - } - - @RobotKeyword - public short returnShort() { - return -88; - } - - @RobotKeyword - public Short returnShortObject() { - return 9; - } - - @RobotKeyword - public byte returnByte() { - return 67; - } - - @RobotKeyword - public Byte returnByteObject() { - return 127; - } - - @RobotKeyword - public char[] returnArrayContainingChars() { - return new char[] { 79, 75 }; - } - - @RobotKeyword - public MyObject[] returnArrayOfObjects() { - return new MyObject[] { new MyObject("1"), new MyObject("2") }; - } - - @RobotKeyword - public Byte[] returnArrayOfByte() { - return new Byte[] { (byte) -57, (byte) 21 }; - } - - @RobotKeyword - public byte[] returnPrimitiveArrayOfByte() { - return new byte[] { (byte) -4, (byte) 8 }; - } - - @RobotKeyword - public Short[] returnArrayOfShort() { - return new Short[] { 34, -98 }; - } - - @RobotKeyword - public short[] returnPrimitiveArrayOfShort() { - return new short[] { 287, -86 }; - } - - @RobotKeyword - public Object[] returnArrayOfInteger() { - return new Integer[] { 3, -5 }; - } - - @RobotKeyword - public int[] returnPrimitiveArrayOfInt() { - return new int[] { -338, 897 }; - } - - @RobotKeyword - public Long[] returnArrayOfLong() { - return new Long[] { -9223372036854775800L, 9223372036854775805L }; - } - - @RobotKeyword - public long[] returnPrimitiveArrayOfLong() { - return new long[] { 8723372036854774829L, -9123372036854775382L }; - } - - @RobotKeyword - public Float[] returnArrayOfFloat() { - return new Float[] { 8.2f, -7.38f }; - } - - @RobotKeyword - public float[] returnPrimitiveArrayOfFloat() { - return new float[] { -7.774f, 562.1f }; - } - - @RobotKeyword - public Double[] returnArrayOfDouble() { - return new Double[] { 101.6, 45.67 }; - } - - @RobotKeyword - public double[] returnPrimitiveArrayOfDouble() { - return new double[] { -37.11, 90.4 }; - } - - @RobotKeyword - public Boolean[] returnArrayOfBoolean() { - return new Boolean[] { false, true }; - } - - @RobotKeyword - public boolean[] returnPrimitiveArrayOfBoolean() { - return new boolean[] { true, false }; - } - - @RobotKeyword - public Date returnDate() { - return new Date(0); - } - - @RobotKeyword - public Queue returnQueue() { - Queue queue = new LinkedBlockingQueue(); - queue.add("first"); - queue.add(new MyObject("second")); - return queue; - } - - @RobotKeyword - public Queue returnEmptyQueue() { - return new PriorityQueue(); - } - - @RobotKeyword - public Object returnTreeSet() { - SortedSet s = new TreeSet(); - s.add(5); - s.add(2); - return s; - } - - @RobotKeyword - public static String staticMethod() { - return "eggs"; - } - - private void privateMethod() { - } - - private void shouldBeEqual(Object a, Object b) { - shouldBeEqual(a, b, ""); - } - - /* - * The equals method of any class is too precise in most classes to use - * directly, especially on PyObject's subclasses. This method considers - * equality to mean all Lists and array have the same elements in the same - * order. For maps, order is ignored and keys are assumed to be strings. - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - private void shouldBeEqual(Object a, Object b, String where) { - if (a == null && b == null) - return; - else if (a == null || b == null) - throw new AssertionError(String.format("%sone is null other is not %s %s", where, a, b)); - else if (a.equals(b) || b.equals(a)) - return; - else if (a instanceof List || b instanceof List) { - if (!(a instanceof List && b instanceof List)) - throw new AssertionError(String.format("%sOne is List other is not: %s %s", where, a.getClass(), - b.getClass())); - List la = new ArrayList((List) a); - List lb = new ArrayList((List) b); - if (la.size() != lb.size()) - throw new AssertionError(String.format("%ssize of a: %s != size of b: %s", where, la.size(), lb.size())); - for (int i = 0; i < la.size(); i++) - shouldBeEqual(la.get(i), lb.get(i), String.format("%slist(%d)>", where, i)); - } else if (a instanceof Map || b instanceof Map) { - if (!(a instanceof Map && b instanceof Map)) - throw new AssertionError(String.format("%sOne is Map other is not: %s %s", where, a.getClass(), - b.getClass())); - Map ma = (Map) a; - Map mb = (Map) b; - int sa = ma.entrySet().size(); - int sb = mb.entrySet().size(); - if (sa != sb) - throw new AssertionError(String.format("%ssize of a: %s != size of b: %s", where, sa, sb)); - Set seta = ma.entrySet(); - Set setb = mb.entrySet(); - for (Entry entry : seta) { - String key = (String) entry.getKey(); - if (!mb.keySet().contains(key)) - throw new AssertionError(String.format("%sb missing key %s", where, key)); - shouldBeEqual(entry.getValue(), mb.get(key), String.format("%skey(%s) of a>", where, key)); - } - for (Entry entry : setb) { - String key = (String) entry.getKey(); - if (!ma.keySet().contains(key)) - throw new AssertionError(String.format("%sa missing key %s", where, key)); - shouldBeEqual(entry.getValue(), ma.get(key), String.format("%skey(%s) of a>", where, key)); - } - } else if (a instanceof Object[] || b instanceof Object[]) { - if (!(a instanceof Object[] && b instanceof Object[])) - throw new AssertionError(String.format("%sOne is an array and the other is not: %s %s", where, - a.getClass(), b.getClass())); - Object[] aa = (Object[]) a; - Object[] ab = (Object[]) b; - if (aa.length != ab.length) - throw new AssertionError(String.format("%ssize of a: %s != size of b: %s", where, aa.length, ab.length)); - for (int i = 0; i < aa.length; i++) - shouldBeEqual(aa, ab, String.format("%sarray(%d)>", where, i)); - } else - throw new AssertionError(String.format("%sNot equal: %s:%s %s:%s", where, a.getClass(), a, b.getClass(), b)); - } -} diff --git a/atest/libs/src/main/java/org/robotframework/examplelib/impl/MyException.java b/atest/libs/src/main/java/org/robotframework/examplelib/impl/MyException.java deleted file mode 100644 index 8f46ed8..0000000 --- a/atest/libs/src/main/java/org/robotframework/examplelib/impl/MyException.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.robotframework.examplelib.impl; - -@SuppressWarnings("serial") -public class MyException extends Exception { - - public MyException(String string) { - super(string); - } -} diff --git a/atest/libs/src/main/java/org/robotframework/examplelib/impl/MyObject.java b/atest/libs/src/main/java/org/robotframework/examplelib/impl/MyObject.java deleted file mode 100644 index 19ac867..0000000 --- a/atest/libs/src/main/java/org/robotframework/examplelib/impl/MyObject.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.robotframework.examplelib.impl; - -public class MyObject { - - MyObject(String id) { - this.id = id; - } - - public String toString() { - return String.format("", id); - } - - private String id; -} diff --git a/atest/libs/src/main/java/org/robotframework/examplelib/impl/SpecialException.java b/atest/libs/src/main/java/org/robotframework/examplelib/impl/SpecialException.java deleted file mode 100644 index e8fcd82..0000000 --- a/atest/libs/src/main/java/org/robotframework/examplelib/impl/SpecialException.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.robotframework.examplelib.impl; - -@SuppressWarnings("serial") -public class SpecialException extends RuntimeException { - - public boolean ROBOT_CONTINUE_ON_FAILURE = false; - public boolean ROBOT_EXIT_ON_FAILURE = false; - - SpecialException(String message, boolean continuable, boolean fatal) { - super(message); - ROBOT_CONTINUE_ON_FAILURE = continuable; - ROBOT_EXIT_ON_FAILURE = fatal; - } - -} diff --git a/atest/libs/src/main/java/org/robotframework/examplelib/impl/SpecificSuppressedNameException.java b/atest/libs/src/main/java/org/robotframework/examplelib/impl/SpecificSuppressedNameException.java deleted file mode 100644 index 2927540..0000000 --- a/atest/libs/src/main/java/org/robotframework/examplelib/impl/SpecificSuppressedNameException.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.robotframework.examplelib.impl; - -@SuppressWarnings("serial") -public class SpecificSuppressedNameException extends SuppressedNameException { - -} diff --git a/atest/libs/src/main/java/org/robotframework/examplelib/impl/SuppressedNameException.java b/atest/libs/src/main/java/org/robotframework/examplelib/impl/SuppressedNameException.java deleted file mode 100644 index b4b5643..0000000 --- a/atest/libs/src/main/java/org/robotframework/examplelib/impl/SuppressedNameException.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.robotframework.examplelib.impl; - -@SuppressWarnings("serial") -public class SuppressedNameException extends Exception { - - public static boolean ROBOT_SUPPRESS_NAME = true; - - public SuppressedNameException() { - super("name suppressed"); - } -} diff --git a/atest/run.py b/atest/run.py deleted file mode 100644 index 55c88ce..0000000 --- a/atest/run.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python - -"""Script for running the remote server tests using different interpreters. - -usage: run.py [runner] [libraries] [[options] datasources] - -`runner` is the interpreter to use for running tests, defaulting to -python. `libraries` is a comma-delimited list of libraries in the form -class:port. - -By default the test libraries will be a AnnotationLibrary, ClassPath library, -and a static API library. By default all tests under `tests` directory are -executed. This can be changed by giving data sources and options explicitly. -""" - -import sys -import subprocess -from os.path import abspath, dirname, exists, join -from os import mkdir -from shutil import rmtree - -import robot - -import servercontroller -import statuschecker - -BASE = dirname(abspath(__file__)) -RESULTS = join(BASE, 'results') -if exists(RESULTS): - rmtree(RESULTS) -mkdir(RESULTS) - -clargs = sys.argv[1:] -if '-h' in clargs or '--help' in clargs: - sys.exit(__doc__) - -interpreter = clargs.pop(0) if clargs else 'python' -libraries = \ - 'org.robotframework.examplelib.FullDynamic:/FullDynamic,' + \ - 'org.robotframework.examplelib.MinDynamic:/MinDynamic,' + \ - 'org.robotframework.examplelib.Static:/Static,' + \ - 'org.robotframework.examplelib.MinDynamicKwargs:/MinDynamicKwargs' -if clargs: - libraries = clargs.pop(0) - -servercontroller.start(libraries) -libraries = [x.strip() for x in libraries.split(',')] -outputs = [] - -for entry in libraries: - name, _, path = entry.partition(':') - name = name.rsplit('.', 1)[1] - OUTPUT = join(RESULTS, 'output-' + name + '.xml') - outputs.append(OUTPUT) - - args = [interpreter, '-m', 'robot.run', '--name', name, '--variable', 'PATH:' + path, - '--output', OUTPUT, '--log', 'NONE', '--report', 'NONE'] - if 'MinDynamic' in name: - args.extend(['--exclude', 'argsknown']) - if 'kwargs' in name.lower(): - args.extend(['--include', 'kwargs']) - else: - args.extend(['--exclude', 'kwargs']) - args.extend(['--loglevel','DEBUG']) - args.extend([join(BASE, 'tests')]) - print 'Running tests with command:\n%s' % ' '.join(args) - subprocess.call(args) - - print - statuschecker.process_output(OUTPUT) - -servercontroller.stop(8270, "/Static") -rc = robot.rebot(*outputs, outputdir=RESULTS) -if rc == 0: - print 'All tests passed' -else: - print '%d test%s failed' % (rc, 's' if rc != 1 else '') diff --git a/atest/servercontroller.py b/atest/servercontroller.py deleted file mode 100644 index 8e38930..0000000 --- a/atest/servercontroller.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python - -"""Module/script for controlling remote server used in tests. - -When used as module, provides `start`, `test`, and `stop` methods. -The server's stdin and stdout streams are redirected to results/server.txt - -Usage: servercontroller.py start|stop|test [args] - - start args: [libraries=default_libraries] formatted like class:port, ... - test args: [port=8270] [attempts=1] - stop args: [port=8270] - - default_libraries are a AnnotationLibrary, ClassPathLibrary, and static API - library on ports 8270-8272. - -Note: Starting from CLI leaves the terminal in a messed up state. -""" - -from __future__ import with_statement -import xmlrpclib -import time -import subprocess -import socket -from os.path import abspath, dirname, exists, join -import os -import sys -import glob - - -BASE = dirname(abspath(__file__)) - - -def start(libraries= - 'org.robotframework.examplelib.FullDynamic:/FullDynamic,' + \ - 'org.robotframework.examplelib.MinDynamic:/MinDynamic,' + \ - 'org.robotframework.examplelib.Static:/Static' ): - if not os.path.exists(os.path.join(BASE, 'libs', 'target', 'examplelib-jar-with-dependencies.jar')): - cmd = 'mvn -f "%s" clean package' % os.path.join(BASE, 'libs', 'pom.xml') - print 'Building the test libraries with command:\n%s' % cmd - subprocess.call(cmd, shell=True) - files = glob.glob(os.path.join(dirname(BASE), 'target') + os.sep + '*jar-with-dependencies.jar') - if not files: - raise Exception('Build jrobotremoteserver including the standalone jar first') - rs_path = os.path.join(dirname(BASE), 'target', files[0]) - tl_path = os.path.join(BASE, 'libs', 'target', 'examplelib-jar-with-dependencies.jar') - os.environ['CLASSPATH'] = rs_path + os.pathsep + tl_path - print 'CLASSPATH: %s' % os.environ['CLASSPATH'] - results = _get_result_directory() - port = "8270" - args = ['java', 'org.robotframework.remoteserver.RemoteServerImpl', '--port', port] - libraries = [x.strip() for x in libraries.split(',')] - paths = [x.partition(':')[2] for x in libraries] - for lib in libraries: - args.extend(['--library', lib]) - print 'adding library %s on path %s' % (lib.split(':')[0], lib.split(':')[1]) - with open(join(results, 'server.txt'), 'w') as output: - server = subprocess.Popen(args, - stdout=output, stderr=subprocess.STDOUT, - env=_get_environ()) - for path in paths: - if not test(port, path, attempts=15): - server.terminate() - raise RuntimeError('Starting remote server failed') - -def _get_result_directory(): - path = join(BASE, 'results') - if not exists(path): - os.mkdir(path) - return path - -def _get_environ(): - environ = os.environ.copy() - src = join(BASE, '..', 'src') - environ.update(PYTHONPATH=src, JYTHONPATH=src, IRONPYTHONPATH=src) - return environ - - -def test(port, path, attempts=1): - url = 'http://localhost:%s%s' % (port, path) - for i in range(int(attempts)): - if i > 0: - time.sleep(1) - try: - ret = xmlrpclib.ServerProxy(url).run_keyword('get_server_language', []) - except socket.error, (errno, errmsg): - pass - except xmlrpclib.Error, err: - errmsg = err.faultString - break - else: - print "Remote server running on port %s, path %s" % (port, path) - return True - print "Failed to connect to remote server on port %s path %s: %s" % (port, path, errmsg) - return False - - -def stop(port=8270, path="/"): - if test(port, path): - server = xmlrpclib.ServerProxy('http://localhost:%s%s' % (port, path)) - server.stop_remote_server() - print "Remote server on port %s path %s stopped" % (port, path) - - -if __name__ == '__main__': - if len(sys.argv) == 1 or '-h' in sys.argv or '--help' in sys.argv: - sys.exit(__doc__) - mode = sys.argv[1] - args = sys.argv[2:] - try: - {'start': start, 'stop': stop, 'test': test}[mode](*args) - except (KeyError, TypeError): - sys.exit(__doc__) diff --git a/atest/statuschecker.py b/atest/statuschecker.py deleted file mode 100644 index 20b6a84..0000000 --- a/atest/statuschecker.py +++ /dev/null @@ -1,190 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2008-2012 Nokia Siemens Networks Oyj -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Robot Framework Test Status Checker - -Usage: statuschecker.py infile [outfile] - -This tool processes Robot Framework output XML files and checks that test case -statuses and messages are as expected. Main use case is post-processing output -files got when testing Robot Framework test libraries using Robot Framework -itself. - -If output file is not given, the input file is considered to be also output -file and it is edited in place. - -By default all test cases are expected to 'PASS' and have no message. Changing -the expected status to 'FAIL' is done by having word 'FAIL' (in uppercase) -somewhere in the test case documentation. Expected error message must then be -given after 'FAIL'. Error message can also be specified as a regular -expression by prefixing it with string 'REGEXP:'. Testing only the beginning -of the message is possible with 'STARTS:' prefix. - -This tool also allows testing the created log messages. They are specified -using a syntax 'LOG x.y:z LEVEL Actual message', which is described in detail -detail in the tool documentation. -""" - -import re - -from robot.result import ExecutionResult - - -def process_output(inpath, outpath=None): - result = ExecutionResult(inpath) - _process_suite(result.suite) - result.save(outpath) - return result.return_code - -def _process_suite(suite): - for subsuite in suite.suites: - _process_suite(subsuite) - for test in suite.tests: - _process_test(test) - -def _process_test(test): - exp = _Expected(test.doc) - _check_status(test, exp) - if test.status == 'PASS': - _check_logs(test, exp) - -def _check_status(test, exp): - if exp.status != test.status: - test.status = 'FAIL' - if exp.status == 'PASS': - test.message = ("Test was expected to PASS but it FAILED. " - "Error message:\n") + test.message - else: - test.message = ("Test was expected to FAIL but it PASSED. " - "Expected message:\n") + exp.message - elif not _message_matches(test.message, exp.message): - test.status = 'FAIL' - test.message = ("Wrong error message.\n\nExpected:\n%s\n\nActual:\n%s\n" - % (exp.message, test.message)) - elif test.status == 'FAIL': - test.status = 'PASS' - test.message = 'Original test failed as expected.' - -def _message_matches(actual, expected): - if actual == expected: - return True - if expected.startswith('REGEXP:'): - pattern = '^%s$' % expected.replace('REGEXP:', '', 1).strip() - if re.match(pattern, actual, re.DOTALL): - return True - if expected.startswith('STARTS:'): - start = expected.replace('STARTS:', '', 1).strip() - if actual.startswith(start): - return True - return False - -def _check_logs(test, exp): - for kw_indices, msg_index, level, message in exp.logs: - try: - kw = test.keywords[kw_indices[0]] - for index in kw_indices[1:]: - kw = kw.keywords[index] - except IndexError: - indices = '.'.join(str(i+1) for i in kw_indices) - test.status = 'FAIL' - test.message = ("Test '%s' does not have keyword with index '%s'" - % (test.name, indices)) - return - if len(kw.messages) <= msg_index: - if message != 'NONE': - test.status = 'FAIL' - test.message = ("Keyword '%s' should have had at least %d " - "messages" % (kw.name, msg_index+1)) - else: - if _check_log_level(level, test, kw, msg_index): - _check_log_message(message, test, kw, msg_index) - -def _check_log_level(expected, test, kw, index): - actual = kw.messages[index].level - if actual == expected: - return True - test.status = 'FAIL' - test.message = ("Wrong level for message %d of keyword '%s'.\n\n" - "Expected: %s\nActual: %s.\n%s" - % (index+1, kw.name, expected, - actual, kw.messages[index].message)) - return False - -def _check_log_message(expected, test, kw, index): - actual = kw.messages[index].message.strip() - if _message_matches(actual, expected): - return True - test.status = 'FAIL' - test.message = ("Wrong content for message %d of keyword '%s'.\n\n" - "Expected:\n%s\n\nActual:\n%s" - % (index+1, kw.name, expected, actual)) - return False - - -class _Expected: - - def __init__(self, doc): - self.status, self.message = self._get_status_and_message(doc) - self.logs = self._get_logs(doc) - - def _get_status_and_message(self, doc): - if 'FAIL' in doc: - return 'FAIL', doc.split('FAIL', 1)[1].split('LOG', 1)[0].strip() - return 'PASS', '' - - def _get_logs(self, doc): - logs = [] - for item in doc.split('LOG')[1:]: - index_str, msg_str = item.strip().split(' ', 1) - kw_indices, msg_index = self._get_indices(index_str) - level, message = self._get_log_message(msg_str) - logs.append((kw_indices, msg_index, level, message)) - return logs - - def _get_indices(self, index_str): - try: - kw_indices, msg_index = index_str.split(':') - except ValueError: - kw_indices, msg_index = index_str, '1' - kw_indices = [int(index) - 1 for index in kw_indices.split('.')] - return kw_indices, int(msg_index) - 1 - - def _get_log_message(self, msg_str): - try: - level, message = msg_str.split(' ', 1) - if level not in ['TRACE', 'DEBUG', 'INFO', 'WARN', 'FAIL']: - raise ValueError - except ValueError: - level, message = 'INFO', msg_str - return level, message - - -if __name__=='__main__': - import sys - import os - - if not 2 <= len(sys.argv) <= 3 or '--help' in sys.argv: - print __doc__ - sys.exit(1) - infile = sys.argv[1] - outfile = sys.argv[2] if len(sys.argv) == 3 else None - print "Checking %s" % os.path.abspath(infile) - rc = process_output(infile, outfile) - if outfile: - print "Output: %s" % os.path.abspath(outfile) - if rc > 255: - rc = 255 - sys.exit(rc) diff --git a/atest/tests/ProxyableRemote.py b/atest/tests/ProxyableRemote.py deleted file mode 100644 index 876c651..0000000 --- a/atest/tests/ProxyableRemote.py +++ /dev/null @@ -1,43 +0,0 @@ -from robot.libraries.Remote import Remote, XmlRpcRemoteClient -import xmlrpclib -import httplib - - -class ProxyableRemote(Remote): - """A Remote library proxy that can optionally operate through a proxy, such as Fiddler, for debugging XML-RPC traffic. Example value for proxy: localhost:8888 - """ - - def __init__(self, uri, proxy=None): - Remote.__init__(self, uri) - self._client = ProxyableXmlRpcRemoteClient(uri, proxy) - - -class ProxyableXmlRpcRemoteClient(XmlRpcRemoteClient): - - def __init__(self, uri, proxy=None): - tp = None - if proxy is not None: - tp = ProxiedTransport() - tp.set_proxy(proxy) - self._server = xmlrpclib.ServerProxy(uri, transport=tp, encoding='UTF-8') - - -class ProxiedTransport(xmlrpclib.Transport): - - def set_proxy(self, proxy): - self.proxy = proxy - - def make_connection(self, host): - self.realhost = host - if self.proxy is None: - h = httplib.HTTPConnection() - else: - h = httplib.HTTPConnection(self.proxy) - self._connection = host, h - return h - - def send_request(self, connection, handler, request_body): - connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler)) - - def send_host(self, connection, host): - connection.putheader('Host', self.realhost) diff --git a/atest/tests/Z_LAST__special_failures.txt b/atest/tests/Z_LAST__special_failures.txt deleted file mode 100644 index 49f592d..0000000 --- a/atest/tests/Z_LAST__special_failures.txt +++ /dev/null @@ -1,26 +0,0 @@ -*** Settings *** -Resource resource.txt - -*** Test Cases *** -Not special - [Documentation] FAIL org.robotframework.examplelib.impl.SpecialException: message - Not special message - Fail This should not be executed - -Continuable - [Documentation] FAIL Several failures occurred:\n\n - ... 1) org.robotframework.examplelib.impl.SpecialException: message\n\n - ... 2) org.robotframework.examplelib.impl.SpecialException: second message\n\n - ... 3) org.robotframework.examplelib.impl.SpecialException: third message - Continuable message - Continuable second message - Continuable third message - -Fatal - [Documentation] FAIL org.robotframework.examplelib.impl.SpecialException: Execution ends here - Fatal Execution ends here - Fail This should not be executed - -Fails due to earlier fatal error - [Documentation] FAIL Test execution stopped due to a fatal error. - Fail This should not be executed \ No newline at end of file diff --git a/atest/tests/argument_counts.txt b/atest/tests/argument_counts.txt deleted file mode 100644 index cb3f9ce..0000000 --- a/atest/tests/argument_counts.txt +++ /dev/null @@ -1,36 +0,0 @@ -*** Settings *** -Resource resource.txt -Test Template Arguments Should Be Accepted - -*** Test Cases *** -No Arguments - no arguments No Arguments - -Required Arguments - some argument One Argument some argument - arg1 arg2 Two Arguments arg1 arg2 - 1 2 3 4 5 6 7 Seven Arguments 1 2 3 4 5 6 7 - -Arguments With Default Values - one two three Arguments With Default Values one two three - one two 3 Arguments With Default Values one two - one 2 3 Arguments With Default Values one - -Variable Number Of Arguments - ${EMPTY} Variable Number Of Arguments - One argument Variable Number Of Arguments One argument - 3 args now Variable Number Of Arguments 3 args now - 1 2 3 4 5 6 Variable Number Of Arguments 1 2 3 4 5 6 - -Required Arguments, Default Values and Varargs - Hello world Required Defaults And Varargs Hello - Hi tellus Required Defaults And Varargs Hi tellus - Hei taas maa Required Defaults And Varargs Hei taas maa - 1 2 3 4 5 Required Defaults And Varargs 1 2 3 4 5 - -*** Keywords *** -Arguments Should Be Accepted - [Arguments] ${expected} ${keyword} @{arguments} - ${actual} = Run Keyword ${keyword} @{arguments} - Should Be Equal ${actual} ${expected} - diff --git a/atest/tests/argument_types.txt b/atest/tests/argument_types.txt deleted file mode 100644 index e60cab7..0000000 --- a/atest/tests/argument_types.txt +++ /dev/null @@ -1,79 +0,0 @@ -| *** Settings *** | -| Resource | resource.txt | - -| *** Test Cases *** | -| String As Argument | -| | String As Argument | ${BYTE STRING} | - -| Non-ASCII String As Argument | -| | Unicode String As Argument | ${UNICODE STRING} | - -| Control Char As Argument | -| | [Documentation] | Fails with ExpatError when server runs on Jython 2.5. | -| | Control Char As Argument | ${CONTROL CHAR} | - -| Empty String As Argument | -| | Empty String As Argument | ${EMPTY} | - -| Integer As Argument | -| | Integer As Argument | ${42} | -| | Negative Integer As Argument | ${-1} | - -| Int As Argument Conversion From String | -| | [Documentation] | JavalibCore does the conversion, this is just a sanity check | -| | ${number}= | Int As Argument | 42 | -| | Should Be Equal | ${number} | ${42} | - -| Double As Argument | -| | Double As Argument | ${9.34} | -| | Double Object As Argument | ${4.2} | - -| Zero As Argument | -| | Zero As Argument | ${0} | - -| Boolean As Argument | -| | Boolean True As Argument | ${True} | -| | Boolean False As Argument | ${False} | -| | Boolean Object As Argument | ${False} | - -| Null As Argument | -| | [Documentation] | None is converted to empty string because it is not supported by all XML-RPC versions. | -| | Null As Argument | ${None} | - -| Arbitrary Object As Argument | -| | [Documentation] | Arbitrary objects cannot be transferred over XML-RPC and thus only their string presentation is used | -| | Object As Argument | ${MyObject()} | - -| List As Argument | -| | List As Argument | ${LIST} | -| | Empty List As Argument | ${EMPTY LIST} | - -| List Containing None As Argument | -| | List Containing None As Argument | ${LIST WITH NONE} | - -| List Containing Arbitrary Objects As Argument | -| | List Containing Objects As Argument | ${LIST WITH OBJECTS} | - -| Nested List As Argument | -| | Nested List As Argument | ${NESTED LIST} | - -| Map As Argument | -| | Map As Argument | ${DICT} | -| | Empty Map As Argument | ${EMPTY DICT} | - -| Map With Non-String Keys As Argument | -| | [Documentation] | XML-RPC supports only strings as keys so must convert them | -| | Map With Non String Keys As Argument | ${DICT WITH NON STRING KEYS} | - -| Map Containing None As Argument | -| | Map Containing None As Argument | ${DICT WITH NONE} | - -| Map Containing Objects As Argument | -| | Map Containing Objects As Argument | ${DICT WITH OBJECTS} | - -| Nested Map As Argument | -| | Nested Map As Argument | ${NESTED DICT} | - -| Array As Argument | -| | Array As Argument | ${LIST_WITH_INTEGERS} | ${-2} | - diff --git a/atest/tests/basic_communication.txt b/atest/tests/basic_communication.txt deleted file mode 100644 index b33e9ee..0000000 --- a/atest/tests/basic_communication.txt +++ /dev/null @@ -1,31 +0,0 @@ -*** Settings *** -Resource resource.txt - -*** Variables *** -${COUNT} 100 - -*** Test Cases *** -Passing - Passing - -Failing - [Documentation] FAIL This is the error we get - Failing This is the error we get - -Logging - [Documentation] LOG 1 INFO Hello, world! LOG 2 WARN Warning, warning!! - Logging Hello, world! - Logging Warning, warning!! WARN - -Returning - ${ret} = Returning - Should Be Equal ${ret} returned string - -Use Remote Keyword Multiple Times - [Documentation] - ... LOG 1.1.1 Round 1 - ... LOG 1.2.1 Round 2 - ... LOG 1.${COUNT}.1 Round ${COUNT} - : FOR ${i} IN RANGE ${COUNT} - \ Logging Round ${i + 1} - diff --git a/atest/tests/failures.txt b/atest/tests/failures.txt deleted file mode 100644 index f42783e..0000000 --- a/atest/tests/failures.txt +++ /dev/null @@ -1,40 +0,0 @@ -| *** Settings *** | -| Resource | resource.txt | - -| *** Test Cases *** | -| Base Exception | -| | [Documentation] | FAIL My message | -| | Base Exception | - -| Exception Without Message | -| | [Documentation] | FAIL Exception | -| | Exception Without Message | - -| AssertionError | -| | [Documentation] | FAIL Failure message | -| | Assertion Error | - -| RuntimeError | -| | [Documentation] | FAIL Error message | -| | Runtime Error | - -| Zero Division | -| | [Documentation] | FAIL java.lang.ArithmeticException: / by zero | -| | Zero Division | - -| Custom Exception | -| | [Documentation] | FAIL org.robotframework.examplelib.impl.MyException: My message | -| | Custom Exception | - -| Suppressed Name Exception | -| | Run Keyword And Expect Error | name suppressed | Suppressed Name Exception | ${True} | -| | Run Keyword And Expect Error | name suppressed | Suppressed Name Exception | ${False} | - -| Failure Deeper | -| | [Documentation] | FAIL Finally failing | -| | Failure Deeper | - -| Error Message With Non-ASCII Unicode | -| | [Documentation] | FAIL ${UNICODE STRING} | -| | Error Message With Non ASCII Unicode | - diff --git a/atest/tests/finding_keywords.txt b/atest/tests/finding_keywords.txt deleted file mode 100644 index d43b71d..0000000 --- a/atest/tests/finding_keywords.txt +++ /dev/null @@ -1,11 +0,0 @@ -| *** Settings *** | -| Resource | resource.txt | - -| *** Test Cases *** | -| Private Methods Should Be Ignored | -| | [Documentation] | FAIL No keyword with name 'Private Method' found. | -| | Private Method | - -| Static Methods Should Be Supported | -| | ${breakfast}= | Static Method | -| | Should Be Equal | ${breakfast} | eggs | diff --git a/atest/tests/invalid_argument_counts.txt b/atest/tests/invalid_argument_counts.txt deleted file mode 100644 index 5bfc097..0000000 --- a/atest/tests/invalid_argument_counts.txt +++ /dev/null @@ -1,29 +0,0 @@ -*** Settings *** -Default Tags argsknown -Resource resource.txt - -*** Test Cases *** - -Using Arguments When No Accepted - [Documentation] FAIL Keyword 'Remote.No Arguments' expected 0 arguments, got 1. - No Arguments not allowed - -Too Few Arguments When Using Only Required Args - [Documentation] FAIL Keyword 'Remote.One Argument' expected 1 argument, got 0. - One Argument - -Too Many Arguments When Using Only Required Args - [Documentation] FAIL Keyword 'Remote.Two Arguments' expected 2 arguments, got 3. - Two Arguments too many arguments - -Too Few Arguments When Using Default Values - [Documentation] FAIL Keyword 'Remote.Arguments With Default Values' expected 1 to 3 arguments, got 0. - Arguments With Default Values - -Too Many Arguments When Using Default Values - [Documentation] FAIL Keyword 'Remote.Arguments With Default Values' expected 1 to 3 arguments, got 5. - Arguments With Default Values this is way too much - -Too Few Arguments When Using Varargs - [Documentation] FAIL Keyword 'Remote.Required Defaults And Varargs' expected at least 1 argument, got 0. - Required Defaults And Varargs diff --git a/atest/tests/kwargs.txt b/atest/tests/kwargs.txt deleted file mode 100644 index e8a78e9..0000000 --- a/atest/tests/kwargs.txt +++ /dev/null @@ -1,8 +0,0 @@ -*** Settings *** -Force Tags kwargs -Resource resource.txt - -*** Test Cases *** -Kwargs Are Handled - ${value}= Get Kwarg Value eggs eggs=${2} - Should Be Equal ${value} ${2} diff --git a/atest/tests/logging.txt b/atest/tests/logging.txt deleted file mode 100644 index 63c75be..0000000 --- a/atest/tests/logging.txt +++ /dev/null @@ -1,44 +0,0 @@ -| *** Settings *** | -| Suite Setup | Set Debug Log Level | -| Suite Teardown | Reset Log Level | -| Resource | resource.txt | - -| *** Test Cases *** | -| One message Without Level | -| | [Documentation] | LOG 1 INFO Hello, world! | -| | One Message Without Level | - -| Log Levels | -| | [Documentation] | LOG 1 DEBUG Debug message\nLOG 2 INFO Information message\nLOG 3 WARN Warning message | -| | Logging | Debug message | DEBUG | -| | Logging | Information message | INFO | -| | Logging | Warning message | WARN | - -| Multiple Messages With Different Levels | -| | [Documentation] | LOG 1:1 INFO Info message\nLOG 1:2 DEBUG Debug message\nLOG 1:3 INFO Second info\n this time with two lines\nLOG 1:4 INFO Third info\nLOG 1:5 WARN Warning | -| | Multiple Messages With Different Levels | - -| Log Unicode | -| | [Documentation] | LOG 1 INFO ${UNICODE STRING} | -| | Log Unicode | - -| Logging And Failing | -| | [Documentation] | FAIL Too slow\nLOG 1:1 INFO This keyword will fail!\nLOG 1:2 WARN Run for your lives!!\nLOG 1:3 FAIL Too slow\nLOG 1:4 DEBUG REGEXP: [^:]+: Too slow.* | -| | Logging And Failing | - -| Logging And Returning | -| | [Documentation] | LOG 1:1 INFO Logged message\nLOG 1:2 INFO \${ret} = Returned value\nLOG 3:1 WARN This keyword returns nothing\nLOG 3:2 INFO \${ret} = ${EMPTY} | -| | ${ret} = | Logging And Returning | -| | Should Be Equal | ${ret} | Returned value | -| | ${ret} = | Logging | This keyword returns nothing | WARN | -| | Should Be Equal | ${ret} | ${EMPTY} | - -| Log Control Char | -| | [Documentation] | Expected unicode char has a \x01 in it.\nLOG 1:1 INFO ģ | -| | Log Control Char | - -| Logging both through stdout and stderr | -| | [Documentation] | LOG 1:1 INFO stdout\nLOG 1:2 INFO stderr\nLOG 2:1 DEBUG stdout-continue\nLOG 2:2 INFO stderr\nLOG 3:1 INFO o\no2\nLOG 3:2 DEBUG e\nLOG 3:3 INFO e2 | -| | Logging both to stdout and stderr | stdout | stderr | -| | Logging both to stdout and stderr | *DEBUG* stdout | stderr | -continue | -| | Logging both to stdout and stderr | o\n | *DEBUG* e\n | o2 | *INFO* e2 | diff --git a/atest/tests/resource.txt b/atest/tests/resource.txt deleted file mode 100644 index 66179fb..0000000 --- a/atest/tests/resource.txt +++ /dev/null @@ -1,16 +0,0 @@ -*** Settings *** -Library Remote localhost:${PORT}${PATH} -Variables variables.py - -*** Variables *** -${PORT} 8270 -${PATH} / -${ORIG LOG LEVEL} INFO - -*** Keywords *** -Set Debug Log Level - ${ORIG LOG LEVEL} = Set Log Level DEBUG - Set Suite Variable ${ORIG LOG LEVEL} - -Reset Log Level - Set Log Level ${ORIG LOG LEVEL} diff --git a/atest/tests/return_values.txt b/atest/tests/return_values.txt deleted file mode 100644 index 0ba8a6f..0000000 --- a/atest/tests/return_values.txt +++ /dev/null @@ -1,139 +0,0 @@ -| *** Settings *** | -| Test Template | Return Value Should Be | -| Resource | resource.txt | - -| *** Test Cases *** | -| Return String | -| | Return String | Hello, world! | - -| Return Empty String | -| | Return Empty String | ${EMPTY} | - -| Return Unicode String | -| | Return Unicode String | ${UNICODE STRING} | - -| Return Control Char | -| | [Documentation] | Fails with ExpatError when running tests on Jython 2.5. | -| | Return Control Char | ${CONTROL CHAR} | - -| Return Short | -| | Return Short | ${-88} | -| | Return Short Object | ${9} | - -| Return Integer | -| | Return Int | ${12} | -| | Return Integer | ${42} | -| | Return Negative Integer | ${-1} | - -| Return Zero | -| | Return Zero | ${0} | - -| Return Float | -| | Return Float | ${3.14} | -| | Return Negative Float | ${-0.5} | -| | Return Float Object | ${86.02} | - -| Return Double | -| | Return Double | ${9.34} | -| | Return Double Object | ${4.2} | - -| Return Byte | -| | Return Byte | ${67} | -| | Return Byte Object | ${127} | - -| Return Boolean | -| | Return Boolean True | ${True} | -| | Return Boolean False | ${False} | -| | Return Boolean Object | ${False} | - -| Return Null And Void | -| | [Documentation] | None is not supported by all XML-RPC versions and thus it is converted to an empty string | -| | Return Nothing | ${EMPTY} | -| | Return Null | ${EMPTY} | - -| Return Arbitrary Object | -| | [Documentation] | Arbitrary objects cannot be transferred over XML-RPC and thus only their string presentation is returned | -| | Return Object | | - -| Return List | -| | Return List | ${LIST} | -| | Return Empty List | ${EMPTY LIST} | - -| Return List Containing Null | -| | Return List Containing Null | [''] | eval | - -| Return List Containing Arbitrary Objects | -| | Return List Containing Objects | ['', ''] | eval | - -| Return Nested List | -| | Return Nested List | [[True, False], [[1, '', '', {}]]] | eval | - -| Return Map | -| | Return Map | ${DICT} | -| | Return Empty Map | ${EMPTY DICT} | - -| Return Map With Non-String Keys | -| | [Documentation] | XML-RPC supports only strings as keys so must convert them | -| | Return Map \ With Non String Keys | {'1': 2, '': 1} | eval | - -| Return Map Containing Null | -| | Return Map Containing Null | {'As value': '', '': 'As key'} | eval | - -| Return Map Containing Objects | -| | Return Map \ Containing Objects | {'As value': '', '': 'As key'} | eval | - -| Return Nested Map | -| | Return Nested Map | {'1': {'': False}, '2': {'A': {'n': ''}, 'B': {'o': '', 'e': {}}}} | eval | - -| Return Array Containing Bytes | -| | Return Array Of Byte | [${-57}, ${21}] | eval | -| | Return Primitive Array Of Byte | [${-4}, ${8}] | eval | - -| Return Array Containing Strings | -| | Return Array Containing Strings | ['spam', 'eggs'] | eval | - -| Return Array Containing Integers | -| | Return Array Of Short | [${34}, ${-98}] | eval | -| | Return Primitive Array Of Short | [${287}, ${-86}] | eval | -| | Return Array Of Integer | [${3}, ${-5}] | eval | -| | Return Primitive Array Of Int | [${-338}, ${897}] | eval | -| | Return Array Of Long | ['-9223372036854775800', '9223372036854775805'] | eval | # strings as longs do not fit in I4 | -| | Return Primitive Array Of Long | ['8723372036854774829', '-9123372036854775382'] | eval | - -| Return Array Containing Rational Numbers | -| | Return Array Of Float | [${8.2}, ${-7.38}] | eval | -| | Return Primitive Array Of Float | [${-7.774}, ${562.1}] | eval | -| | Return Array Of Double | [${101.6}, ${45.67}] | eval | -| | Return Primitive Array Of Double | [${-37.11}, ${90.4}] | eval | -| | Return Primitive Array Of Boolean | [${True}, ${False}] | eval | - -| Return Array Containing Booleans | -| | Return Array Of Boolean | [${False}, ${True}] | eval | -| | Return Primitive Array Of Boolean | [${True}, ${False}] | eval | - -| Return Array Containing Chars | -| | Return Array Containing Chars | OK | - -| Return Array Containing Arbitrary Objects | -| | Return Array Of Objects | ['', ''] | eval | - -| Return Iterable | -| | Return Queue | ['first', ''] | eval | -| | Return Tree Set | [${2}, ${5}] | eval | -| | Return Empty Queue | [] | eval | - -| Return Date | -| | Return Date | Wed Dec 31 18:00:00 CST 1969 | - -| *** Keywords *** | -| Return Value Should Be | -| | [Arguments] | ${keyword} | ${expected} | ${evaluate}= | -| | ${actual} = | Run Keyword | ${keyword} | -| | ${tester} = | Set Variable If | "${evaluate}" | Should Be Equal Evaluated | Should Be Equal | -| | Run Keyword | ${tester} | ${actual} | ${expected} | - -| Should Be Equal Evaluated | -| | [Arguments] | ${actual} | ${expected} | -| | ${expected} = | Evaluate | ${expected} | -| | Should Be Equal | ${actual} | ${expected} | - diff --git a/atest/tests/traceback.txt b/atest/tests/traceback.txt deleted file mode 100644 index bb5aac3..0000000 --- a/atest/tests/traceback.txt +++ /dev/null @@ -1,18 +0,0 @@ -| *** Settings *** | -| Suite Setup | Set Debug Log Level | -| Suite Teardown | Reset Log Level | -| Resource | resource.txt | - -| *** Test Cases *** | -| Remote Traceback Is Shown In Log | -| | [Documentation] | FAIL My error message\nLOG 1:1 FAIL My error message\nLOG 1:2 DEBUG REGEXP: .*\n\\s+at [^\\(]+\\(.*java:\\d+\\).* | -| | Failing | My error message | - -| Remote Traceback With Multiple Entries | -| | [Documentation] | FAIL Finally failing\nLOG 1:1 FAIL Finally failing\nLOG 1:2 DEBUG REGEXP: [^:]+: Finally failing.* | -| | Failure Deeper | - -| Local Traceback Is Not Shown In Log | -| | [Documentation] | FAIL Yet another error\nLOG 1:1 FAIL Yet another error\nLOG 1:2 DEBUG REGEXP: .*\n\\s+at [^\\(]+\\(.*java:\\d+\\).*\nLOG 1:3 NONE | -| | Failing | Yet another error | - diff --git a/atest/tests/variables.py b/atest/tests/variables.py deleted file mode 100644 index fb4a9b5..0000000 --- a/atest/tests/variables.py +++ /dev/null @@ -1,29 +0,0 @@ -# Can be used in the test data like ${MyObject()} or ${MyObject(1)} -class MyObject: - def __init__(self, index=''): - self.index = index - def __str__(self): - return '' % self.index - -BYTE_STRING = 'Hello, world!' -UNICODE_STRING = (u'Hyv\u00E4\u00E4 y\u00F6t\u00E4. ' - u'\u0421\u043F\u0430\u0441\u0438\u0431\u043E!') -CONTROL_CHAR = '\x01' - -LIST = ['One', -2, False] -EMPTY_LIST = [] -LIST_WITH_NONE = [None] -LIST_WITH_OBJECTS = [MyObject(1), MyObject(2)] -NESTED_LIST = [[True, False], [[1, None, MyObject(), {}]]] -LIST_WITH_INTEGERS = [3, -5] - -DICT = {'one': 1, 'spam': 'eggs'} -EMPTY_DICT = {} -DICT_WITH_NON_STRING_KEYS = {1: 2, None: True} -DICT_WITH_NONE = {'As value': None, None: 'As key'} -DICT_WITH_OBJECTS = {'As value': MyObject(1), MyObject(2): 'As key'} -NESTED_DICT = {1: {None: False}, - 2: {'A': {'n': None}, - 'B': {'o': MyObject(), 'e': {}}}} - -REPLACEMENT_CHARACTER = u'\uFFFD' diff --git a/examples/AnnotationLibrary/README.txt b/examples/AnnotationLibrary/README.txt deleted file mode 100644 index 0413ed7..0000000 --- a/examples/AnnotationLibrary/README.txt +++ /dev/null @@ -1,29 +0,0 @@ -A bare-bones example of how to use jrobotremoteserver would be quite simple. This example instead aims to show how to use jrobotremoteserver together with other Robot Framework-related tools to create a remote test library that is properly documented and easy to develop. - -Building the Example --------------------- -At the root directory of the project execute 'mvn clean package'. This will build the project, run tests, and generate library documentation. Maven must be installed and located on the PATH (see http://maven.apache.org/download.html#Installation). - -Starting the Remote Library ---------------------------- -After building the project, from the project directory execute 'java -jar target/MyRemoteLibrary-1.0-jar-with-dependencies.jar'. Depending on your installation of Java, you may be also able to type just the name of the jar file or double-click on the jar file to start the server. - -Project Structure ------------------ -This project follows the Maven conventions for the location of all files. The default locations used by robotframework-maven-plugin are used as well. -The library keywords are implemented in several classes. This is not necessary for a library as simple as this, but the capability to do so is important and something that JavaLib Core provides. - -Library Documentation ---------------------- -The library documentation is created during a unit test. Ideally this would be done using the libdoc goal of robotframework-maven-plugin, but it does not support dynamic API libraries that have dependencies. - -Acceptance Testing ------------------- -The testing is executed during the build using robotframework-maven-plugin. The suite is set up to start and stop the remote server only when running as part of the build process. - -Build Artifacts ---------------- -target/MyRemoteLibrary-1.0.jar - test library alone -target/MyRemoteLibrary-1.0-jar-with-dependencies.jar - test library including dependencies (this is runnable) -target/robotframework/MyRemoteLibrary-1.0.html - library documentation for humans -target/robotframework/MyRemoteLibrary-1.0.xml - library documentation for RIDE \ No newline at end of file diff --git a/examples/AnnotationLibrary/pom.xml b/examples/AnnotationLibrary/pom.xml deleted file mode 100644 index 5be2e7c..0000000 --- a/examples/AnnotationLibrary/pom.xml +++ /dev/null @@ -1,114 +0,0 @@ - - 4.0.0 - com.example - MyRemoteLibrary - 1.0 - jar - - UTF-8 - com.example.MyRemoteLibrary - - - - - - org.robotframework - javalib-core - 0.9.1 - - - - - com.github.ombre42 - jrobotremoteserver - 2.0-BETA - - - - - commons-io - commons-io - 2.3 - - - - - org.robotframework - robotframework - 2.7.0 - test - - - - - org.testng - testng - 6.3.1 - test - - - - - - - - maven-assembly-plugin - - - jar-with-dependencies - - - - - - ${testLibraryClass} - - - - - - - - make-my-jar-with-dependencies - package - - single - - - - - - - - com.googlecode.robotframework-maven-plugin - robotframework-maven-plugin - 1.1.1 - - - test - - run - - - - - - - - BUILDING:True - - - - - - - - - src/test/resources - true - - - - diff --git a/examples/AnnotationLibrary/src/main/java/com/example/MyRemoteLibrary.java b/examples/AnnotationLibrary/src/main/java/com/example/MyRemoteLibrary.java deleted file mode 100644 index e4c1df5..0000000 --- a/examples/AnnotationLibrary/src/main/java/com/example/MyRemoteLibrary.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.example; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.nio.charset.Charset; - -import org.apache.commons.io.IOUtils; -import org.robotframework.javalib.library.AnnotationLibrary; -import org.robotframework.remoteserver.RemoteServer; - -public class MyRemoteLibrary extends AnnotationLibrary { - public MyRemoteLibrary() { - // tell AnnotationLibrary where to find the keywords - super("com/example/keywords/*.class"); - } - - @Override - public String getKeywordDocumentation(String keywordName) { - if (keywordName.equals("__intro__")) - return getIntro(); - return super.getKeywordDocumentation(keywordName); - } - - /* Starts jrobotremoteserver with an example library and returns. The application will shutdown when all of the - * web server's threads exit. - */ - public static void main(String[] args) throws Exception { - RemoteServer.configureLogging(); - RemoteServer server = new RemoteServer(); - server.addLibrary(MyRemoteLibrary.class, 8270); - server.start(); - } - - // The introduction is stored in a text file resource because it is easier to edit than String constants. - private String getIntro() { - try { - InputStream introStream = MyRemoteLibrary.class.getResourceAsStream("__intro__.txt"); - StringWriter writer = new StringWriter(); - IOUtils.copy(introStream, writer, Charset.defaultCharset()); - return writer.toString(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/examples/AnnotationLibrary/src/main/java/com/example/keywords/QueueManager.java b/examples/AnnotationLibrary/src/main/java/com/example/keywords/QueueManager.java deleted file mode 100644 index 69d2deb..0000000 --- a/examples/AnnotationLibrary/src/main/java/com/example/keywords/QueueManager.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.example.keywords; - -import static org.apache.commons.lang.StringEscapeUtils.escapeHtml; - -import java.util.Iterator; -import java.util.Queue; -import java.util.concurrent.LinkedBlockingQueue; - -import org.robotframework.javalib.annotation.ArgumentNames; -import org.robotframework.javalib.annotation.RobotKeyword; -import org.robotframework.javalib.annotation.RobotKeywords; - -@RobotKeywords -public class QueueManager -{ - private Queue queue = new LinkedBlockingQueue(); - - @RobotKeyword("Clears the queue.") - @ArgumentNames({}) - public void clearQueue() { - queue.clear(); - } - - @RobotKeyword("Adds the given `element` to tail of the queue.") - @ArgumentNames({"element"}) - public void addToQueue(Object element) { - queue.add(element); - } - - @RobotKeyword("Removes the element at the head of the queue.") - @ArgumentNames({}) - public Object removeFromQueue() { - return queue.remove(); - } - - @RobotKeyword("Retrieves the queue.") - @ArgumentNames({}) - public Queue getQueue() { - return queue; - } - - @RobotKeyword("Logs the elements in the queue.") - @ArgumentNames({}) - public void logQueue() { - StringBuilder sb = new StringBuilder(); - sb.append("*HTML* "); - Iterator iter = queue.iterator(); - while (iter.hasNext()) { - Object element = iter.next(); - String value = escapeHtml(element.toString()); - sb.append(""); - sb.append(""); - sb.append(""); - sb.append(""); - } - sb.append("
ValueType
" + value + "" + element.getClass().getName() + "
"); - System.out.print(sb.toString()); - } -} diff --git a/examples/AnnotationLibrary/src/main/resources/com/example/__intro__.txt b/examples/AnnotationLibrary/src/main/resources/com/example/__intro__.txt deleted file mode 100644 index 274e0e2..0000000 --- a/examples/AnnotationLibrary/src/main/resources/com/example/__intro__.txt +++ /dev/null @@ -1,5 +0,0 @@ -MyRemoteLibrary is an example library that demonstrates how to use jrobotremoteserver and AnnotationLibrary from JavaLib Core together. - -This library exposes a LinkedBlockingQueue to Robot Framework that will store whatever Robot Framework sends. - -jrobotremoteserver aims to make returning Java objects to Robot Framework painless. Note that `Get Queue` returns a LinkedBlockingQueue, which does not implement List but does, however, implement Iterable. Iterables are converted to arrays during serialization. See the [https://github.com/ombre42/jrobotremoteserver/wiki/User-Guide|User Guide] for more information on type conversions. \ No newline at end of file diff --git a/examples/AnnotationLibrary/src/test/java/com/example/MyRemoteLibraryLauncher.java b/examples/AnnotationLibrary/src/test/java/com/example/MyRemoteLibraryLauncher.java deleted file mode 100644 index cc4c7d1..0000000 --- a/examples/AnnotationLibrary/src/test/java/com/example/MyRemoteLibraryLauncher.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.example; - -// A static API test library to allow starting the remote server when Robot Framework is executing in Jython -public class MyRemoteLibraryLauncher -{ - public void startRemoteServer() throws Exception { - MyRemoteLibrary.main(null); - } -} diff --git a/examples/AnnotationLibrary/src/test/java/robotframework/LibraryDocumentationGeneratorTest.java b/examples/AnnotationLibrary/src/test/java/robotframework/LibraryDocumentationGeneratorTest.java deleted file mode 100644 index 9650149..0000000 --- a/examples/AnnotationLibrary/src/test/java/robotframework/LibraryDocumentationGeneratorTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package robotframework; - - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import org.robotframework.RobotFramework; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class LibraryDocumentationGeneratorTest { - /* - * Generates the library documentation, which is not really a test. It would be more desirable to do this with - * robotframework-maven-plugin, but it does not support dynamic API libraries at this time. - */ - @Test - public void generate() - { - Properties props = getMavenProperties(); - String name = props.getProperty("project.name"); - String version = props.getProperty("project.version"); - String testLibraryClass = props.getProperty("testLibraryClass"); - new File("target/robotframework").mkdirs(); - for (String type : new String[] {"xml", "html"}) { - List args = new ArrayList(); - args.add("libdoc"); - args.add("--name"); - args.add(name); - args.add("--version"); - args.add(version); - args.add("--format"); - args.add(type); - args.add(testLibraryClass); - args.add(String.format("target/robotframework/%s-%s.%s", name, version, type)); - int exitCode = RobotFramework.run(args.toArray(new String[] {})); - Assert.assertEquals(exitCode, 0, String.format("Failed to generate %s library documentation", type)); - } - } - - public Properties getMavenProperties() - { - Properties props = new Properties(); - try { - InputStream in = this.getClass().getResourceAsStream("maven.properties"); - props.load(in); - } catch (IOException e) { - throw new RuntimeException(e); - } - return props; - } -} diff --git a/examples/AnnotationLibrary/src/test/resources/robotframework/maven.properties b/examples/AnnotationLibrary/src/test/resources/robotframework/maven.properties deleted file mode 100644 index 5294534..0000000 --- a/examples/AnnotationLibrary/src/test/resources/robotframework/maven.properties +++ /dev/null @@ -1,5 +0,0 @@ -# provides a way to access Maven properties during the test phase. Resource filtering will replace the right-hand side with values during the build process. -# There is another way of doing this, but it involves having an element in the POM for every property. -project.name=${project.name} -project.version=${project.version} -testLibraryClass=${testLibraryClass} \ No newline at end of file diff --git a/examples/AnnotationLibrary/src/test/resources/robotframework/tests/MyRemoteLibrary.txt b/examples/AnnotationLibrary/src/test/resources/robotframework/tests/MyRemoteLibrary.txt deleted file mode 100644 index ab0e439..0000000 --- a/examples/AnnotationLibrary/src/test/resources/robotframework/tests/MyRemoteLibrary.txt +++ /dev/null @@ -1,31 +0,0 @@ -| *** Settings *** | -| Documentation | A suite of acceptance tests.\n\nEven though the library could arguably be used locally for acceptance testing, this suite is true end-to-end testing because the library is accessed remotely. | -| Suite Setup | Run Keywords | Start Remote Server If Building | Import Remote Library | -| Suite Teardown | Stop Remote Server If Building | -| Library | TypeLibrary.py | -| Resource | Resources/common.txt | - -| *** Variables *** | - -| *** Test Cases *** | -| Add And Remove Elements To Queue | -| | Clear Queue | -| | Add To Queue | ${42} | -| | Add To Queue | ${3.14} | -| | Add To Queue | Hail to the robots | -| | Log Queue | -| | ${queue} | Get Queue | -| | Length Should Be | ${queue} | 3 | -| | ${value} | Remove From Queue | -| | Should Be Int | ${value} | -| | Should Be Equal | ${value} | ${queue[0]} | -| | ${value} | Remove From Queue | -| | Should Be Float | ${value} | -| | Should Be Equal | ${value} | ${queue[1]} | -| | ${value} | Remove From Queue | -| | Should Be String | ${value} | -| | Should Be Equal | ${value} | ${queue[2]} | -| | ${queue} | Get Queue | -| | Should Be Empty | ${queue} | - -| *** Keywords *** | diff --git a/examples/AnnotationLibrary/src/test/resources/robotframework/tests/Resources/common.txt b/examples/AnnotationLibrary/src/test/resources/robotframework/tests/Resources/common.txt deleted file mode 100644 index a0e067e..0000000 --- a/examples/AnnotationLibrary/src/test/resources/robotframework/tests/Resources/common.txt +++ /dev/null @@ -1,13 +0,0 @@ -| *** Variables *** | -| ${BUILDING} | False | # Whether a build of the library is taking place | - -| *** Keywords *** | -| Import Remote Library | -| | Import Library | Remote | http://localhost:8270/ | WITH NAME | MyRemoteLibrary | - -| Start Remote Server If Building | -| | Run Keyword If | ${BUILDING} | Import Library | com.example.MyRemoteLibraryLauncher | -| | Run Keyword If | ${BUILDING} | Start Remote Server | - -| Stop Remote Server If Building | -| | Run Keyword If | ${BUILDING} | Stop Remote Server | diff --git a/examples/AnnotationLibrary/src/test/resources/robotframework/tests/TypeLibrary.py b/examples/AnnotationLibrary/src/test/resources/robotframework/tests/TypeLibrary.py deleted file mode 100644 index 13a1a50..0000000 --- a/examples/AnnotationLibrary/src/test/resources/robotframework/tests/TypeLibrary.py +++ /dev/null @@ -1,16 +0,0 @@ -from types import * - - -class TypeLibrary(object): - - def should_be_int(self, value): - if type(value) is not IntType: - raise AssertionError('Type is %s, not int' % type(value)) - - def should_be_float(self, value): - if type(value) is not FloatType: - raise AssertionError('Type is %s, not float' % type(value)) - - def should_be_string(self, value): - if type(value) is not StringType: - raise AssertionError('Type is %s, not string' % type(value)) \ No newline at end of file diff --git a/jrobot-features/pom.xml b/jrobot-features/pom.xml new file mode 100644 index 0000000..34bce00 --- /dev/null +++ b/jrobot-features/pom.xml @@ -0,0 +1,88 @@ + + + 4.0.0 + + jrobot-parent + com.github.aenniw + 3.2-SNAPSHOT + + jrobot-features + jar + + features.xml + + + + + com.github.aenniw + jrobot-remote-server + ${project.version} + + + com.github.aenniw + jrobot-test-library + ${project.version} + + + + + + + src/main/resources + true + + + + + org.apache.karaf.tooling + karaf-maven-plugin + true + + + + kar + + + ${project.build.directory}/classes/${features.file} + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + generate-resources + + resources + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + package + + attach-artifact + + + + + ${project.build.directory}/classes/${features.file} + xml + features + + + + + + + + + diff --git a/jrobot-features/src/main/resources/features.xml b/jrobot-features/src/main/resources/features.xml new file mode 100644 index 0000000..b953621 --- /dev/null +++ b/jrobot-features/src/main/resources/features.xml @@ -0,0 +1,11 @@ + + + + + mvn:com.github.aenniw/jrobot-remote-server/${project.version} + jetty + + diff --git a/jrobot-karaf/pom.xml b/jrobot-karaf/pom.xml new file mode 100755 index 0000000..c9c4d3b --- /dev/null +++ b/jrobot-karaf/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + jrobot-parent + com.github.aenniw + 3.2-SNAPSHOT + + jrobot-karaf + karaf-assembly + + + + org.apache.karaf.features + framework + kar + + + org.apache.karaf.features + standard + features + xml + runtime + + + com.github.aenniw + jrobot-features + ${project.version} + features + xml + runtime + + + + + + + org.apache.karaf.tooling + karaf-maven-plugin + true + + + standard + jrobot-remote-server + + + + + org.robotframework + robotframework-maven-plugin + + + + run + + + + + + + diff --git a/jrobot-karaf/src/test/robotframework/acceptance/010_feature_tests.robot b/jrobot-karaf/src/test/robotframework/acceptance/010_feature_tests.robot new file mode 100644 index 0000000..cd966a9 --- /dev/null +++ b/jrobot-karaf/src/test/robotframework/acceptance/010_feature_tests.robot @@ -0,0 +1,20 @@ +*** Settings *** +Documentation Test suite to verify OSGI capabilities of jrobot-remoe-server +Suite Setup Start Karaf +Suite Teardown Stop Karaf +Resource ../karaf_keywords.robot + +*** Variables *** + +*** Test Cases *** +JRobot Feature Test + [Documentation] Tests if jrobot-remote-server feature is deployable + Verify Feature Installed On Karaf jrobot-remote-server + Verify Feature Started On Karaf jrobot-remote-server + +JRobot Library Test + [Documentation] Tests if jrobot-remote-server feature accepts bundled libraries + Install Bundle On Karaf mvn:com.github.aenniw/jrobot-test-library + Verify Bundle Installed On Karaf jrobot-test-library + Start Bundle On Karaf jrobot-test-library + Verify Bundle Started On Karaf jrobot-test-library diff --git a/jrobot-karaf/src/test/robotframework/karaf_keywords.robot b/jrobot-karaf/src/test/robotframework/karaf_keywords.robot new file mode 100644 index 0000000..54b9c04 --- /dev/null +++ b/jrobot-karaf/src/test/robotframework/karaf_keywords.robot @@ -0,0 +1,82 @@ +*** Settings *** +Documentation Resource containing keywords manipulating with apache.karaf +Library OperatingSystem + +*** Variables *** +${KARAF_ROOT} ./jrobot-karaf/target/assembly + +*** Keywords *** +Start Karaf + [Documentation] Starts karaf container instance + ${rc} Run and Return RC ${KARAF_ROOT}/bin/start.bat + ${rc} Run Keyword If ${rc} != 0 Run and Return RC ${KARAF_ROOT}/bin/start + Should Be Equal As Integers ${rc} 0 + Wait Until Keyword Succeeds 10 1 Karaf Status Running + #Let the karaf properly start + Sleep 2s + +Stop Karaf + [Documentation] Stops karaf container instance + ${rc} Run and Return RC ${KARAF_ROOT}/bin/stop.bat + ${rc} Run Keyword If ${rc} != 0 Run and Return RC ${KARAF_ROOT}/bin/stop + Should Be Equal As Integers ${rc} 0 + Wait Until Keyword Succeeds 10 1 Karaf Status Not Running + +Karaf Status + [Arguments] ${expected_status} + [Documentation] Checks status of karaf container + ${output} Run ${KARAF_ROOT}/bin/status.bat + ${output} Run Keyword If '${expected_status}' not in '${output}' run ${KARAF_ROOT}/bin/status + Should Contain ${output} ${expected_status} + +Run On Karaf + [Arguments] ${cmd} + [Documentation] Issue command on karaf console + ${rc} ${output} Run and Return RC and Output ${KARAF_ROOT}/bin/client.bat "${cmd}" + ${rc} ${output} Run Keyword If ${rc} != 0 run and return rc and output ${KARAF_ROOT}/bin/client "${cmd}" + Should Be Equal As Integers ${rc} 0 + [Return] ${output} + +Install Feature On Karaf + [Arguments] ${feature_name} + [Documentation] Install specified feature + Run On Karaf feature:install ${feature_name} + +Install Bundle On Karaf + [Arguments] ${bundle_uri} + [Documentation] Install bundle specified with URI + Run On Karaf bundle:install ${bundle_uri} + +Start Feature On Karaf + [Arguments] ${feature_name} + [Documentation] Start already installed feature + Run On Karaf feature:start ${feature_name} + +Start Bundle On Karaf + [Arguments] ${bundle_name} + [Documentation] Start already installed bundle + Run On Karaf bundle:start ${bundle_name} + +Verify Feature Installed On Karaf + [Arguments] ${feature_name} + [Documentation] Checks if feature was installed + ${output} Run On Karaf feature:list -i + Should Contain ${output} ${feature_name} + +Verify Bundle Installed On Karaf + [Arguments] ${bundle_name} + [Documentation] Checks if bundle was installed + ${output} Run On Karaf bundle:list | grep ${bundle_name} + Should Contain ${output} Installed + +Verify Feature Started On Karaf + [Arguments] ${feature_name} + [Documentation] Checks if feature was started + ${output} Run On Karaf feature:list -i | grep ${feature_name} + Should Contain ${output} Started + +Verify Bundle Started On Karaf + [Arguments] ${bundle_name} + [Documentation] Checks if bundle was started + ${output} Run On Karaf bundle:list | grep ${bundle_name} + Should Contain ${output} Active diff --git a/jrobot-remote-server/pom.xml b/jrobot-remote-server/pom.xml new file mode 100644 index 0000000..66431d1 --- /dev/null +++ b/jrobot-remote-server/pom.xml @@ -0,0 +1,114 @@ + + + 4.0.0 + + jrobot-parent + com.github.aenniw + 3.2-SNAPSHOT + + jrobot-remote-server + bundle + + + org.apache.aries.blueprint + org.apache.aries.blueprint + + + + org.apache.xmlrpc + xmlrpc-server + + + + org.robotframework + javalib-core + + + + org.apache.ws.commons.util + ws-commons-util + + + org.eclipse.jetty + jetty-servlet + + + org.apache.commons + commons-lang3 + + + log4j + log4j + + + org.apache.xmlrpc + xmlrpc-client + test + + + org.testng + testng + test + + + org.jboss.resteasy + tjws + test + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + + jar + + + + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.groupId}.${project.artifactId} + + !org.apache.commons.lang3.*, + !org.apache.ws.commons.*, + !org.robotframework.*, + !org.apache.xmlrpc.*, + * + + + org.apache.commons.lang3.*, + org.apache.ws.commons.*, + org.robotframework.*, + org.apache.xmlrpc.* + + + *;artifactId=xmlrpc-server|javalib-core|ws-commons-util + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + + diff --git a/src/main/java/org/robotframework/remoteserver/RemoteServer.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServer.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/RemoteServer.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServer.java diff --git a/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java diff --git a/src/main/java/org/robotframework/remoteserver/cli/CommandLineHelper.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/cli/CommandLineHelper.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/cli/CommandLineHelper.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/cli/CommandLineHelper.java diff --git a/src/main/java/org/robotframework/remoteserver/context/RemoteServerContext.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/context/RemoteServerContext.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/context/RemoteServerContext.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/context/RemoteServerContext.java diff --git a/src/main/java/org/robotframework/remoteserver/javalib/KeywordOverload.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/KeywordOverload.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/javalib/KeywordOverload.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/KeywordOverload.java diff --git a/src/main/java/org/robotframework/remoteserver/javalib/OverloadableKeyword.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/OverloadableKeyword.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/javalib/OverloadableKeyword.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/OverloadableKeyword.java diff --git a/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractor.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractor.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractor.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractor.java diff --git a/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactory.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactory.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactory.java diff --git a/src/main/java/org/robotframework/remoteserver/javalib/SingleClassLibrary.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SingleClassLibrary.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/javalib/SingleClassLibrary.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SingleClassLibrary.java diff --git a/src/main/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactory.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactory.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactory.java diff --git a/src/main/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibrary.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibrary.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibrary.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibrary.java diff --git a/src/main/java/org/robotframework/remoteserver/library/RemoteLibrary.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibrary.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/library/RemoteLibrary.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibrary.java diff --git a/src/main/java/org/robotframework/remoteserver/library/RemoteLibraryFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibraryFactory.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/library/RemoteLibraryFactory.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibraryFactory.java diff --git a/src/main/java/org/robotframework/remoteserver/library/StaticApiRemoteLibrary.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/StaticApiRemoteLibrary.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/library/StaticApiRemoteLibrary.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/StaticApiRemoteLibrary.java diff --git a/src/main/java/org/robotframework/remoteserver/logging/Jetty2Log4J.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/logging/Jetty2Log4J.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/logging/Jetty2Log4J.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/logging/Jetty2Log4J.java diff --git a/src/main/java/org/robotframework/remoteserver/servlet/IllegalPathException.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/IllegalPathException.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/servlet/IllegalPathException.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/IllegalPathException.java diff --git a/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerRequestProcessorFactoryFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerRequestProcessorFactoryFactory.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/servlet/RemoteServerRequestProcessorFactoryFactory.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerRequestProcessorFactoryFactory.java diff --git a/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java diff --git a/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java diff --git a/src/main/java/org/robotframework/remoteserver/xmlrpc/ByteArrayToStringParser.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/ByteArrayToStringParser.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/xmlrpc/ByteArrayToStringParser.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/ByteArrayToStringParser.java diff --git a/src/main/java/org/robotframework/remoteserver/xmlrpc/IterableSerializer.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/IterableSerializer.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/xmlrpc/IterableSerializer.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/IterableSerializer.java diff --git a/src/main/java/org/robotframework/remoteserver/xmlrpc/MapSerializer.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/MapSerializer.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/xmlrpc/MapSerializer.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/MapSerializer.java diff --git a/src/main/java/org/robotframework/remoteserver/xmlrpc/ReflectiveHandlerMapping.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/ReflectiveHandlerMapping.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/xmlrpc/ReflectiveHandlerMapping.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/ReflectiveHandlerMapping.java diff --git a/src/main/java/org/robotframework/remoteserver/xmlrpc/StringSerializer.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/StringSerializer.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/xmlrpc/StringSerializer.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/StringSerializer.java diff --git a/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java similarity index 100% rename from src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java diff --git a/jrobot-remote-server/src/main/resources/OSGI-INF/blueprint/jrobot-remote-server.xml b/jrobot-remote-server/src/main/resources/OSGI-INF/blueprint/jrobot-remote-server.xml new file mode 100644 index 0000000..0d55008 --- /dev/null +++ b/jrobot-remote-server/src/main/resources/OSGI-INF/blueprint/jrobot-remote-server.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + diff --git a/src/test/java/org/robotframework/remoteserver/RemoteLibraryClient.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteLibraryClient.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/RemoteLibraryClient.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteLibraryClient.java diff --git a/src/test/java/org/robotframework/remoteserver/RemoteServerImplTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteServerImplTest.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/RemoteServerImplTest.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteServerImplTest.java diff --git a/src/test/java/org/robotframework/remoteserver/cli/CommandLineHelpertTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/cli/CommandLineHelpertTest.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/cli/CommandLineHelpertTest.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/cli/CommandLineHelpertTest.java diff --git a/src/test/java/org/robotframework/remoteserver/javalib/OverloadableKeywordTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/OverloadableKeywordTest.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/javalib/OverloadableKeywordTest.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/OverloadableKeywordTest.java diff --git a/src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractorTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractorTest.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractorTest.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractorTest.java diff --git a/src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactoryTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactoryTest.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactoryTest.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactoryTest.java diff --git a/src/test/java/org/robotframework/remoteserver/javalib/SingleClassLibraryTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SingleClassLibraryTest.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/javalib/SingleClassLibraryTest.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SingleClassLibraryTest.java diff --git a/src/test/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactoryTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactoryTest.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactoryTest.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactoryTest.java diff --git a/src/test/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibraryTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibraryTest.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibraryTest.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibraryTest.java diff --git a/src/test/java/org/robotframework/remoteserver/library/StaticApiRemoteLibraryTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/StaticApiRemoteLibraryTest.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/library/StaticApiRemoteLibraryTest.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/StaticApiRemoteLibraryTest.java diff --git a/src/test/java/org/robotframework/remoteserver/servlet/AlternativeContainerTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/servlet/AlternativeContainerTest.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/servlet/AlternativeContainerTest.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/servlet/AlternativeContainerTest.java diff --git a/src/test/java/org/robotframework/remoteserver/servlet/RemoteServerServletTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/servlet/RemoteServerServletTest.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/servlet/RemoteServerServletTest.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/servlet/RemoteServerServletTest.java diff --git a/src/test/java/org/robotframework/remoteserver/testlibraries/ConflictingOverloadVariableArguments.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/ConflictingOverloadVariableArguments.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/testlibraries/ConflictingOverloadVariableArguments.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/ConflictingOverloadVariableArguments.java diff --git a/src/test/java/org/robotframework/remoteserver/testlibraries/DuplicateKeywords.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DuplicateKeywords.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/testlibraries/DuplicateKeywords.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DuplicateKeywords.java diff --git a/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargs.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargs.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargs.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargs.java diff --git a/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargsList.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargsList.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargsList.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargsList.java diff --git a/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordNoKwargs.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordNoKwargs.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordNoKwargs.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordNoKwargs.java diff --git a/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicUsingLists.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicUsingLists.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/testlibraries/DynamicUsingLists.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicUsingLists.java diff --git a/src/test/java/org/robotframework/remoteserver/testlibraries/OverloadedMethods.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/OverloadedMethods.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/testlibraries/OverloadedMethods.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/OverloadedMethods.java diff --git a/src/test/java/org/robotframework/remoteserver/testlibraries/StaticOne.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/StaticOne.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/testlibraries/StaticOne.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/StaticOne.java diff --git a/src/test/java/org/robotframework/remoteserver/testlibraries/StaticTwo.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/StaticTwo.java similarity index 100% rename from src/test/java/org/robotframework/remoteserver/testlibraries/StaticTwo.java rename to jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/StaticTwo.java diff --git a/jrobot-test-library/pom.xml b/jrobot-test-library/pom.xml new file mode 100644 index 0000000..1dab5da --- /dev/null +++ b/jrobot-test-library/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + + jrobot-parent + com.github.aenniw + 3.2-SNAPSHOT + + jrobot-test-library + bundle + + + com.github.aenniw + jrobot-remote-server + ${project.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + + jar + + + + + + org.apache.felix + maven-bundle-plugin + true + + + org.codehaus.mojo + build-helper-maven-plugin + + + + diff --git a/jrobot-test-library/src/main/java/org/robotframework/test/TestLibrary.java b/jrobot-test-library/src/main/java/org/robotframework/test/TestLibrary.java new file mode 100644 index 0000000..05992b1 --- /dev/null +++ b/jrobot-test-library/src/main/java/org/robotframework/test/TestLibrary.java @@ -0,0 +1,11 @@ +package org.robotframework.test; + +import org.robotframework.remoteserver.RemoteServer; + +public class TestLibrary { + + public TestLibrary(RemoteServer server) { + server.putLibrary("/" + getClass().getSimpleName(), this); + } + +} diff --git a/jrobot-test-library/src/main/resources/OSGI-INF/blueprint/jrobot-test-library.xml b/jrobot-test-library/src/main/resources/OSGI-INF/blueprint/jrobot-test-library.xml new file mode 100644 index 0000000..b5e0cbc --- /dev/null +++ b/jrobot-test-library/src/main/resources/OSGI-INF/blueprint/jrobot-test-library.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/pom.xml b/pom.xml index 0da43ca..f0ccf86 100644 --- a/pom.xml +++ b/pom.xml @@ -1,157 +1,164 @@ - - 4.0.0 - com.github.aenniw - jrobotremoteserver - 3.2-SNAPSHOT - bundle - jrobotremoteserver - https://github.com/aenniw/jrobotremoteserver - - - Apache 2 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - Kevin Ormbrek - kormbrek@gmail.com - - - David Luu - mangaroo@gmail.com - - - Martin Mihálek - aenniw@gmail.com - - - - org.sonatype.oss - oss-parent - 7 - - - UTF-8 - - - - org.apache.aries.blueprint - org.apache.aries.blueprint - 1.1.0 - - - - org.apache.xmlrpc - xmlrpc-server - 3.1.3 - - - - org.robotframework - javalib-core - 1.2.1 - - - - org.apache.ws.commons.util - ws-commons-util - 1.0.2 - - - org.eclipse.jetty - jetty-servlet - 8.0.4.v20111024 - - - org.apache.commons - commons-lang3 - 3.4 - - - log4j - log4j - 1.2.16 - - - org.apache.xmlrpc - xmlrpc-client - 3.1.3 - test - - - org.testng - testng - 6.3.1 - test - - - org.jboss.resteasy - tjws - 2.3.2.Final - test - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8.1 - - - - jar - - - - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.groupId}.${project.artifactId} - - !org.apache.commons.lang3.*, - !org.apache.ws.commons.*, - !org.robotframework.*, - !org.apache.xmlrpc.*, - * - - - org.apache.commons.lang3.*, - org.apache.ws.commons.*, - org.robotframework.*, - org.apache.xmlrpc.* - - - *;artifactId=xmlrpc-server|javalib-core|ws-commons-util - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - - Serves remote test libraries for Robot Framework that are implemented in Java. - - scm:git:git@github.com:aenniw/jrobotremoteserver.git - scm:git:git@github.com:aenniw/jrobotremoteserver.git - git@github.com:aenniw/jrobotremoteserver.git - + + 4.0.0 + com.github.aenniw + jrobot-parent + 3.2-SNAPSHOT + + jrobot-remote-server + jrobot-test-library + jrobot-features + jrobot-karaf + + pom + https://github.com/aenniw/jrobotremoteserver + + + Apache 2 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + Kevin Ormbrek + kormbrek@gmail.com + + + David Luu + mangaroo@gmail.com + + + Martin Mihálek + aenniw@gmail.com + + + + org.sonatype.oss + oss-parent + 7 + + + UTF-8 + + + + + org.apache.aries.blueprint + org.apache.aries.blueprint + 1.1.0 + + + + org.apache.xmlrpc + xmlrpc-server + 3.1.3 + + + + org.robotframework + javalib-core + 1.2.1 + + + + org.apache.ws.commons.util + ws-commons-util + 1.0.2 + + + org.eclipse.jetty + jetty-servlet + 8.0.4.v20111024 + + + org.apache.commons + commons-lang3 + 3.4 + + + log4j + log4j + 1.2.16 + + + org.apache.xmlrpc + xmlrpc-client + 3.1.3 + test + + + org.testng + testng + 6.3.1 + test + + + org.jboss.resteasy + tjws + 2.3.2.Final + test + + + org.apache.karaf.features + framework + 4.0.6 + kar + + + org.apache.karaf.features + standard + features + 4.0.6 + xml + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + org.apache.felix + maven-bundle-plugin + 3.2.0 + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + org.apache.maven.plugins + maven-resources-plugin + 3.0.1 + + + org.apache.karaf.tooling + karaf-maven-plugin + 4.0.6 + + + org.robotframework + robotframework-maven-plugin + 1.4.6 + + + + + Serves remote test libraries for Robot Framework that are implemented in Java. + + scm:git:git@github.com:aenniw/jrobotremoteserver.git + scm:git:git@github.com:aenniw/jrobotremoteserver.git + git@github.com:aenniw/jrobotremoteserver.git + diff --git a/src/main/resources/OSGI-INF/blueprint/remote-server.xml b/src/main/resources/OSGI-INF/blueprint/remote-server.xml deleted file mode 100644 index 6804b44..0000000 --- a/src/main/resources/OSGI-INF/blueprint/remote-server.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - From 852409f7ac38a300ad274c704dc9f78747e801d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Mih=C3=A1lek?= Date: Wed, 28 Sep 2016 18:24:11 +0200 Subject: [PATCH 02/11] Remove Depricated API, code format MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Martin Mihálek --- .../remoteserver/RemoteServerImpl.java | 149 ++---------------- .../remoteserver/cli/CommandLineHelper.java | 112 ++++++------- .../context/RemoteServerContext.java | 53 +++---- .../remoteserver/javalib/KeywordOverload.java | 75 +++++---- .../javalib/OverloadableKeyword.java | 20 +-- .../javalib/SimpleKeywordExtractor.java | 8 +- .../javalib/SimpleKeywordFactory.java | 8 +- .../javalib/SingleClassLibrary.java | 17 +- .../library/DefaultRemoteLibraryFactory.java | 39 ++--- .../library/DynamicApiRemoteLibrary.java | 23 ++- .../remoteserver/library/RemoteLibrary.java | 43 +++-- .../library/RemoteLibraryFactory.java | 3 +- .../library/StaticApiRemoteLibrary.java | 19 +-- .../remoteserver/logging/Jetty2Log4J.java | 90 +++++------ .../servlet/IllegalPathException.java | 3 +- ...eServerRequestProcessorFactoryFactory.java | 8 +- .../servlet/RemoteServerServlet.java | 105 ++++++------ .../remoteserver/servlet/ServerMethods.java | 54 +++---- .../xmlrpc/ByteArrayToStringParser.java | 3 +- .../xmlrpc/IterableSerializer.java | 15 +- .../remoteserver/xmlrpc/MapSerializer.java | 51 +++--- .../xmlrpc/ReflectiveHandlerMapping.java | 47 +++--- .../remoteserver/xmlrpc/StringSerializer.java | 4 +- .../remoteserver/xmlrpc/TypeFactory.java | 21 ++- .../remoteserver/RemoteServerImplTest.java | 26 --- .../javalib/OverloadableKeywordTest.java | 4 +- .../library/DynamicApiRemoteLibraryTest.java | 7 +- .../DynamicOneRunKeywordKwargsList.java | 2 +- .../testlibraries/DynamicUsingLists.java | 4 +- 29 files changed, 404 insertions(+), 609 deletions(-) diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java index 585e56a..a5d83dd 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java @@ -17,18 +17,12 @@ import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.log4j.BasicConfigurator; -import org.apache.log4j.Level; -import org.apache.log4j.Logger; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; -import org.robotframework.remoteserver.cli.CommandLineHelper; import org.robotframework.remoteserver.library.RemoteLibrary; -import org.robotframework.remoteserver.logging.Jetty2Log4J; -import org.robotframework.remoteserver.servlet.IllegalPathException; import org.robotframework.remoteserver.servlet.RemoteServerServlet; /** @@ -40,9 +34,9 @@ * @see jrobotremoteserver wiki * @see Remote Library wiki page * @see User - * Guide for Robot Framework + * Guide for Robot Framework * @see XML-RPC - * Specification + * Specification */ public class RemoteServerImpl implements RemoteServer { @@ -53,7 +47,7 @@ public class RemoteServerImpl implements RemoteServer { public RemoteServerImpl() { connector.setName("jrobotremoteserver"); - server.setConnectors(new Connector[] { connector }); + server.setConnectors(new Connector[] {connector}); ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/", false, false); servletContextHandler.addServlet(new ServletHolder(servlet), "/"); } @@ -62,7 +56,7 @@ public RemoteServerImpl() { * Returns the actual port the server is listening on. * * @return The actual port the server's connector is listening on or -1 if - * it has not been opened, or -2 if it has been closed. + * it has not been opened, or -2 if it has been closed. */ public int getPort() { return connector.getLocalPort(); @@ -71,9 +65,8 @@ public int getPort() { /** * Sets the port to listen on. * - * @param port - * The port to listen on for connections or 0 if any available - * port may be used. Defaults port is 0. + * @param port The port to listen on for connections or 0 if any available + * port may be used. Defaults port is 0. */ public void setPort(int port) { connector.setPort(port); @@ -91,8 +84,7 @@ public boolean getAllowStop() { /** * Allow or disallow stopping the server remotely. * - * @param allowed - * true to allow stopping the server remotely + * @param allowed true to allow stopping the server remotely */ public void setAllowStop(boolean allowed) { servlet.setAllowStop(allowed); @@ -112,49 +104,13 @@ public String getHost() { * determined automatically. For exotic network configuration, network with * VPN, specifying the host might be necessary. * - * @param hostName - * the hostname or address representing the interface to which - * all connectors will bind, or null for all interfaces. + * @param hostName the hostname or address representing the interface to which + * all connectors will bind, or null for all interfaces. */ public void setHost(String hostName) { connector.setHost(hostName); } - /** - * Main method for command line usage. - * - * @param args - * @throws Exception If server cannot be started - */ - public static void main(String[] args) throws Exception { - configureLogging(); - CommandLineHelper helper = new CommandLineHelper(args); - if (helper.getHelpRequested()) { - System.out.print(helper.getUsage()); - System.exit(0); - } - RemoteServerImpl remoteServer = new RemoteServerImpl(); - String error = helper.getError(); - if (error == null) { - try { - for (String path : helper.getLibraryMap().keySet()) - remoteServer.putLibrary(path, helper.getLibraryMap().get(path)); - } catch (IllegalPathException e) { - error = e.getMessage(); - } - } - if (error != null) { - System.out.println("Error: " + error); - System.out.println(); - System.out.println(helper.getUsage()); - System.exit(1); - } - remoteServer.setPort(helper.getPort()); - remoteServer.setAllowStop(helper.getAllowStop()); - remoteServer.setHost(helper.getHost()); - remoteServer.start(); - } - @Override public RemoteLibrary putLibrary(String path, Object library) { RemoteLibrary oldLibrary = servlet.putLibrary(path, library); String name = servlet.getLibraryMap().get(path).getName(); @@ -170,69 +126,13 @@ public static void main(String[] args) throws Exception { return servlet.getLibraryMap(); } - /** - * This has been deprecated. Please use {@link #putLibrary} and - * {@link #setPort} instead. - * - * Map the given test library to / and sets the port for the server. The - * server must be stopped when calling this. - * - * @param className - * class name of the test library - * @param port - * port for the server to listen on - */ - @Deprecated - public void addLibrary(String className, int port) { - Class clazz; - try { - clazz = Class.forName(className); - } catch (Exception e) { - throw new RuntimeException(e); - } - addLibrary(clazz, port); - } - - /** - * This has been deprecated. Please use {@link #putLibrary} and - * {@link #setPort} instead. - * - * Map the given test library to / and sets the port for the server. The - * server must be stopped when calling this. - * - * @param clazz - * class of the test library - * @param port - * port for the server to listen on - */ - @Deprecated - public void addLibrary(Class clazz, int port) { - if (!server.isStopped()) // old behavior - throw new IllegalStateException("Cannot add a library once the server is started"); - if (connector.getPort() != 0 && connector.getPort() != port) { - throw new RuntimeException( - "Serving on multiple ports is no longer supported. Please use putLibrary with different paths instead."); - } - if (servlet.getLibraryMap().keySet().contains("/")) { - throw new RuntimeException("A library has already been mapped to /."); - } - Object library; - try { - library = clazz.newInstance(); - } catch (Exception e) { - throw new RuntimeException(e); - } - setPort(port); - putLibrary("/", library); - } - @Override public void stop(int timeoutMS) throws Exception { log.info("Robot Framework remote server stopping"); if (timeoutMS > 0) { server.setGracefulShutdown(timeoutMS); Thread stopper = new Thread() { - @Override - public void run() { + + @Override public void run() { try { server.stop(); } catch (Throwable e) { @@ -255,31 +155,4 @@ public void run() { server.start(); log.info(String.format("Robot Framework remote server started on port %d.", getPort())); } - - /** - * Configures logging systems used by RemoteServer and its - * dependencies. Specifically, - *
    - *
  • Configure Log4J to log to the console
  • - *
  • Set Log4J's log level to INFO
  • - *
  • Redirect the Jetty's logging to Log4J
  • - *
  • Set Jakarta Commons Logging to log to Log4J
  • - *
- * This is convenient if you do not want to configure the logging yourself. - * This will only affect future instances of - * {@link org.eclipse.jetty.util.log.Logger} and - * {@link org.apache.commons.logging.Log}, so this should be called as early - * as possible. - */ - public static void configureLogging() { - Logger root = Logger.getRootLogger(); - root.removeAllAppenders(); - BasicConfigurator.configure(); - root.setLevel(Level.INFO); - org.eclipse.jetty.util.log.Log.setLog(new Jetty2Log4J()); - LogFactory.releaseAll(); - LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log", - "org.apache.commons.logging.impl.Log4JLogger"); - log = LogFactory.getLog(RemoteServer.class); - } } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/cli/CommandLineHelper.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/cli/CommandLineHelper.java index c1b9191..27f0100 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/cli/CommandLineHelper.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/cli/CommandLineHelper.java @@ -20,7 +20,7 @@ public class CommandLineHelper { - private Map libraryMap = new HashMap(); + private Map libraryMap = new HashMap<>(); private boolean allowStop = true; private String host = null; private String error = null; @@ -30,45 +30,6 @@ public class CommandLineHelper { private int port = 0; private boolean usedOldLibraryOption = false; - public boolean getAllowStop() { - return allowStop; - } - - public String getHost() { - return host; - } - - public int getPort() { - return port; - } - - public Map getLibraryMap() { - return libraryMap; - } - - public String getError() { - return error; - } - - public boolean getHelpRequested() { - return helpRequested; - } - - public String getUsage() { - return "Usage: org.robotframework.remoteserver.RemoteServer options\n\n" + // - "Options:\n" + // - // ////////////////////////////////////////////////////////////////////////////// - " -l --library classname[:path] library to serve and path to map to. Path\n" + // - " has a default value of /. The library option\n" + // - " may be repeated to serve multiple libraries\n" + // - " -p --port port port to bind to, defaults to 0 (ephemeral)\n" + // - " -a --allowstop true|false whether to allow remote stop\n" + // - " -H --host hostname hostname of the interface to bind to\n" + // - " -h -? --help print this help message\n\n" + // - " For backwards compatibility, one library can be added using the form\n" + // - " --library classname:port\n"; - } - public CommandLineHelper(String[] clargs) { args = clargs; try { @@ -111,6 +72,61 @@ else if (value.equalsIgnoreCase("true")) } } + public boolean getAllowStop() { + return allowStop; + } + + public String getHost() { + return host; + } + + public int getPort() { + return port; + } + + private void setPort(String portString) { + if (usedOldLibraryOption) { + throw new RuntimeException( + "Cannot use the port option or use multiple libraries when specifying libraries in the form classname:port"); + } + int port; + try { + port = Integer.valueOf(portString.trim()); + if (port < 1 || port > 65535) + throw new Exception(); + } catch (Exception e) { + throw new RuntimeException("Port must be 1-65535"); + } + this.port = port; + } + + public Map getLibraryMap() { + return libraryMap; + } + + public String getError() { + return error; + } + + public boolean getHelpRequested() { + return helpRequested; + } + + public String getUsage() { + return "Usage: org.robotframework.remoteserver.RemoteServer options\n\n" + // + "Options:\n" + // + // ////////////////////////////////////////////////////////////////////////////// + " -l --library classname[:path] library to serve and path to map to. Path\n" + // + " has a default value of /. The library option\n" + // + " may be repeated to serve multiple libraries\n" + // + " -p --port port port to bind to, defaults to 0 (ephemeral)\n" + // + " -a --allowstop true|false whether to allow remote stop\n" + // + " -H --host hostname hostname of the interface to bind to\n" + // + " -h -? --help print this help message\n\n" + // + " For backwards compatibility, one library can be added using the form\n" + // + " --library classname:port\n"; + } + private String getValue(String name) { if (idx == args.length - 1 || (args[idx + 1].startsWith("-"))) throw new RuntimeException("Missing value for option " + name); @@ -142,20 +158,4 @@ private void putLibrary(String path, String className) { libraryMap.put(path, library); } - private void setPort(String portString) { - if (usedOldLibraryOption) { - throw new RuntimeException( - "Cannot use the port option or use multiple libraries when specifying libraries in the form classname:port"); - } - int port; - try { - port = Integer.valueOf(portString.trim()); - if (port < 1 || port > 65535) - throw new Exception(); - } catch (Exception e) { - throw new RuntimeException("Port must be 1-65535"); - } - this.port = port; - } - } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/context/RemoteServerContext.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/context/RemoteServerContext.java index 1822b1e..05631a8 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/context/RemoteServerContext.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/context/RemoteServerContext.java @@ -15,37 +15,42 @@ package org.robotframework.remoteserver.context; import java.util.Map; - import javax.servlet.http.HttpServletRequest; - import org.robotframework.remoteserver.library.RemoteLibrary; public interface RemoteServerContext { /** * Returns true if this server allows remote stopping. - * + * * @return true if this server allows remote stopping */ - public boolean getAllowStop(); + boolean getAllowStop(); + + /** + * Allow or disallow stopping the server remotely. + * + * @param allowed true to allow stopping the server remotely + */ + void setAllowStop(boolean allowed); /** * Gets a copy of the current library map. Keys in the map are the paths and * the values are {@link RemoteLibrary} wrappers of the libraries being * served. - * + * * @return a copy of the current library map */ - public Map getLibraryMap(); + Map getLibraryMap(); /** * Returns a {@link HttpServletRequest} object that contains the request the * client has made of the remote server servlet. - * + * * @return {@link HttpServletRequest} object that contains the request the - * client has made of the remote server servlet + * client has made of the remote server servlet */ - public HttpServletRequest getRequest(); + HttpServletRequest getRequest(); /** * Map the given test library to the specified path. Paths must: @@ -55,34 +60,22 @@ public interface RemoteServerContext { *
  • not end in a /
  • *
  • not contain a repeating sequence of /s
  • * - * * Example: putLibrary("/myLib", new MyLibrary()); - * - * @param library - * instance of the test library - * @param path - * path to map the test library to + * + * @param library instance of the test library + * @param path path to map the test library to * @return the previous library mapped to the path, or null if there was no - * mapping for the path + * mapping for the path */ - public RemoteLibrary putLibrary(String path, Object library); + RemoteLibrary putLibrary(String path, Object library); /** * Removes the library mapped to the given path if the mapping exists - * - * @param path - * path for the library whose mapping is to be removed + * + * @param path path for the library whose mapping is to be removed * @return the previous library associated with the path, or null if there - * was no mapping for the path. - */ - public RemoteLibrary removeLibrary(String path); - - /** - * Allow or disallow stopping the server remotely. - * - * @param allowed - * true to allow stopping the server remotely + * was no mapping for the path. */ - public void setAllowStop(boolean allowed); + RemoteLibrary removeLibrary(String path); } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/KeywordOverload.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/KeywordOverload.java index 61991a8..6d65017 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/KeywordOverload.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/KeywordOverload.java @@ -17,9 +17,7 @@ */ package org.robotframework.remoteserver.javalib; - import java.lang.reflect.Method; - import org.robotframework.javalib.keyword.Keyword; import org.robotframework.javalib.reflection.ArgumentConverter; import org.robotframework.javalib.reflection.ArgumentGrouper; @@ -28,46 +26,45 @@ public class KeywordOverload implements Keyword { - private final Method method; - private final Object obj; + private final Method method; + private final Object obj; + + public KeywordOverload(Object obj, Method method) { + this.obj = obj; + this.method = method; + } - public KeywordOverload(Object obj, Method method) { - this.obj = obj; - this.method = method; - } + public Object execute(Object[] args) { + try { + Object[] groupedArguments = createArgumentGrouper().groupArguments(args); + Object[] convertedArguments = createArgumentConverter().convertArguments(groupedArguments); + return method.invoke(obj, convertedArguments); + } catch (Exception e) { + throw new RuntimeException(e); + } + } - public Object execute(Object[] args) { - try { - Object[] groupedArguments = createArgumentGrouper().groupArguments(args); - Object[] convertedArguments = createArgumentConverter().convertArguments(groupedArguments); - return method.invoke(obj, convertedArguments); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + public boolean canExecute(Object[] args) { + try { + Object[] groupedArguments = createArgumentGrouper().groupArguments(args); + Object[] convertedArguments = createArgumentConverter().convertArguments(groupedArguments); + for (int i = 0; i < args.length; i++) { + if ((convertedArguments[i] == null) && (args[i] != null)) { + return false; + } + } + return true; + } catch (Exception e) { + return false; + } + } - public boolean canExecute(Object[] args) { - try { - Object[] groupedArguments = createArgumentGrouper().groupArguments(args); - Object[] convertedArguments = createArgumentConverter().convertArguments(groupedArguments); - for (int i = 0; i < args.length; i++) { - if ( (convertedArguments[i] == null) && (args[i] != null) ) { - return false; - } - } - return true; - } - catch (Exception e) { - return false; - } - } + protected IArgumentConverter createArgumentConverter() { + return new ArgumentConverter(method.getParameterTypes()); + } - protected IArgumentConverter createArgumentConverter() { - return new ArgumentConverter(method.getParameterTypes()); - } - - protected IArgumentGrouper createArgumentGrouper() { - return new ArgumentGrouper(method.getParameterTypes()); - } + protected IArgumentGrouper createArgumentGrouper() { + return new ArgumentGrouper(method.getParameterTypes()); + } } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/OverloadableKeyword.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/OverloadableKeyword.java index 156f2e4..9f3bacc 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/OverloadableKeyword.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/OverloadableKeyword.java @@ -22,18 +22,17 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.robotframework.javalib.keyword.Keyword; public class OverloadableKeyword implements Keyword { - private Map> keywordMap = new HashMap>(); + private static Log log = LogFactory.getLog(OverloadableKeyword.class); + private Map> keywordMap = new HashMap<>(); private String name; private Object keywordBean; private boolean usesVarArgs = false; - private static Log log = LogFactory.getLog(OverloadableKeyword.class); public OverloadableKeyword(Object keywordBean, Method method) { name = method.getName(); @@ -60,17 +59,18 @@ public Object execute(Object[] arguments) { } } if (selectedKeyword == null) { - throw new IllegalArgumentException(String.format("No overload of %s can take the given arguments", - name)); + throw new IllegalArgumentException( + String.format("No overload of %s can take the given arguments", name)); } } } else { if (keywordMap.size() == 1) { - throw new IllegalArgumentException(String.format("%s takes %d argument(s), received %d.", name, - keywordMap.keySet().toArray()[0], argCount)); + throw new IllegalArgumentException( + String.format("%s takes %d argument(s), received %d.", name, keywordMap.keySet().toArray()[0], + argCount)); } else { - throw new IllegalArgumentException(String.format("No overload of %s takes %d argument(s).", name, - argCount)); + throw new IllegalArgumentException( + String.format("No overload of %s takes %d argument(s).", name, argCount)); } } return selectedKeyword.execute(arguments); @@ -85,7 +85,7 @@ public void addOverload(Method method) { } else if (keywordMap.containsKey(argCount)) { keywordMap.get(argCount).add(new KeywordOverload(keywordBean, method)); } else { - List overloadList = new ArrayList(); + List overloadList = new ArrayList<>(); overloadList.add(new KeywordOverload(keywordBean, method)); keywordMap.put(argCount, overloadList); } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractor.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractor.java index 00db6a5..e926167 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractor.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractor.java @@ -21,13 +21,12 @@ import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; - import org.robotframework.javalib.beans.annotation.IKeywordExtractor; public class SimpleKeywordExtractor implements IKeywordExtractor { public Map extractKeywords(Object keywordBean) { - Map overloadableKeywords = new HashMap(); + Map overloadableKeywords = new HashMap<>(); Method[] methods = keywordBean.getClass().getMethods(); for (final Method method : methods) { @@ -38,9 +37,10 @@ public Map extractKeywords(Object keywordBean) { return overloadableKeywords; } - private void createOrUpdateKeyword(Map extractedKeywords, Object keywordBean, Method method) { + private void createOrUpdateKeyword(Map extractedKeywords, Object keywordBean, + Method method) { String name = method.getName(); - if(extractedKeywords.containsKey(name)){ + if (extractedKeywords.containsKey(name)) { extractedKeywords.get(name).addOverload(method); } else { extractedKeywords.put(name, new OverloadableKeyword(keywordBean, method)); diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactory.java index 437a0e1..d8de852 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactory.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactory.java @@ -21,16 +21,16 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - import org.robotframework.javalib.beans.annotation.IKeywordExtractor; import org.robotframework.javalib.factory.KeywordFactory; import org.robotframework.javalib.util.IKeywordNameNormalizer; import org.robotframework.javalib.util.KeywordNameNormalizer; public class SimpleKeywordFactory implements KeywordFactory { - private Map keywords = new HashMap(); + + private Map keywords = new HashMap<>(); private IKeywordNameNormalizer keywordNameNormalizer = new KeywordNameNormalizer(); - private List keywordNames = new ArrayList(); + private List keywordNames = new ArrayList<>(); public SimpleKeywordFactory(Object keywordBean) { extractKeywordsFromKeywordBean(keywordBean); @@ -42,7 +42,7 @@ public OverloadableKeyword createKeyword(String keywordName) { } public String[] getKeywordNames() { - return (String[]) keywordNames.toArray(new String[0]); + return keywordNames.toArray(new String[0]); } protected void extractKeywordsFromKeywordBean(Object keywordBean) { diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SingleClassLibrary.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SingleClassLibrary.java index 7cc0f75..bf38937 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SingleClassLibrary.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SingleClassLibrary.java @@ -18,13 +18,12 @@ package org.robotframework.remoteserver.javalib; import java.lang.reflect.InvocationTargetException; - import org.robotframework.javalib.factory.KeywordFactory; import org.robotframework.javalib.library.KeywordDocumentationRepository; import org.robotframework.javalib.library.KeywordFactoryBasedLibrary; -public class SingleClassLibrary extends KeywordFactoryBasedLibrary implements - KeywordDocumentationRepository { +public class SingleClassLibrary extends KeywordFactoryBasedLibrary + implements KeywordDocumentationRepository { private KeywordFactory keywordFactory; private Object keywordBean; @@ -33,16 +32,14 @@ public SingleClassLibrary(Object keywordBean) { this.keywordBean = keywordBean; } - @Override - protected KeywordFactory createKeywordFactory() { + @Override protected KeywordFactory createKeywordFactory() { if (keywordFactory == null) { keywordFactory = new SimpleKeywordFactory(keywordBean); } return keywordFactory; } - @Override - public Object runKeyword(String keywordName, Object[] args) { + @Override public Object runKeyword(String keywordName, Object[] args) { try { return super.runKeyword(keywordName, args); } catch (RuntimeException e) { @@ -50,13 +47,11 @@ public Object runKeyword(String keywordName, Object[] args) { } } - @Override - public String[] getKeywordArguments(String keywordName) { + @Override public String[] getKeywordArguments(String keywordName) { return createKeywordFactory().createKeyword(keywordName).getArguments(); } - @Override - public String getKeywordDocumentation(String keywordName) { + @Override public String getKeywordDocumentation(String keywordName) { return ""; } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactory.java index 41727fc..cefa82c 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactory.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactory.java @@ -23,6 +23,15 @@ public class DefaultRemoteLibraryFactory implements RemoteLibraryFactory { + private static List[]> runKeywordParamArrays = new ArrayList<>(); + + static { + runKeywordParamArrays.add(new Class[] {String.class, Object[].class, Map.class}); + runKeywordParamArrays.add(new Class[] {String.class, List.class, Map.class}); + runKeywordParamArrays.add(new Class[] {String.class, Object[].class}); + runKeywordParamArrays.add(new Class[] {String.class, List.class}); + } + public RemoteLibrary createRemoteLibrary(Object library) { if (library instanceof RemoteLibrary) { return (RemoteLibrary) library; @@ -40,7 +49,7 @@ public RemoteLibrary createRemoteLibrary(Object library) { } private List getPublicMethods(Class clazz) { - List methods = new ArrayList(); + List methods = new ArrayList<>(); for (Method m : clazz.getMethods()) { if (Modifier.isPublic(m.getModifiers())) { methods.add(m); @@ -51,29 +60,21 @@ private List getPublicMethods(Class clazz) { private Method getGetKeywordNames(List methods) { for (Method m : methods) { - if (((m.getName().equals("getKeywordNames") || (m.getName().equals("get_keyword_names"))) - && (m.getReturnType() == String[].class || m.getReturnType() == List.class) && m - .getParameterTypes().length == 0)) { + if (((m.getName().equals("getKeywordNames") || (m.getName().equals("get_keyword_names"))) && ( + m.getReturnType() == String[].class || m.getReturnType() == List.class) + && m.getParameterTypes().length == 0)) { return m; } } return null; } - private static List[]> runKeywordParamArrays = new ArrayList[]>(); - static { - runKeywordParamArrays.add(new Class[] { String.class, Object[].class, Map.class }); - runKeywordParamArrays.add(new Class[] { String.class, List.class, Map.class }); - runKeywordParamArrays.add(new Class[] { String.class, Object[].class }); - runKeywordParamArrays.add(new Class[] { String.class, List.class }); - } - private Method getRunKeyword(List methods) { Method matchingMethod = null; for (Method m : methods) { Class[] pTypes = m.getParameterTypes(); - if ((m.getName().equals("runKeyword") || m.getName().equals("run_keyword")) - && m.getReturnType().equals(Object.class)) { + if ((m.getName().equals("runKeyword") || m.getName().equals("run_keyword")) && m.getReturnType() + .equals(Object.class)) { for (Class[] paramArray : runKeywordParamArrays) { if (Arrays.equals(pTypes, paramArray)) { if (pTypes.length == 3) { @@ -91,9 +92,9 @@ private Method getRunKeyword(List methods) { private Method getGetKeywordArguments(List methods) { for (Method m : methods) { - if ((m.getName().equals("getKeywordArguments") || m.getName().equals("get_keyword_arguments")) - && (m.getReturnType() == String[].class || m.getReturnType() == List.class) - && Arrays.equals(m.getParameterTypes(), new Class[] { String.class })) + if ((m.getName().equals("getKeywordArguments") || m.getName().equals("get_keyword_arguments")) && ( + m.getReturnType() == String[].class || m.getReturnType() == List.class) && Arrays.equals( + m.getParameterTypes(), new Class[] {String.class})) return m; } return null; @@ -102,8 +103,8 @@ private Method getGetKeywordArguments(List methods) { private Method getGetKeywordDocumentation(List methods) { for (Method m : methods) { if ((m.getName().equals("getKeywordDocumentation") || m.getName().equals("get_keyword_documentation")) - && m.getReturnType() == String.class - && Arrays.equals(m.getParameterTypes(), new Class[] { String.class })) + && m.getReturnType() == String.class && Arrays.equals(m.getParameterTypes(), + new Class[] {String.class})) return m; } return null; diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibrary.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibrary.java index 0e73616..5abb7df 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibrary.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibrary.java @@ -21,6 +21,7 @@ import java.util.Map; public class DynamicApiRemoteLibrary implements RemoteLibrary { + private Object library; private Method getKeywordNames; private Method runKeyword; @@ -36,10 +37,9 @@ protected DynamicApiRemoteLibrary(Object library, Method getKeywordNames, Method this.getKeywordDocumentation = getKeywordDocumentation; } - @Override - public String[] getKeywordNames() { + @Override public String[] getKeywordNames() { try { - Object names = getKeywordNames.invoke(library, new Object[] {}); + Object names = getKeywordNames.invoke(library); if (names instanceof List) { return (String[]) ((List) names).toArray(); } else { @@ -50,8 +50,7 @@ public String[] getKeywordNames() { } } - @Override - public Object runKeyword(String keyword, Object[] args, Map kwargs) throws Throwable { + @Override public Object runKeyword(String keyword, Object[] args, Map kwargs) throws Throwable { if (kwargs != null && !kwargs.isEmpty() && runKeyword.getParameterTypes().length == 2) { throw new RuntimeException("This library does not support keyword arguments."); } @@ -68,10 +67,9 @@ public Object runKeyword(String keyword, Object[] args, Map kwar } } - @Override - public String[] getKeywordArguments(String keyword) { + @Override public String[] getKeywordArguments(String keyword) { if (getKeywordArguments == null) - return new String[] { "*args" }; + return new String[] {"*args"}; try { Object args = getKeywordArguments.invoke(library, keyword); if (args instanceof List) { @@ -84,8 +82,7 @@ public String[] getKeywordArguments(String keyword) { } } - @Override - public String getKeywordDocumentation(String keyword) { + @Override public String getKeywordDocumentation(String keyword) { if (getKeywordDocumentation == null) return ""; try { @@ -95,13 +92,11 @@ public String getKeywordDocumentation(String keyword) { } } - @Override - public String getName() { + @Override public String getName() { return library.getClass().getName(); } - @Override - public Object getImplementation() { + @Override public Object getImplementation() { return library; } } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibrary.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibrary.java index b363092..1bd0a3b 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibrary.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibrary.java @@ -19,68 +19,61 @@ /** * An interface for handling libraries in jrobotremoteserver. There is no reason * for libraries to implement this. - *

    * User libraries are wrapped so that they can be handled in the same way. Use * {@link #getImplementation()} to access the wrapped library. - * */ public interface RemoteLibrary { /** * Returns the names of keywords in the library. - * + * * @return The names of keywords in the library. */ - public String[] getKeywordNames(); + String[] getKeywordNames(); /** * Executes the keyword with the given name. As some library implementations * may be case-, space-, or underscore-sensitive, it is best to use the name * as returned from {@link #getKeywordNames()}. - * - * @param name - * name of the keyword to execute - * @param arguments - * positional arguments to the keyword - * @param kwargs - * keyword arguments + * + * @param name name of the keyword to execute + * @param arguments positional arguments to the keyword + * @param kwargs keyword arguments * @return value returned by the keyword */ - public Object runKeyword(String name, Object[] arguments, Map kwargs) throws Throwable; + Object runKeyword(String name, Object[] arguments, Map kwargs) throws Throwable; /** * Gets the argument descriptors for the given keyword name. - * - * @param keyword - * name of the keyword to get argument specifications for + * + * @param keyword name of the keyword to get argument specifications for * @return array of argument specifications */ - public String[] getKeywordArguments(String keyword); + String[] getKeywordArguments(String keyword); /** * Gets the documentation string for the given keyword name. - * - * @param name - * name of the keyword to get documentation for + * + * @param name name of the keyword to get documentation for * @return keyword documentation string */ - public String getKeywordDocumentation(String name); + String getKeywordDocumentation(String name); /** * Gets the name of the remote library. - * + * * @return The name of the remote library, which is the same as the class - * name + * name */ - public String getName(); + String getName(); /** * Gets the underlying library implementation. The {@link RemoteLibrary} * interface is intended to be used by wrapper classes. The original user * library can be accessed with this method. - * + * * @return The underlying library implementation */ - public Object getImplementation(); + Object getImplementation(); } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibraryFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibraryFactory.java index 5c7b184..97a748f 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibraryFactory.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibraryFactory.java @@ -15,5 +15,6 @@ package org.robotframework.remoteserver.library; public interface RemoteLibraryFactory { - public RemoteLibrary createRemoteLibrary(Object library); + + RemoteLibrary createRemoteLibrary(Object library); } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/StaticApiRemoteLibrary.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/StaticApiRemoteLibrary.java index 0f42963..787f6d2 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/StaticApiRemoteLibrary.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/StaticApiRemoteLibrary.java @@ -15,7 +15,6 @@ package org.robotframework.remoteserver.library; import java.util.Map; - import org.robotframework.remoteserver.javalib.SingleClassLibrary; public class StaticApiRemoteLibrary implements RemoteLibrary { @@ -28,36 +27,30 @@ protected StaticApiRemoteLibrary(Object library) { this.library = library; } - @Override - public String[] getKeywordNames() { + @Override public String[] getKeywordNames() { return handler.getKeywordNames(); } - @Override - public Object runKeyword(String keywordName, Object[] args, Map kwargs) throws Throwable { + @Override public Object runKeyword(String keywordName, Object[] args, Map kwargs) throws Throwable { if (kwargs != null && !kwargs.isEmpty()) { throw new RuntimeException("Keyword arguments not yet supported for static API libraries."); } return handler.runKeyword(keywordName, args); } - @Override - public String[] getKeywordArguments(String keyword) { + @Override public String[] getKeywordArguments(String keyword) { return handler.getKeywordArguments(keyword); } - @Override - public String getKeywordDocumentation(String keyword) { + @Override public String getKeywordDocumentation(String keyword) { return ""; } - @Override - public String getName() { + @Override public String getName() { return library.getClass().getName(); } - @Override - public Object getImplementation() { + @Override public Object getImplementation() { return library; } } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/logging/Jetty2Log4J.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/logging/Jetty2Log4J.java index ef40c22..49a149a 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/logging/Jetty2Log4J.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/logging/Jetty2Log4J.java @@ -14,8 +14,8 @@ */ package org.robotframework.remoteserver.logging; -import org.eclipse.jetty.util.log.Logger; import org.apache.log4j.Level; +import org.eclipse.jetty.util.log.Logger; /** * Jetty logger that redirects directly to Log4J without needing SLF4J on the classpath. This way users do not need to @@ -27,97 +27,97 @@ public class Jetty2Log4J implements Logger { private Level configuredLevel; public Jetty2Log4J() { - this("org.eclipse.jetty.util.log"); + this("org.eclipse.jetty.util.log"); } public Jetty2Log4J(String name) { - logger = org.apache.log4j.Logger.getLogger(name); + logger = org.apache.log4j.Logger.getLogger(name); } public String getName() { - return logger.getName(); + return logger.getName(); } public void warn(String msg, Object... args) { - logger.warn(format(msg, args)); + logger.warn(format(msg, args)); } public void warn(Throwable thrown) { - logger.warn("", thrown); + logger.warn("", thrown); } public void warn(String msg, Throwable thrown) { - logger.warn(msg, thrown); + logger.warn(msg, thrown); } public void info(String msg, Object... args) { - logger.info(format(msg, args)); + logger.info(format(msg, args)); } public void info(Throwable thrown) { - logger.info(null, thrown); + logger.info(null, thrown); } public void info(String msg, Throwable thrown) { - logger.info(msg, thrown); + logger.info(msg, thrown); } public boolean isDebugEnabled() { - return false; + return false; } public void setDebugEnabled(boolean enabled) { - if (enabled) { - configuredLevel = logger.getLevel(); - logger.setLevel(Level.DEBUG); - } else { - logger.setLevel(configuredLevel); - } + if (enabled) { + configuredLevel = logger.getLevel(); + logger.setLevel(Level.DEBUG); + } else { + logger.setLevel(configuredLevel); + } } public void debug(String msg, Object... args) { - logger.debug(format(msg, args)); + logger.debug(format(msg, args)); } public void debug(Throwable thrown) { - logger.debug("", thrown); + logger.debug("", thrown); } public void debug(String msg, Throwable thrown) { - logger.debug(msg, thrown); + logger.debug(msg, thrown); } public Logger getLogger(String name) { - return new Jetty2Log4J(name); + return new Jetty2Log4J(name); } public void ignore(Throwable ignored) { - try { - logger.trace("", ignored); - } catch (NoSuchMethodError e) { - // ignore. can happen if Log4J version < 1.2.12 loaded at runtime - } + try { + logger.trace("", ignored); + } catch (NoSuchMethodError e) { + // ignore. can happen if Log4J version < 1.2.12 loaded at runtime + } } private String format(String msg, Object... args) { - msg = String.valueOf(msg); // Avoids NPE - String braces = "{}"; - StringBuilder builder = new StringBuilder(); - int start = 0; - for (Object arg : args) { - int bracesIndex = msg.indexOf(braces, start); - if (bracesIndex < 0) { - builder.append(msg.substring(start)); - builder.append(" "); - builder.append(arg); - start = msg.length(); - } else { - builder.append(msg.substring(start, bracesIndex)); - builder.append(String.valueOf(arg)); - start = bracesIndex + braces.length(); - } - } - builder.append(msg.substring(start)); - return builder.toString(); + msg = String.valueOf(msg); // Avoids NPE + String braces = "{}"; + StringBuilder builder = new StringBuilder(); + int start = 0; + for (Object arg : args) { + int bracesIndex = msg.indexOf(braces, start); + if (bracesIndex < 0) { + builder.append(msg.substring(start)); + builder.append(" "); + builder.append(arg); + start = msg.length(); + } else { + builder.append(msg.substring(start, bracesIndex)); + builder.append(String.valueOf(arg)); + start = bracesIndex + braces.length(); + } + } + builder.append(msg.substring(start)); + return builder.toString(); } } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/IllegalPathException.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/IllegalPathException.java index 2052b56..34e3f11 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/IllegalPathException.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/IllegalPathException.java @@ -3,8 +3,7 @@ /** * Thrown when a path is not valid for mapping to a library */ -@SuppressWarnings("serial") -public class IllegalPathException extends RuntimeException { +@SuppressWarnings("serial") public class IllegalPathException extends RuntimeException { public IllegalPathException(String message) { super(message); diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerRequestProcessorFactoryFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerRequestProcessorFactoryFactory.java index 6924d50..486c0bf 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerRequestProcessorFactoryFactory.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerRequestProcessorFactoryFactory.java @@ -19,6 +19,7 @@ import org.apache.xmlrpc.server.RequestProcessorFactoryFactory; public class RemoteServerRequestProcessorFactoryFactory implements RequestProcessorFactoryFactory { + private final RequestProcessorFactory factory = new RemoteServerRequestProcessorFactory(); private final ServerMethods serverMethods; @@ -26,14 +27,15 @@ public RemoteServerRequestProcessorFactoryFactory(RemoteServerServlet servlet) { this.serverMethods = new ServerMethods(servlet); } - @SuppressWarnings("rawtypes") - public RequestProcessorFactory getRequestProcessorFactory(Class aClass) throws XmlRpcException { + @SuppressWarnings("rawtypes") public RequestProcessorFactory getRequestProcessorFactory(Class aClass) + throws XmlRpcException { return factory; } private class RemoteServerRequestProcessorFactory implements RequestProcessorFactory { + public Object getRequestProcessor(XmlRpcRequest xmlRpcRequest) throws XmlRpcException { return serverMethods; } } -} \ No newline at end of file +} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java index a8ea1ba..a0bcf47 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java @@ -20,12 +20,10 @@ import java.util.Map; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; - import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.commons.lang3.StringEscapeUtils; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.server.XmlRpcHandlerMapping; @@ -45,12 +43,47 @@ * System.exit(0) is executed. */ public class RemoteServerServlet extends XmlRpcServlet implements RemoteServerContext { + private static final long serialVersionUID = -7981676271855172976L; - private static final ThreadLocal request = new ThreadLocal(); - private static final ThreadLocal currLibrary = new ThreadLocal(); - private Map libraryMap = new ConcurrentHashMap(); + private static final ThreadLocal request = new ThreadLocal<>(); + private static final ThreadLocal currLibrary = new ThreadLocal<>(); + private Map libraryMap = new ConcurrentHashMap<>(); private boolean allowStop = true; + /** + * Cleans up the path of an incoming request. Repeating /s are reduced to + * one /. Trailing /s are removed. A null or empty path is + * converted to /. + * + * @param path the path the client requested + * @return cleaned up path + */ + private static String cleanPath(String path) { + path = path == null ? "/" : path; + if (!path.startsWith("/")) { + path = "/" + path; + } + path = path.replaceAll("/+", "/"); + if (path.length() > 1 && path.endsWith("/")) { + path = path.substring(0, path.length() - 1); + } + return path; + } + + private static void checkPath(String path) { + if (path == null || !path.startsWith("/")) { + throw new IllegalPathException(String.format("Path [%s] does not start with a /.", path)); + } else if (path.contains("//")) { + throw new IllegalPathException(String.format("Path [%s] contains repeated forward slashes.", path)); + } else if (!path.equals("/") && path.endsWith("/")) { + throw new IllegalPathException(String.format("Path [%s] ends with a /.", path)); + } else if (!path.matches("[a-zA-Z0-9-._~/]+")) { + throw new IllegalPathException(String.format( + "Path [%s] contains disallowed characters (must contain only alphanumeric or any of these: -._~/).", + path)); + } + } + public RemoteLibrary putLibrary(String path, Object library) { checkPath(path); RemoteLibraryFactory libraryFactory = createLibraryFactory(); @@ -63,7 +96,7 @@ public RemoteLibrary removeLibrary(String path) { } public Map getLibraryMap() { - return new HashMap(libraryMap); + return new HashMap<>(libraryMap); } public boolean getAllowStop() { @@ -74,15 +107,13 @@ public void setAllowStop(boolean allowed) { allowStop = allowed; } - @Override - protected XmlRpcServletServer newXmlRpcServer(ServletConfig pConfig) throws XmlRpcException { + @Override protected XmlRpcServletServer newXmlRpcServer(ServletConfig pConfig) throws XmlRpcException { XmlRpcServletServer server = new XmlRpcServletServer(); server.setTypeFactory(new TypeFactory(this.getXmlRpcServletServer())); return server; } - @Override - protected XmlRpcHandlerMapping newXmlRpcHandlerMapping() throws XmlRpcException { + @Override protected XmlRpcHandlerMapping newXmlRpcHandlerMapping() throws XmlRpcException { ReflectiveHandlerMapping map = new ReflectiveHandlerMapping(); map.setRequestProcessorFactoryFactory(new RemoteServerRequestProcessorFactoryFactory(this)); map.addHandler("keywords", ServerMethods.class); @@ -90,8 +121,8 @@ protected XmlRpcHandlerMapping newXmlRpcHandlerMapping() throws XmlRpcException return map; } - @Override - protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + @Override protected void service(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { request.set(req); try { super.service(req, resp); @@ -100,8 +131,8 @@ protected void service(HttpServletRequest req, HttpServletResponse resp) throws } } - @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { /* * when the client is Jython 2.5.x (old xmlrpclib using HTTP/1.0), the * server's sockets got stuck in FIN_WAIT_2 for some time, eventually @@ -120,8 +151,8 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws Serv } } - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { resp.setContentType("text/html"); String body = getPage(); resp.setContentLength(body.length()); @@ -134,7 +165,7 @@ public HttpServletRequest getRequest() { } private String getPage() { - Map map = new TreeMap(getLibraryMap()); + Map map = new TreeMap<>(getLibraryMap()); StringBuilder sb = new StringBuilder(); sb.append("" + "jrobotremoteserver" + "

    jrobotremoteserver serving:

    " @@ -144,7 +175,7 @@ private String getPage() { } else { for (String path : map.keySet()) { sb.append(""); - sb.append(path.toString()); + sb.append(path); sb.append(""); sb.append(StringEscapeUtils.escapeHtml4(map.get(path).getName())); sb.append(""); @@ -158,7 +189,7 @@ private String getPage() { * Returns the library to use in the current context. This should only be * used while a request is being processed and only on the same thread that * is handling the request. - * + * * @return the library to use in the current context */ public RemoteLibrary getLibrary() { @@ -169,40 +200,4 @@ protected RemoteLibraryFactory createLibraryFactory() { return new DefaultRemoteLibraryFactory(); } - /** - * Cleans up the path of an incoming request. Repeating /s are reduced to - * one /. Trailing /s are removed. A null or empty path is - * converted to /. - * - * @param path - * the path the client requested - * @return cleaned up path - */ - private static String cleanPath(String path) { - path = path == null ? "/" : path; - if (!path.startsWith("/")) { - path = "/" + path; - } - path = path.replaceAll("/+", "/"); - if (path.length() > 1 && path.endsWith("/")) { - path = path.substring(0, path.length() - 1); - } - return path; - } - - private static void checkPath(String path) { - if (path == null || !path.startsWith("/")) { - throw new IllegalPathException(String.format("Path [%s] does not start with a /.", path)); - } else if (path.contains("//")) { - throw new IllegalPathException(String.format("Path [%s] contains repeated forward slashes.", path)); - } else if (!path.equals("/") && path.endsWith("/")) { - throw new IllegalPathException(String.format("Path [%s] ends with a /.", path)); - } else if (!path.matches("[a-zA-Z0-9-._~/]+")) { - throw new IllegalPathException( - String.format( - "Path [%s] contains disallowed characters (must contain only alphanumeric or any of these: -._~/).", - path)); - } - } - } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java index 7f3f877..fa2d685 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java @@ -18,7 +18,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.logging.Log; @@ -27,18 +26,18 @@ /** * Contains the XML-RPC methods that implement the remote library interface. - * + * * @author David Luu - * */ public class ServerMethods { + private static List + genericExceptions = + Arrays.asList("AssertionError", "AssertionFailedError", "Exception", "Error", "RuntimeError", + "RuntimeException", "DataError", "TimeoutError", "RemoteError"); + String[] logLevelPrefixes = new String[] {"*TRACE*", "*DEBUG*", "*INFO*", "*HTML*", "*WARN*"}; private Log log; private RemoteServerServlet servlet; - private static List genericExceptions = Arrays.asList(new String[] { "AssertionError", - "AssertionFailedError", "Exception", "Error", "RuntimeError", "RuntimeException", "DataError", - "TimeoutError", "RemoteError" }); - String[] logLevelPrefixes = new String[] { "*TRACE*", "*DEBUG*", "*INFO*", "*HTML*", "*WARN*" }; public ServerMethods(RemoteServerServlet servlet) { log = LogFactory.getLog(ServerMethods.class); @@ -48,7 +47,7 @@ public ServerMethods(RemoteServerServlet servlet) { /** * Get an array containing the names of the keywords that the library * implements. - * + * * @return String array containing keyword names in the library */ public String[] get_keyword_names() { @@ -67,17 +66,14 @@ public String[] get_keyword_names() { /** * Run the given keyword and return the results. - * - * @param keyword - * keyword to run - * @param args - * arguments packed in an array to pass to the keyword method - * @param kwargs - * keyword arguments to pass to the keyword method + * + * @param keyword keyword to run + * @param args arguments packed in an array to pass to the keyword method + * @param kwargs keyword arguments to pass to the keyword method * @return remote result Map containing the execution results */ public Map run_keyword(String keyword, Object[] args, Map kwargs) { - Map result = new HashMap(); + Map result = new HashMap<>(); StdStreamRedirecter redirector = new StdStreamRedirecter(); redirector.redirectStdStreams(); try { @@ -143,11 +139,9 @@ public Map run_keyword(String keyword, Object[] args, Map run_keyword(String keyword, Object[] args) { @@ -156,9 +150,8 @@ public Map run_keyword(String keyword, Object[] args) { /** * Get an array of argument specifications for the given keyword. - * - * @param keyword - * The keyword to lookup. + * + * @param keyword The keyword to lookup. * @return A string array of argument specifications for the given keyword. */ public String[] get_keyword_arguments(String keyword) { @@ -176,9 +169,8 @@ public String[] get_keyword_arguments(String keyword) { /** * Get documentation for given keyword. - * - * @param keyword - * The keyword to get documentation for. + * + * @param keyword The keyword to get documentation for. * @return A documentation string for the given keyword. */ public String get_keyword_documentation(String keyword) { @@ -196,7 +188,7 @@ public String get_keyword_documentation(String keyword) { /** * Stops the remote server if it is configured to allow that. - * + * * @return remote result Map containing the execution results */ public Map stop_remote_server() { @@ -207,8 +199,8 @@ protected boolean stopRemoteServer() throws Exception { if (servlet.getAllowStop()) { System.out.print("Robot Framework remote server stopping"); new Thread("remote-server-stopper") { - @Override - public void run() { + + @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { @@ -252,7 +244,7 @@ protected Object arraysToLists(Object arg) { return list; } else if (arg instanceof Map) { Map oldMap = (Map) arg; - Map newMap = new HashMap(); + Map newMap = new HashMap<>(); for (Object key : oldMap.keySet()) newMap.put(key, arraysToLists(oldMap.get(key))); return newMap; diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/ByteArrayToStringParser.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/ByteArrayToStringParser.java index 845a21f..768621a 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/ByteArrayToStringParser.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/ByteArrayToStringParser.java @@ -16,9 +16,7 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; - import javax.xml.namespace.QName; - import org.apache.ws.commons.util.Base64; import org.apache.xmlrpc.parser.TypeParserImpl; import org.xml.sax.Attributes; @@ -70,6 +68,7 @@ public void startElement(String pURI, String pLocalName, String pQName, Attribut if (level++ == 0) { baos = new ByteArrayOutputStream(); decoder = new Base64.Decoder(1024) { + protected void writeBuffer(byte[] pBytes, int pOffset, int pLen) throws IOException { baos.write(pBytes, pOffset, pLen); } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/IterableSerializer.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/IterableSerializer.java index 04fb054..cfa3c10 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/IterableSerializer.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/IterableSerializer.java @@ -14,8 +14,6 @@ */ package org.robotframework.remoteserver.xmlrpc; -import java.util.Iterator; - import org.apache.xmlrpc.common.TypeFactory; import org.apache.xmlrpc.common.XmlRpcStreamConfig; import org.apache.xmlrpc.serializer.ObjectArraySerializer; @@ -25,14 +23,13 @@ public class IterableSerializer extends ObjectArraySerializer { public IterableSerializer(TypeFactory pTypeFactory, XmlRpcStreamConfig pConfig) { - super(pTypeFactory, pConfig); + super(pTypeFactory, pConfig); } protected void writeData(ContentHandler pHandler, Object pObject) throws SAXException { - Iterable obj = (Iterable) pObject; - Iterator iter = obj.iterator(); - while (iter.hasNext()) { - writeObject(pHandler, iter.next()); - } + Iterable obj = (Iterable) pObject; + for (Object anObj : obj) { + writeObject(pHandler, anObj); + } } -} \ No newline at end of file +} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/MapSerializer.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/MapSerializer.java index 4344041..a270a25 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/MapSerializer.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/MapSerializer.java @@ -16,7 +16,6 @@ import java.util.Iterator; import java.util.Map; - import org.apache.xmlrpc.common.TypeFactory; import org.apache.xmlrpc.common.XmlRpcStreamConfig; import org.apache.xmlrpc.serializer.TypeSerializer; @@ -34,41 +33,41 @@ public class MapSerializer extends TypeSerializerImpl { private final XmlRpcStreamConfig config; public MapSerializer(TypeFactory pTypeFactory, XmlRpcStreamConfig pConfig) { - typeFactory = pTypeFactory; - config = pConfig; + typeFactory = pTypeFactory; + config = pConfig; } protected void writeEntry(ContentHandler pHandler, Object pKey, Object pValue) throws SAXException { - pHandler.startElement("", MEMBER_TAG, MEMBER_TAG, ZERO_ATTRIBUTES); - pHandler.startElement("", NAME_TAG, NAME_TAG, ZERO_ATTRIBUTES); - String key = pKey == null ? "" : pKey.toString(); - pHandler.characters(key.toCharArray(), 0, key.length()); - pHandler.endElement("", NAME_TAG, NAME_TAG); - writeValue(pHandler, pValue); - pHandler.endElement("", MEMBER_TAG, MEMBER_TAG); + pHandler.startElement("", MEMBER_TAG, MEMBER_TAG, ZERO_ATTRIBUTES); + pHandler.startElement("", NAME_TAG, NAME_TAG, ZERO_ATTRIBUTES); + String key = pKey == null ? "" : pKey.toString(); + pHandler.characters(key.toCharArray(), 0, key.length()); + pHandler.endElement("", NAME_TAG, NAME_TAG); + writeValue(pHandler, pValue); + pHandler.endElement("", MEMBER_TAG, MEMBER_TAG); } private void writeValue(ContentHandler pHandler, Object pValue) throws SAXException { - TypeSerializer ts = typeFactory.getSerializer(config, pValue); - if (ts == null) { - throw new SAXException("Unsupported Java type: " + pValue.getClass().getName()); - } - ts.write(pHandler, pValue); + TypeSerializer ts = typeFactory.getSerializer(config, pValue); + if (ts == null) { + throw new SAXException("Unsupported Java type: " + pValue.getClass().getName()); + } + ts.write(pHandler, pValue); } protected void writeData(ContentHandler pHandler, Object pData) throws SAXException { - Map map = (Map) pData; - for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); - writeEntry(pHandler, entry.getKey(), entry.getValue()); - } + Map map = (Map) pData; + for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) { + Map.Entry entry = (Map.Entry) iter.next(); + writeEntry(pHandler, entry.getKey(), entry.getValue()); + } } public void write(final ContentHandler pHandler, Object pObject) throws SAXException { - pHandler.startElement("", VALUE_TAG, VALUE_TAG, ZERO_ATTRIBUTES); - pHandler.startElement("", STRUCT_TAG, STRUCT_TAG, ZERO_ATTRIBUTES); - writeData(pHandler, pObject); - pHandler.endElement("", STRUCT_TAG, STRUCT_TAG); - pHandler.endElement("", VALUE_TAG, VALUE_TAG); + pHandler.startElement("", VALUE_TAG, VALUE_TAG, ZERO_ATTRIBUTES); + pHandler.startElement("", STRUCT_TAG, STRUCT_TAG, ZERO_ATTRIBUTES); + writeData(pHandler, pObject); + pHandler.endElement("", STRUCT_TAG, STRUCT_TAG); + pHandler.endElement("", VALUE_TAG, VALUE_TAG); } -} \ No newline at end of file +} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/ReflectiveHandlerMapping.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/ReflectiveHandlerMapping.java index 446ee6a..1e03c21 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/ReflectiveHandlerMapping.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/ReflectiveHandlerMapping.java @@ -27,31 +27,30 @@ public class ReflectiveHandlerMapping extends AbstractReflectiveHandlerMapping { * Removes the prefixes from all keys in this handler mapping assuming a String was used as the key and period was * used as a separator. Example: AccountsReceivable.Billing.getInvoice getInvoice */ - @SuppressWarnings("unchecked") - public void removePrefixes() { - Map newHandlerMap = new HashMap(); - for (Entry entry : (Set>) this.handlerMap.entrySet()) { - String newKey = (String) entry.getKey(); - if (entry.getKey() instanceof String) { - String key = (String) entry.getKey(); - if (key.contains(".")) { - newKey = key.substring(key.lastIndexOf(".") + 1); - } - } - newHandlerMap.put(newKey, entry.getValue()); - } - this.handlerMap = newHandlerMap; + @SuppressWarnings("unchecked") public void removePrefixes() { + Map newHandlerMap = new HashMap<>(); + for (Entry entry : (Set>) this.handlerMap.entrySet()) { + String newKey = entry.getKey(); + if (entry.getKey() != null) { + String key = entry.getKey(); + if (key.contains(".")) { + newKey = key.substring(key.lastIndexOf(".") + 1); + } + } + newHandlerMap.put(newKey, entry.getValue()); + } + this.handlerMap = newHandlerMap; } - /** - * Adds handlers for the given object to the mapping. The handlers are build by invoking - * {@link #registerPublicMethods(String, Class)}. - * - * @param pKey The class key, which is passed to {@link #registerPublicMethods(String, Class)}. - * @param pClass Class, which is responsible for handling the request. - * @throws XmlRpcException If error occurs - */ - public void addHandler(String pKey, Class pClass) throws XmlRpcException { - registerPublicMethods(pKey, pClass); + /** + * Adds handlers for the given object to the mapping. The handlers are build by invoking + * {@link #registerPublicMethods(String, Class)}. + * + * @param pKey The class key, which is passed to {@link #registerPublicMethods(String, Class)}. + * @param pClass Class, which is responsible for handling the request. + * @throws XmlRpcException If error occurs + */ + public void addHandler(String pKey, Class pClass) throws XmlRpcException { + registerPublicMethods(pKey, pClass); } } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/StringSerializer.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/StringSerializer.java index 572c475..4535cc9 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/StringSerializer.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/StringSerializer.java @@ -16,15 +16,15 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; - +import java.util.regex.Pattern; import org.apache.ws.commons.util.Base64; import org.apache.ws.commons.util.Base64.Encoder; import org.apache.xmlrpc.serializer.TypeSerializerImpl; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; -import java.util.regex.Pattern; public class StringSerializer extends TypeSerializerImpl { + public static final String STRING_TAG = "string"; public static final String BASE_64_TAG = "base64"; private static Pattern pattern = Pattern.compile("[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]"); diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java index d05a8fb..806adb4 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java @@ -16,7 +16,6 @@ import java.util.List; import java.util.Map; - import org.apache.commons.lang3.ArrayUtils; import org.apache.ws.commons.util.NamespaceContextImpl; import org.apache.xmlrpc.common.TypeFactoryImpl; @@ -41,19 +40,20 @@ public class TypeFactory extends TypeFactoryImpl { private static final TypeSerializer DOUBLE_SERIALIZER = new DoubleSerializer(); private static final TypeSerializer BOOLEAN_SERIALIZER = new BooleanSerializer(); private static final TypeSerializer NULL_SERIALIZER = new org.apache.xmlrpc.serializer.StringSerializer() { - @Override - public void write(ContentHandler pHandler, Object pObject) throws SAXException { + + @Override public void write(ContentHandler pHandler, Object pObject) throws SAXException { write(pHandler, null, ""); } }; private static final TypeSerializer CHAR_ARRAY_SERIALIZER = new TypeSerializerImpl() { + public void write(ContentHandler pHandler, Object pObject) throws SAXException { char[] chars = (char[]) pObject; write(pHandler, null, chars); } }; - private TypeSerializer primitiveArraySerializer; private static final TypeParser BYTE_ARRAY_PARSER = new ByteArrayToStringParser(); + private TypeSerializer primitiveArraySerializer; public TypeFactory(XmlRpcController pController) { super(pController); @@ -81,10 +81,10 @@ else if (pObject instanceof Iterable) else if (pObject instanceof char[]) return CHAR_ARRAY_SERIALIZER; else if (pObject.getClass().isArray()) { // object[] & char[] handled - // before this + // before this primitiveArraySerializer = new ObjectArraySerializer(this, pConfig) { - @Override - protected void writeData(ContentHandler pHandler, Object pObject) throws SAXException { + + @Override protected void writeData(ContentHandler pHandler, Object pObject) throws SAXException { Object[] array; if (pObject instanceof byte[]) array = ArrayUtils.toObject((byte[]) pObject); @@ -102,8 +102,8 @@ else if (pObject instanceof boolean[]) array = ArrayUtils.toObject((boolean[]) pObject); else // should never happen - throw new SAXException(String.format("Array of type %s[] not handled!", pObject.getClass() - .getComponentType().getName())); + throw new SAXException(String.format("Array of type %s[] not handled!", + pObject.getClass().getComponentType().getName())); super.writeData(pHandler, array); } }; @@ -112,8 +112,7 @@ else if (pObject instanceof boolean[]) return STRING_SERIALIZER; } - @Override - public TypeParser getParser(XmlRpcStreamConfig pConfig, NamespaceContextImpl pContext, String pURI, + @Override public TypeParser getParser(XmlRpcStreamConfig pConfig, NamespaceContextImpl pContext, String pURI, String pLocalName) { if (ByteArraySerializer.BASE_64_TAG.equals(pLocalName)) { return BYTE_ARRAY_PARSER; diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteServerImplTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteServerImplTest.java index c952bd8..5fb8ac2 100644 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteServerImplTest.java +++ b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteServerImplTest.java @@ -64,32 +64,6 @@ public void ephemeralPort() throws Exception { Assert.assertEquals(server.getPort(), -2); } - @Test - public void addTwoLibrariesOnDifferentPorts() { - server.addLibrary(StaticOne.class, 8270); - Exception ex = null; - try { - server.addLibrary(StaticOne.class, 8271); - } catch (Exception e) { - ex = e; - } - Assert.assertEquals(ex.getMessage(), - "Serving on multiple ports is no longer supported. Please use putLibrary with different paths instead."); - } - - @Test - public void mixAddLibraryWithSetPort() { - server.setPort(8270); - Exception ex = null; - try { - server.addLibrary(StaticOne.class, 8271); - } catch (Exception e) { - ex = e; - } - Assert.assertEquals(ex.getMessage(), - "Serving on multiple ports is no longer supported. Please use putLibrary with different paths instead."); - } - @Test public void libraryMap() { server.putLibrary("/", new StaticOne()); diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/OverloadableKeywordTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/OverloadableKeywordTest.java index 9586721..d37a713 100644 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/OverloadableKeywordTest.java +++ b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/OverloadableKeywordTest.java @@ -16,8 +16,8 @@ public class OverloadableKeywordTest @BeforeTest public void setup() throws Exception { - shortOverload = library.getClass().getDeclaredMethod("numberType", new Class[] {short.class}); - intOverload = library.getClass().getDeclaredMethod("numberType", new Class[] {int.class}); + shortOverload = library.getClass().getDeclaredMethod("numberType", short.class); + intOverload = library.getClass().getDeclaredMethod("numberType", int.class); keyword = new OverloadableKeyword(library, shortOverload); keyword.addOverload(intOverload); } diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibraryTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibraryTest.java index 789e256..64ca166 100644 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibraryTest.java +++ b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibraryTest.java @@ -24,8 +24,7 @@ public class DynamicApiRemoteLibraryTest { public void getDynamicAPILibraryImplementation() throws Exception { DynamicOneRunKeywordNoKwargs lib = new DynamicOneRunKeywordNoKwargs(); Method gkn = DynamicOneRunKeywordNoKwargs.class.getMethod("getKeywordNames"); - Method rk = DynamicOneRunKeywordNoKwargs.class.getMethod("runKeyword", new Class[] { String.class, - Object[].class }); + Method rk = DynamicOneRunKeywordNoKwargs.class.getMethod("runKeyword", String.class, Object[].class); DynamicApiRemoteLibrary wrapper = new DynamicApiRemoteLibrary(lib, gkn, rk, null, null); assertEquals(wrapper.getImplementation(), lib); } @@ -34,8 +33,8 @@ public void getDynamicAPILibraryImplementation() throws Exception { public void libraryUsingLists() throws Throwable { DynamicUsingLists lib = new DynamicUsingLists(); Method gkn = DynamicUsingLists.class.getMethod("getKeywordNames"); - Method rk = DynamicUsingLists.class.getMethod("runKeyword", new Class[] { String.class, List.class }); - Method gka = DynamicUsingLists.class.getMethod("getKeywordArguments", new Class[] { String.class }); + Method rk = DynamicUsingLists.class.getMethod("runKeyword", String.class, List.class); + Method gka = DynamicUsingLists.class.getMethod("getKeywordArguments", String.class); DynamicApiRemoteLibrary wrapper = new DynamicApiRemoteLibrary(lib, gkn, rk, gka, null); Assert.assertEquals(wrapper.getKeywordNames(), new String[] { "go" }); Assert.assertEquals(wrapper.runKeyword("go", new Object[] { "there" }, noKwargs), "there"); diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargsList.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargsList.java index f487bb8..d0e0a92 100644 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargsList.java +++ b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargsList.java @@ -19,7 +19,7 @@ public Object runKeyword(String name, List args, Map kwargs) { } public List getKeywordArguments(String name) { - return Arrays.asList(new String[] {"*args", "**kwargs"}); + return Arrays.asList("*args", "**kwargs"); } } diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicUsingLists.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicUsingLists.java index 59409e7..68c1603 100644 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicUsingLists.java +++ b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicUsingLists.java @@ -7,7 +7,7 @@ public class DynamicUsingLists { public List getKeywordNames() { - return Arrays.asList(new String[] {"go"}); + return Arrays.asList("go"); } public Object runKeyword(String name, List arguments) { @@ -26,7 +26,7 @@ public Object runKeyword(String name, List arguments) { public List getKeywordArguments(String name) { if (name.equals("go")) { - return Arrays.asList(new String[] {"where"}); + return Arrays.asList("where"); } throw new RuntimeException("bad keyword"); } From 552046dc92d4292fffd6fc92452f09df300866eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Mih=C3=A1lek?= Date: Wed, 28 Sep 2016 18:38:04 +0200 Subject: [PATCH 03/11] Change robotframework-maven-plugin phase to test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Martin Mihálek --- jrobot-karaf/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/jrobot-karaf/pom.xml b/jrobot-karaf/pom.xml index c9c4d3b..99768f9 100755 --- a/jrobot-karaf/pom.xml +++ b/jrobot-karaf/pom.xml @@ -52,6 +52,7 @@ robotframework-maven-plugin + test run From f189bbb14c0fe2aa797d7110edfe245f3e880521 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Mih=C3=A1lek?= Date: Wed, 28 Sep 2016 19:18:05 +0200 Subject: [PATCH 04/11] Wait for karaf start for max 120s via info command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Martin Mihálek --- jrobot-karaf/src/test/robotframework/karaf_keywords.robot | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/jrobot-karaf/src/test/robotframework/karaf_keywords.robot b/jrobot-karaf/src/test/robotframework/karaf_keywords.robot index 54b9c04..71f87cb 100644 --- a/jrobot-karaf/src/test/robotframework/karaf_keywords.robot +++ b/jrobot-karaf/src/test/robotframework/karaf_keywords.robot @@ -12,8 +12,7 @@ Start Karaf ${rc} Run Keyword If ${rc} != 0 Run and Return RC ${KARAF_ROOT}/bin/start Should Be Equal As Integers ${rc} 0 Wait Until Keyword Succeeds 10 1 Karaf Status Running - #Let the karaf properly start - Sleep 2s + Wait Until Keyword Succeeds 120 1 Run On Karaf info Stop Karaf [Documentation] Stops karaf container instance From 97c90bfb99379270e324df01278a421178452926 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Mih=C3=A1lek?= Date: Fri, 14 Oct 2016 20:19:05 +0200 Subject: [PATCH 05/11] Update maven dependencies, gitignore MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Martin Mihálek --- .gitignore | 2 +- pom.xml | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index b9d4684..8cdd140 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,6 @@ test-output atest/results *.pyc .pydevproject -/.idea/ +.idea/ /target/ *.iml diff --git a/pom.xml b/pom.xml index f0ccf86..e23187d 100644 --- a/pom.xml +++ b/pom.xml @@ -40,6 +40,8 @@ UTF-8 + 1.8 + 19.0 @@ -77,9 +79,9 @@ 3.4 - log4j - log4j - 1.2.16 + org.slf4j + slf4j-api + 1.7.21 org.apache.xmlrpc @@ -112,6 +114,11 @@ 4.0.6 xml + + com.google.guava + guava + ${guava.version} + From 844e18aef55eca927eec749b8c2e0100dc0ff132 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Mih=C3=A1lek?= Date: Fri, 14 Oct 2016 20:23:04 +0200 Subject: [PATCH 06/11] Add robotframework acceptance tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Martin Mihálek --- .../acceptance/020_jrobot_tests.robot | 55 +++++++++++++++++++ .../test/robotframework/karaf_keywords.robot | 4 +- 2 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 jrobot-karaf/src/test/robotframework/acceptance/020_jrobot_tests.robot diff --git a/jrobot-karaf/src/test/robotframework/acceptance/020_jrobot_tests.robot b/jrobot-karaf/src/test/robotframework/acceptance/020_jrobot_tests.robot new file mode 100644 index 0000000..b2c918c --- /dev/null +++ b/jrobot-karaf/src/test/robotframework/acceptance/020_jrobot_tests.robot @@ -0,0 +1,55 @@ +*** Settings *** +Documentation Test suite to verify OSGI capabilities of jrobot-remoe-server +Suite Setup Setup Suite +Suite Teardown Clean Suite +Resource ../karaf_keywords.robot + +*** Variables *** + +*** Test Cases *** +Library Type Override Test + [Documentation] TODO + ${result} BaseLib.Concat Concat me together. + Should Be Equal As Strings ${result} Concat me together. + ${result} BaseLib.Concat Number 5 + Should Be Equal As Strings ${result} Number 6 + ${result} BaseLib.Concat 5 Number + Should Be Equal As Strings ${result} 6 Number + ${result} BaseLib.Concat Concat me together. + Should Be Equal As Strings ${result} Concat me together. + +Library Numeric Type Override Test + [Documentation] TODO + ${sum} BaseLib.Add 5.2 1.3 + Should be equal as numbers 6.5 ${sum} + ${sum} BaseLib.Add 5 1 + Should Be Equal As Integers 6 ${sum} + +Library Inheritance Test + [Documentation] + ${name_1} BaseLib.Get Name + ${name_2} ExtendedLib.Get Name + Should Not Be Equal As Strings ${name_1} ${name_2} + Should Be Equal As Strings ${name_1} Base Library + Should Be Equal As Strings ${name_2} Extended Library + ${pi} ExtendedLib.Get Pi + Should be equal as numbers 3.14 ${pi} + +*** Keywords *** +Setup Suite + [Documentation] TODO + Start Karaf + Verify Feature Installed On Karaf jrobot-remote-server + Verify Feature Started On Karaf jrobot-remote-server + Install Bundle On Karaf mvn:com.github.aenniw/jrobot-test-library + Verify Bundle Installed On Karaf jrobot-test-library + Start Bundle On Karaf jrobot-test-library + Verify Bundle Started On Karaf jrobot-test-library + Import Library Remote http://localhost:8270/BaseLibrary WITH NAME BaseLib + Import Library Remote http://localhost:8270/ExtendedLibrary WITH NAME ExtendedLib + +Clean Suite + [Documentation] + BaseLib.Library Cleanup + ExtendedLib.Library Cleanup + Stop Karaf diff --git a/jrobot-karaf/src/test/robotframework/karaf_keywords.robot b/jrobot-karaf/src/test/robotframework/karaf_keywords.robot index 71f87cb..435d1e5 100644 --- a/jrobot-karaf/src/test/robotframework/karaf_keywords.robot +++ b/jrobot-karaf/src/test/robotframework/karaf_keywords.robot @@ -65,8 +65,8 @@ Verify Feature Installed On Karaf Verify Bundle Installed On Karaf [Arguments] ${bundle_name} [Documentation] Checks if bundle was installed - ${output} Run On Karaf bundle:list | grep ${bundle_name} - Should Contain ${output} Installed + ${output} Run On Karaf bundle:list + Should Contain ${output} ${bundle_name} Verify Feature Started On Karaf [Arguments] ${feature_name} From 2ebb715c5ef031e164b927a2e1ed9ef5e53d431b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Mih=C3=A1lek?= Date: Fri, 14 Oct 2016 20:23:59 +0200 Subject: [PATCH 07/11] Redesign jrobot-remote-server logic MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Martin Mihálek --- .../src/main/resources/features.xml | 1 + jrobot-remote-server/pom.xml | 12 +- .../remoteserver/RemoteServer.java | 13 +- .../remoteserver/RemoteServerImpl.java | 78 ++++----- .../KeywordDocumentation.java} | 19 ++- .../remoteserver/cli/CommandLineHelper.java | 161 ------------------ .../remoteserver/javalib/KeywordOverload.java | 70 -------- .../javalib/OverloadableKeyword.java | 127 -------------- .../javalib/SimpleKeywordExtractor.java | 50 ------ .../javalib/SimpleKeywordFactory.java | 75 -------- .../javalib/SingleClassLibrary.java | 67 -------- .../remoteserver/keywords/CheckedKeyword.java | 9 + .../keywords/CheckedKeywordImpl.java | 91 ++++++++++ .../keywords/KeywordExtractor.java | 10 ++ .../keywords/OverloadedKeyword.java | 9 + .../keywords/OverloadedKeywordExtractor.java | 90 ++++++++++ .../keywords/OverloadedKeywordFactory.java | 56 ++++++ .../keywords/OverloadedKeywordImpl.java | 105 ++++++++++++ .../library/AbstractClassLibrary.java | 67 ++++++++ .../library/DefaultRemoteLibraryFactory.java | 113 ------------ .../library/DynamicApiRemoteLibrary.java | 102 ----------- .../remoteserver/library/RemoteLibrary.java | 21 +-- .../library/StaticApiRemoteLibrary.java | 56 ------ .../remoteserver/logging/Jetty2Log4J.java | 123 ------------- .../servlet/IllegalPathException.java | 2 +- .../remoteserver/servlet/JRobotServlet.java | 52 ++++++ .../RemoteServerContext.java | 21 +-- ...eServerRequestProcessorFactoryFactory.java | 4 +- .../servlet/RemoteServerServlet.java | 44 ++--- .../remoteserver/servlet/ServerMethods.java | 154 ++++------------- .../remoteserver/xmlrpc/MapSerializer.java | 6 +- .../remoteserver/xmlrpc/StringSerializer.java | 36 ++-- .../remoteserver/xmlrpc/TypeFactory.java | 36 ++-- .../remoteserver/RemoteLibraryClient.java | 44 ----- .../remoteserver/RemoteServerImplTest.java | 96 ----------- .../cli/CommandLineHelpertTest.java | 102 ----------- .../javalib/OverloadableKeywordTest.java | 48 ------ .../javalib/SimpleKeywordExtractorTest.java | 40 ----- .../javalib/SimpleKeywordFactoryTest.java | 20 --- .../javalib/SingleClassLibraryTest.java | 34 ---- .../DefaultRemoteLibraryFactoryTest.java | 25 --- .../library/DynamicApiRemoteLibraryTest.java | 98 ----------- .../library/StaticApiRemoteLibraryTest.java | 25 --- .../servlet/AlternativeContainerTest.java | 40 ----- .../servlet/RemoteServerServletTest.java | 83 --------- .../ConflictingOverloadVariableArguments.java | 7 - .../testlibraries/DuplicateKeywords.java | 9 - .../DynamicOneRunKeywordKwargs.java | 23 --- .../DynamicOneRunKeywordKwargsList.java | 25 --- .../DynamicOneRunKeywordNoKwargs.java | 17 -- .../testlibraries/DynamicUsingLists.java | 38 ----- .../testlibraries/OverloadedMethods.java | 25 --- .../remoteserver/testlibraries/StaticOne.java | 61 ------- .../remoteserver/testlibraries/StaticTwo.java | 7 - 54 files changed, 641 insertions(+), 2106 deletions(-) rename jrobot-remote-server/src/main/java/org/robotframework/remoteserver/{library/RemoteLibraryFactory.java => anotations/KeywordDocumentation.java} (52%) delete mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/cli/CommandLineHelper.java delete mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/KeywordOverload.java delete mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/OverloadableKeyword.java delete mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractor.java delete mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactory.java delete mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SingleClassLibrary.java create mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/CheckedKeyword.java create mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/CheckedKeywordImpl.java create mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/KeywordExtractor.java create mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeyword.java create mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordExtractor.java create mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordFactory.java create mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordImpl.java create mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/AbstractClassLibrary.java delete mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactory.java delete mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibrary.java delete mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/StaticApiRemoteLibrary.java delete mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/logging/Jetty2Log4J.java create mode 100644 jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/JRobotServlet.java rename jrobot-remote-server/src/main/java/org/robotframework/remoteserver/{context => servlet}/RemoteServerContext.java (80%) delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteLibraryClient.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteServerImplTest.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/cli/CommandLineHelpertTest.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/OverloadableKeywordTest.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractorTest.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactoryTest.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SingleClassLibraryTest.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactoryTest.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibraryTest.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/StaticApiRemoteLibraryTest.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/servlet/AlternativeContainerTest.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/servlet/RemoteServerServletTest.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/ConflictingOverloadVariableArguments.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DuplicateKeywords.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargs.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargsList.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordNoKwargs.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicUsingLists.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/OverloadedMethods.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/StaticOne.java delete mode 100644 jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/StaticTwo.java diff --git a/jrobot-features/src/main/resources/features.xml b/jrobot-features/src/main/resources/features.xml index b953621..9f92bb2 100644 --- a/jrobot-features/src/main/resources/features.xml +++ b/jrobot-features/src/main/resources/features.xml @@ -6,6 +6,7 @@ mvn:com.github.aenniw/jrobot-remote-server/${project.version} + mvn:com.google.guava/guava/${guava.version} jetty diff --git a/jrobot-remote-server/pom.xml b/jrobot-remote-server/pom.xml index 66431d1..2fcd96b 100644 --- a/jrobot-remote-server/pom.xml +++ b/jrobot-remote-server/pom.xml @@ -39,8 +39,8 @@ commons-lang3 - log4j - log4j + org.slf4j + slf4j-api org.apache.xmlrpc @@ -57,6 +57,10 @@ tjws test + + com.google.guava + guava + @@ -64,8 +68,8 @@ org.apache.maven.plugins maven-compiler-plugin - 1.7 - 1.7 + ${java.version} + ${java.version} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServer.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServer.java index c04af19..b12acd4 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServer.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServer.java @@ -7,10 +7,8 @@ public interface RemoteServer { /** * Stops the remote server immediately. - * - * @throws Exception If server cannot be stopped */ - void stop() throws Exception; + void stop(); /** * A non-blocking method for stopping the remote server that allows requests @@ -19,9 +17,8 @@ public interface RemoteServer { * * @param timeoutMS the milliseconds to wait for existing request to complete * before stopping the server - * @throws Exception If server cannot be stopped */ - void stop(int timeoutMS) throws Exception; + void stop(int timeoutMS); /** * Starts the remote server. Add test libraries first before calling this. @@ -58,11 +55,9 @@ public interface RemoteServer { * * Example: putLibrary("/myLib", new MyLibrary()); * - * @param library instance of the test library * @param path path to map the test library to - * @return the previous library mapped to the path, or null if there was no - * mapping for the path + * @param library instance of the test library */ - RemoteLibrary putLibrary(String path, Object library); + void putLibrary(String path, RemoteLibrary library); } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java index a5d83dd..bd82319 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java @@ -14,16 +14,18 @@ */ package org.robotframework.remoteserver; +import com.google.common.base.Preconditions; import java.util.Map; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.robotframework.remoteserver.library.RemoteLibrary; +import org.robotframework.remoteserver.servlet.RemoteServerContext; import org.robotframework.remoteserver.servlet.RemoteServerServlet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Remote server for Robot Framework implemented in Java. Takes one or more test @@ -40,10 +42,10 @@ */ public class RemoteServerImpl implements RemoteServer { - private static Log log = LogFactory.getLog(RemoteServer.class); - protected Server server = new Server(); - private RemoteServerServlet servlet = new RemoteServerServlet(); - private SelectChannelConnector connector = new SelectChannelConnector(); + protected static final Logger LOG = LoggerFactory.getLogger(RemoteServerImpl.class.getName()); + protected final Server server = new Server(); + private final RemoteServerContext servlet = new RemoteServerServlet(); + private final SelectChannelConnector connector = new SelectChannelConnector(); public RemoteServerImpl() { connector.setName("jrobotremoteserver"); @@ -72,24 +74,6 @@ public void setPort(int port) { connector.setPort(port); } - /** - * Returns true if this server allows remote stopping. - * - * @return true if this server allows remote stopping - */ - public boolean getAllowStop() { - return servlet.getAllowStop(); - } - - /** - * Allow or disallow stopping the server remotely. - * - * @param allowed true to allow stopping the server remotely - */ - public void setAllowStop(boolean allowed) { - servlet.setAllowStop(allowed); - } - /** * Returns the hostname set with {@link #setHost(String)}. * @@ -111,11 +95,15 @@ public void setHost(String hostName) { connector.setHost(hostName); } - @Override public RemoteLibrary putLibrary(String path, Object library) { - RemoteLibrary oldLibrary = servlet.putLibrary(path, library); - String name = servlet.getLibraryMap().get(path).getName(); - log.info(String.format("Mapped path %s to library %s.", path, name)); - return oldLibrary; + @Override public void putLibrary(String path, RemoteLibrary library) { + final RemoteLibrary + oldLibrary = + servlet.putLibrary(Preconditions.checkNotNull(path), Preconditions.checkNotNull(library)); + if (oldLibrary != null) { + oldLibrary.close(); + LOG.info("Closed library {} om path {}", library.getClass().getSimpleName(), path); + } + LOG.info("Mapped path {} to library {}", path, library.getClass().getSimpleName()); } @Override public RemoteLibrary removeLibrary(String path) { @@ -126,33 +114,27 @@ public void setHost(String hostName) { return servlet.getLibraryMap(); } - @Override public void stop(int timeoutMS) throws Exception { - log.info("Robot Framework remote server stopping"); - if (timeoutMS > 0) { - server.setGracefulShutdown(timeoutMS); - Thread stopper = new Thread() { - - @Override public void run() { - try { - server.stop(); - } catch (Throwable e) { - log.error(String.format("Failed to stop the server: %s", e.getMessage()), e); - } - } - }; - stopper.start(); - } else { + @Override public void stop(int timeoutMS) { + LOG.info("Robot Framework remote server stopping"); + try { + if (timeoutMS > 0) { + server.setGracefulShutdown(timeoutMS); + } server.stop(); + } catch (Throwable e) { + LOG.error("Failed to stop the server: {}", e.getMessage(), e); + } finally { + servlet.getLibraryMap().values().forEach(RemoteLibrary::close); } } - @Override public void stop() throws Exception { + @Override public void stop() { stop(0); } @Override public void start() throws Exception { - log.info("Robot Framework remote server starting"); + LOG.info("Robot Framework remote server starting"); server.start(); - log.info(String.format("Robot Framework remote server started on port %d.", getPort())); + LOG.info("Robot Framework remote server started on port {}", getPort()); } } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibraryFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/anotations/KeywordDocumentation.java similarity index 52% rename from jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibraryFactory.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/anotations/KeywordDocumentation.java index 97a748f..266f155 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibraryFactory.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/anotations/KeywordDocumentation.java @@ -1,10 +1,11 @@ -/* Copyright 2014 Kevin Ormbrek - * +/* + * Copyright 2013 Nokia Solutions and Networks Oyj + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -12,9 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.robotframework.remoteserver.library; -public interface RemoteLibraryFactory { +package org.robotframework.remoteserver.anotations; - RemoteLibrary createRemoteLibrary(Object library); +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface KeywordDocumentation { + + String value() default ""; } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/cli/CommandLineHelper.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/cli/CommandLineHelper.java deleted file mode 100644 index 27f0100..0000000 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/cli/CommandLineHelper.java +++ /dev/null @@ -1,161 +0,0 @@ -/* Copyright 2014 Kevin Ormbrek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.robotframework.remoteserver.cli; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -public class CommandLineHelper { - - private Map libraryMap = new HashMap<>(); - private boolean allowStop = true; - private String host = null; - private String error = null; - private boolean helpRequested = false; - private String[] args; - private int idx = 0; - private int port = 0; - private boolean usedOldLibraryOption = false; - - public CommandLineHelper(String[] clargs) { - args = clargs; - try { - while (idx < args.length) { - if (args[idx].equals("-l") || args[idx].equals("--library")) { - String[] parts = getValue("library").split(":", 2); - String className = parts[0]; - String path = "/"; - if (parts.length == 2) { - path = parts[1]; - } - if (path.equals("") || path.matches("\\s+")) { - throw new RuntimeException("Missing path for library " + className); - } - putLibrary(path, className); - } else if (args[idx].equals("-p") || args[idx].equals("--port")) { - String portString = getValue("port"); - setPort(portString); - } else if (args[idx].equals("-H") || args[idx].equals("--host")) { - host = getValue("host"); - } else if (args[idx].equals("-a") || args[idx].equals("--allowstop")) { - String value = getValue("allowstop"); - if (value.equalsIgnoreCase("false")) - allowStop = false; - else if (value.equalsIgnoreCase("true")) - allowStop = true; - else - throw new RuntimeException("Value for option allowstop must be true or false"); - } else if (Arrays.asList("-h", "-?", "--help").contains(args[idx])) { - helpRequested = true; - return; - } else - throw new RuntimeException("Unkown option: " + args[idx]); - idx++; - } - if (libraryMap.isEmpty()) - throw new RuntimeException("You must specify at least one library"); - } catch (Exception e) { - error = e.getMessage(); - } - } - - public boolean getAllowStop() { - return allowStop; - } - - public String getHost() { - return host; - } - - public int getPort() { - return port; - } - - private void setPort(String portString) { - if (usedOldLibraryOption) { - throw new RuntimeException( - "Cannot use the port option or use multiple libraries when specifying libraries in the form classname:port"); - } - int port; - try { - port = Integer.valueOf(portString.trim()); - if (port < 1 || port > 65535) - throw new Exception(); - } catch (Exception e) { - throw new RuntimeException("Port must be 1-65535"); - } - this.port = port; - } - - public Map getLibraryMap() { - return libraryMap; - } - - public String getError() { - return error; - } - - public boolean getHelpRequested() { - return helpRequested; - } - - public String getUsage() { - return "Usage: org.robotframework.remoteserver.RemoteServer options\n\n" + // - "Options:\n" + // - // ////////////////////////////////////////////////////////////////////////////// - " -l --library classname[:path] library to serve and path to map to. Path\n" + // - " has a default value of /. The library option\n" + // - " may be repeated to serve multiple libraries\n" + // - " -p --port port port to bind to, defaults to 0 (ephemeral)\n" + // - " -a --allowstop true|false whether to allow remote stop\n" + // - " -H --host hostname hostname of the interface to bind to\n" + // - " -h -? --help print this help message\n\n" + // - " For backwards compatibility, one library can be added using the form\n" + // - " --library classname:port\n"; - } - - private String getValue(String name) { - if (idx == args.length - 1 || (args[idx + 1].startsWith("-"))) - throw new RuntimeException("Missing value for option " + name); - else - return args[idx++ + 1]; - } - - private void putLibrary(String path, String className) { - className = className.trim(); - if (path.matches("\\d+")) { - setPort(path); - usedOldLibraryOption = true; - path = "/"; - } - Class clazz; - try { - clazz = Class.forName(className); - } catch (Exception e) { - throw new RuntimeException("Failed to load class with name " + className + ": " + e.toString()); - } - Object library; - try { - library = clazz.newInstance(); - } catch (Exception e) { - throw new RuntimeException("Failed to create library instance: " + e.toString()); - } - if (libraryMap.containsKey(path)) - throw new RuntimeException(String.format("Duplicate path [%s]", path)); - libraryMap.put(path, library); - } - -} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/KeywordOverload.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/KeywordOverload.java deleted file mode 100644 index 6d65017..0000000 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/KeywordOverload.java +++ /dev/null @@ -1,70 +0,0 @@ -/* Copyright 2014 Kevin Ormbrek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* This code is derived from JavalibCore - * Copyright 2008 Nokia Siemens Networks Oyj - */ -package org.robotframework.remoteserver.javalib; - -import java.lang.reflect.Method; -import org.robotframework.javalib.keyword.Keyword; -import org.robotframework.javalib.reflection.ArgumentConverter; -import org.robotframework.javalib.reflection.ArgumentGrouper; -import org.robotframework.javalib.reflection.IArgumentConverter; -import org.robotframework.javalib.reflection.IArgumentGrouper; - -public class KeywordOverload implements Keyword { - - private final Method method; - private final Object obj; - - public KeywordOverload(Object obj, Method method) { - this.obj = obj; - this.method = method; - } - - public Object execute(Object[] args) { - try { - Object[] groupedArguments = createArgumentGrouper().groupArguments(args); - Object[] convertedArguments = createArgumentConverter().convertArguments(groupedArguments); - return method.invoke(obj, convertedArguments); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public boolean canExecute(Object[] args) { - try { - Object[] groupedArguments = createArgumentGrouper().groupArguments(args); - Object[] convertedArguments = createArgumentConverter().convertArguments(groupedArguments); - for (int i = 0; i < args.length; i++) { - if ((convertedArguments[i] == null) && (args[i] != null)) { - return false; - } - } - return true; - } catch (Exception e) { - return false; - } - } - - protected IArgumentConverter createArgumentConverter() { - return new ArgumentConverter(method.getParameterTypes()); - } - - protected IArgumentGrouper createArgumentGrouper() { - return new ArgumentGrouper(method.getParameterTypes()); - } - -} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/OverloadableKeyword.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/OverloadableKeyword.java deleted file mode 100644 index 9f3bacc..0000000 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/OverloadableKeyword.java +++ /dev/null @@ -1,127 +0,0 @@ -/* Copyright 2014 Kevin Ormbrek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* This code is derived from JavalibCore - * Copyright 2008 Nokia Siemens Networks Oyj - */ -package org.robotframework.remoteserver.javalib; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.robotframework.javalib.keyword.Keyword; - -public class OverloadableKeyword implements Keyword { - - private static Log log = LogFactory.getLog(OverloadableKeyword.class); - private Map> keywordMap = new HashMap<>(); - private String name; - private Object keywordBean; - private boolean usesVarArgs = false; - - public OverloadableKeyword(Object keywordBean, Method method) { - name = method.getName(); - this.keywordBean = keywordBean; - addOverload(method); - } - - public Object execute(Object[] arguments) { - KeywordOverload selectedKeyword = null; - Integer argCount = arguments.length; - if (usesVarArgs) { - for (List kws : keywordMap.values()) { - selectedKeyword = kws.get(0); - } - } else if (keywordMap.containsKey(argCount)) { - List kwList = keywordMap.get(argCount); - if (kwList.size() == 1) { - selectedKeyword = kwList.get(0); - } else { - for (KeywordOverload overload : kwList) { - if (overload.canExecute(arguments)) { - selectedKeyword = overload; - break; - } - } - if (selectedKeyword == null) { - throw new IllegalArgumentException( - String.format("No overload of %s can take the given arguments", name)); - } - } - } else { - if (keywordMap.size() == 1) { - throw new IllegalArgumentException( - String.format("%s takes %d argument(s), received %d.", name, keywordMap.keySet().toArray()[0], - argCount)); - } else { - throw new IllegalArgumentException( - String.format("No overload of %s takes %d argument(s).", name, argCount)); - } - } - return selectedKeyword.execute(arguments); - } - - public void addOverload(Method method) { - Integer argCount = method.getParameterTypes().length; - if (usesVarArgs || (!keywordMap.isEmpty() && hasVariableArgs(method))) { - log.warn(String.format("Overloads with variable arguments not supported. Ignoring overload %s", - method.toString())); - return; - } else if (keywordMap.containsKey(argCount)) { - keywordMap.get(argCount).add(new KeywordOverload(keywordBean, method)); - } else { - List overloadList = new ArrayList<>(); - overloadList.add(new KeywordOverload(keywordBean, method)); - keywordMap.put(argCount, overloadList); - } - if (hasVariableArgs(method)) { - usesVarArgs = true; - } - } - - public String[] getArguments() { - int min = Integer.MAX_VALUE; - int max = 0; - for (int argCount : keywordMap.keySet()) { - if (argCount < min) { - min = argCount; - } - if (argCount > max) { - max = argCount; - } - } - String[] arguments = new String[max]; - for (int i = 0; i < max; i++) { - if (i < min) { - arguments[i] = String.format("arg%d", i + 1); - } else { - arguments[i] = String.format("arg%d=", i + 1); - } - } - if (usesVarArgs) { - arguments[max - 1] = "*varargs"; - } - return arguments; - } - - private boolean hasVariableArgs(Method method) { - Integer argCount = method.getParameterTypes().length; - return (argCount > 0 && method.getParameterTypes()[argCount - 1].isArray()); - } - -} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractor.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractor.java deleted file mode 100644 index e926167..0000000 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractor.java +++ /dev/null @@ -1,50 +0,0 @@ -/* Copyright 2014 Kevin Ormbrek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* This code is derived from JavalibCore - * Copyright 2008 Nokia Siemens Networks Oyj - */ -package org.robotframework.remoteserver.javalib; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.HashMap; -import java.util.Map; -import org.robotframework.javalib.beans.annotation.IKeywordExtractor; - -public class SimpleKeywordExtractor implements IKeywordExtractor { - - public Map extractKeywords(Object keywordBean) { - Map overloadableKeywords = new HashMap<>(); - Method[] methods = keywordBean.getClass().getMethods(); - - for (final Method method : methods) { - if (method.getDeclaringClass() != Object.class && Modifier.isPublic(method.getModifiers())) { - createOrUpdateKeyword(overloadableKeywords, keywordBean, method); - } - } - return overloadableKeywords; - } - - private void createOrUpdateKeyword(Map extractedKeywords, Object keywordBean, - Method method) { - String name = method.getName(); - if (extractedKeywords.containsKey(name)) { - extractedKeywords.get(name).addOverload(method); - } else { - extractedKeywords.put(name, new OverloadableKeyword(keywordBean, method)); - } - } - -} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactory.java deleted file mode 100644 index d8de852..0000000 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactory.java +++ /dev/null @@ -1,75 +0,0 @@ -/* Copyright 2014 Kevin Ormbrek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* This code is derived from JavalibCore - * Copyright 2008 Nokia Siemens Networks Oyj - */ -package org.robotframework.remoteserver.javalib; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.robotframework.javalib.beans.annotation.IKeywordExtractor; -import org.robotframework.javalib.factory.KeywordFactory; -import org.robotframework.javalib.util.IKeywordNameNormalizer; -import org.robotframework.javalib.util.KeywordNameNormalizer; - -public class SimpleKeywordFactory implements KeywordFactory { - - private Map keywords = new HashMap<>(); - private IKeywordNameNormalizer keywordNameNormalizer = new KeywordNameNormalizer(); - private List keywordNames = new ArrayList<>(); - - public SimpleKeywordFactory(Object keywordBean) { - extractKeywordsFromKeywordBean(keywordBean); - } - - public OverloadableKeyword createKeyword(String keywordName) { - String normalizedKeywordName = keywordNameNormalizer.normalize(keywordName); - return keywords.get(normalizedKeywordName); - } - - public String[] getKeywordNames() { - return keywordNames.toArray(new String[0]); - } - - protected void extractKeywordsFromKeywordBean(Object keywordBean) { - IKeywordExtractor keywordExtractor = createKeywordExtractor(); - Map extractedKeywords = keywordExtractor.extractKeywords(keywordBean); - addKeywordNames(extractedKeywords); - addKeywords(extractedKeywords); - } - - IKeywordExtractor createKeywordExtractor() { - return new SimpleKeywordExtractor(); - } - - private void addKeywords(Map extractedKeywords) { - for (String keywordName : extractedKeywords.keySet()) { - handleDuplicateKeywordNames(keywordName); - keywords.put(keywordNameNormalizer.normalize(keywordName), extractedKeywords.get(keywordName)); - } - } - - private void handleDuplicateKeywordNames(String keywordName) { - if (keywords.containsKey(keywordNameNormalizer.normalize(keywordName))) { - throw new RuntimeException("Two keywords with name '" + keywordName + "' found!"); - } - } - - private void addKeywordNames(Map extractedKeywords) { - keywordNames.addAll(extractedKeywords.keySet()); - } -} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SingleClassLibrary.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SingleClassLibrary.java deleted file mode 100644 index bf38937..0000000 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/javalib/SingleClassLibrary.java +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright 2014 Kevin Ormbrek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* This code is derived from JavalibCore - * Copyright 2008 Nokia Siemens Networks Oyj - */ -package org.robotframework.remoteserver.javalib; - -import java.lang.reflect.InvocationTargetException; -import org.robotframework.javalib.factory.KeywordFactory; -import org.robotframework.javalib.library.KeywordDocumentationRepository; -import org.robotframework.javalib.library.KeywordFactoryBasedLibrary; - -public class SingleClassLibrary extends KeywordFactoryBasedLibrary - implements KeywordDocumentationRepository { - - private KeywordFactory keywordFactory; - private Object keywordBean; - - public SingleClassLibrary(Object keywordBean) { - this.keywordBean = keywordBean; - } - - @Override protected KeywordFactory createKeywordFactory() { - if (keywordFactory == null) { - keywordFactory = new SimpleKeywordFactory(keywordBean); - } - return keywordFactory; - } - - @Override public Object runKeyword(String keywordName, Object[] args) { - try { - return super.runKeyword(keywordName, args); - } catch (RuntimeException e) { - throw retrieveInnerException(e); - } - } - - @Override public String[] getKeywordArguments(String keywordName) { - return createKeywordFactory().createKeyword(keywordName).getArguments(); - } - - @Override public String getKeywordDocumentation(String keywordName) { - return ""; - } - - private RuntimeException retrieveInnerException(RuntimeException e) { - Throwable cause = e.getCause(); - if (InvocationTargetException.class.equals(cause.getClass())) { - Throwable original = cause.getCause(); - return new RuntimeException(original.getMessage(), original); - } - return e; - } - -} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/CheckedKeyword.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/CheckedKeyword.java new file mode 100644 index 0000000..edbdce6 --- /dev/null +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/CheckedKeyword.java @@ -0,0 +1,9 @@ +package org.robotframework.remoteserver.keywords; + +import org.robotframework.javalib.keyword.DocumentedKeyword; + +public interface CheckedKeyword extends DocumentedKeyword { + + boolean canExecute(Object[] args); + +} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/CheckedKeywordImpl.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/CheckedKeywordImpl.java new file mode 100644 index 0000000..695ce59 --- /dev/null +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/CheckedKeywordImpl.java @@ -0,0 +1,91 @@ +/* Copyright 2014 Kevin Ormbrek + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* This code is derived from JavalibCore + * Copyright 2008 Nokia Siemens Networks Oyj + */ +package org.robotframework.remoteserver.keywords; + +import java.lang.reflect.Method; +import org.robotframework.javalib.reflection.ArgumentConverter; +import org.robotframework.javalib.reflection.ArgumentGrouper; +import org.robotframework.javalib.reflection.IArgumentConverter; +import org.robotframework.javalib.reflection.IArgumentGrouper; +import org.robotframework.remoteserver.anotations.KeywordDocumentation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CheckedKeywordImpl implements CheckedKeyword { + + protected static final Logger LOG = LoggerFactory.getLogger(CheckedKeywordImpl.class.getName()); + + private final IArgumentConverter argumentConverter; + private final IArgumentGrouper argumentGrouper; + private final Method method; + private final Object obj; + + public CheckedKeywordImpl(Object obj, Method method) { + this.obj = obj; + this.method = method; + this.argumentConverter = new ArgumentConverter(method.getParameterTypes()); + this.argumentGrouper = new ArgumentGrouper(method.getParameterTypes()); + } + + @Override public Object execute(Object[] args) { + try { + Object[] groupedArguments = getArgumentGrouper().groupArguments(args); + Object[] convertedArguments = getArgumentConverter().convertArguments(groupedArguments); + return method.invoke(obj, convertedArguments); + } catch (Exception e) { + LOG.error("Error invoking {} with {}", method.getName(), args, e); + throw new RuntimeException(e); + } + } + + @Override public boolean canExecute(Object[] args) { + try { + Object[] groupedArguments = getArgumentGrouper().groupArguments(args); + Object[] convertedArguments = getArgumentConverter().convertArguments(groupedArguments); + for (int i = 0; i < args.length; i++) { + if ((convertedArguments[i] == null) && (args[i] != null)) { + return false; + } + } + return true; + } catch (Exception e) { + return false; + } + } + + protected IArgumentConverter getArgumentConverter() { + return argumentConverter; + } + + protected IArgumentGrouper getArgumentGrouper() { + return argumentGrouper; + } + + @Override public String getDocumentation() { + return method.getAnnotation(KeywordDocumentation.class) != null ? method.getAnnotation( + KeywordDocumentation.class).value() : ""; + } + + @Override public String[] getArgumentNames() { + String[] names = new String[method.getParameterCount()]; + for (int i = 0; i < method.getParameters().length; i++) { + names[i] = method.getParameters()[i].getName(); + } + return names; + } +} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/KeywordExtractor.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/KeywordExtractor.java new file mode 100644 index 0000000..9a156f7 --- /dev/null +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/KeywordExtractor.java @@ -0,0 +1,10 @@ +package org.robotframework.remoteserver.keywords; + +import java.util.Map; +import org.robotframework.javalib.keyword.Keyword; +import org.robotframework.remoteserver.library.RemoteLibrary; + +public interface KeywordExtractor { + + Map extractKeywords(RemoteLibrary keywordBean); +} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeyword.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeyword.java new file mode 100644 index 0000000..a5c0269 --- /dev/null +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeyword.java @@ -0,0 +1,9 @@ +package org.robotframework.remoteserver.keywords; + +import java.lang.reflect.Method; +import org.robotframework.javalib.keyword.DocumentedKeyword; + +public interface OverloadedKeyword extends DocumentedKeyword { + + void addOverload(Method method); +} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordExtractor.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordExtractor.java new file mode 100644 index 0000000..ad888ff --- /dev/null +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordExtractor.java @@ -0,0 +1,90 @@ +/* Copyright 2014 Kevin Ormbrek + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* This code is derived from JavalibCore + * Copyright 2008 Nokia Siemens Networks Oyj + */ +package org.robotframework.remoteserver.keywords; + +import com.google.common.base.Preconditions; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.stream.Stream; +import org.robotframework.javalib.annotation.RobotKeyword; +import org.robotframework.javalib.annotation.RobotKeywordOverload; +import org.robotframework.javalib.util.IKeywordNameNormalizer; +import org.robotframework.javalib.util.KeywordNameNormalizer; +import org.robotframework.remoteserver.library.RemoteLibrary; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class OverloadedKeywordExtractor implements KeywordExtractor { + + protected static final Logger LOG = LoggerFactory.getLogger(OverloadedKeywordExtractor.class.getName()); + private static OverloadedKeywordExtractor singleton; + + protected OverloadedKeywordExtractor() { + } + + public static synchronized OverloadedKeywordExtractor createInstance() { + if (singleton == null) { + singleton = new OverloadedKeywordExtractor(); + } + return singleton; + } + + public static Stream getMethods(Class obj) { + if (obj == null) + return Stream.empty(); + Stream methods = Stream.of(obj.getMethods()); + for (Class i : obj.getInterfaces()) { + methods = Stream.concat(methods, getMethods(i)); + } + return Stream.concat(methods, getMethods(obj.getSuperclass())); + } + + @Override public Map extractKeywords(final RemoteLibrary keywordBean) { + Preconditions.checkNotNull(keywordBean); + LOG.warn("Extracting {}", keywordBean.getURI()); + IKeywordNameNormalizer keywordNameNormalizer = new KeywordNameNormalizer(); + final Map overloadableKeywords = new HashMap<>(); + final Set interfaceKeywords = new HashSet<>(), interfaceKeywordsOverload = new HashSet<>(); + getMethods(keywordBean.getClass()).forEach(method -> { + if (method.isAnnotationPresent(RobotKeyword.class)) { + interfaceKeywords.add(method.getName()); + LOG.warn("{} Detected Keyword {}", method.getName(), + keywordNameNormalizer.normalize(method.getName())); + } else if (method.isAnnotationPresent(RobotKeywordOverload.class)) { + interfaceKeywordsOverload.add(method.getName()); + LOG.warn("{} Detected KeywordOverload {}", method.getName(), + keywordNameNormalizer.normalize(method.getName())); + } + }); + Arrays.stream(keywordBean.getClass().getMethods()) + .filter(m -> (m.isAnnotationPresent(RobotKeyword.class) || interfaceKeywords.contains(m.getName())) + && !overloadableKeywords.containsKey(m.getName())) + .forEach(m -> overloadableKeywords.put(m.getName(), new OverloadedKeywordImpl(keywordBean, m))); + Arrays.stream(keywordBean.getClass().getMethods()) + .filter(m -> overloadableKeywords.containsKey(m.getName()) && ( + m.isAnnotationPresent(RobotKeywordOverload.class) || interfaceKeywordsOverload.contains( + m.getName()))) + .forEach(m -> overloadableKeywords.get(m.getName()).addOverload(m)); + return overloadableKeywords; + } + +} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordFactory.java new file mode 100644 index 0000000..a4a1e42 --- /dev/null +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordFactory.java @@ -0,0 +1,56 @@ +/* Copyright 2014 Kevin Ormbrek + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* This code is derived from JavalibCore + * Copyright 2008 Nokia Siemens Networks Oyj + */ +package org.robotframework.remoteserver.keywords; + +import com.google.common.base.Preconditions; +import java.util.HashMap; +import java.util.Map; +import org.robotframework.javalib.factory.KeywordFactory; +import org.robotframework.javalib.util.IKeywordNameNormalizer; +import org.robotframework.javalib.util.KeywordNameNormalizer; +import org.robotframework.remoteserver.library.RemoteLibrary; + +public class OverloadedKeywordFactory implements KeywordFactory { + + private final KeywordExtractor extractor; + private final Map keywords = new HashMap<>(); + private final IKeywordNameNormalizer keywordNameNormalizer = new KeywordNameNormalizer(); + + public OverloadedKeywordFactory(RemoteLibrary keywordBean, KeywordExtractor extractor) { + this.extractor = Preconditions.checkNotNull(extractor); + extractKeywordsFromKeywordBean(Preconditions.checkNotNull(keywordBean)); + } + + @Override public OverloadedKeyword createKeyword(String keywordName) { + return keywords.get(keywordNameNormalizer.normalize(keywordName)); + } + + @Override public String[] getKeywordNames() { + return keywords.keySet().toArray(new String[keywords.size()]); + } + + protected void extractKeywordsFromKeywordBean(RemoteLibrary keywordBean) { + Map extractedKeywords = extractor.extractKeywords(keywordBean); + for (String keywordName : extractedKeywords.keySet()) { + if (keywords.containsKey(keywordNameNormalizer.normalize(keywordName))) { + throw new RuntimeException("Two keywords with name '" + keywordName + "' found!"); + } + keywords.put(keywordNameNormalizer.normalize(keywordName), extractedKeywords.get(keywordName)); + } + } +} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordImpl.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordImpl.java new file mode 100644 index 0000000..346bb1d --- /dev/null +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordImpl.java @@ -0,0 +1,105 @@ +/* Copyright 2014 Kevin Ormbrek + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* This code is derived from JavalibCore + * Copyright 2008 Nokia Siemens Networks Oyj + */ +package org.robotframework.remoteserver.keywords; + +import com.google.common.collect.Iterables; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class OverloadedKeywordImpl implements OverloadedKeyword { + + protected static final Logger LOG = LoggerFactory.getLogger(OverloadedKeywordImpl.class.getName()); + + private final Map> keywordMap = new HashMap<>(); + private final String keywordName; + private final Object keywordClass; + + public OverloadedKeywordImpl(Object keywordClass, Method method) { + this.keywordName = method.getName(); + this.keywordClass = keywordClass; + addOverload(method); + } + + @Override public Object execute(Object[] arguments) { + final int argCount = arguments.length; + if (keywordMap.containsKey(argCount)) { + for (CheckedKeyword checkedKeyword : keywordMap.get(argCount)) { + if (checkedKeyword.canExecute(arguments)) + return checkedKeyword.execute(arguments); + } + } + if (keywordMap.size() == 1) { + throw new IllegalArgumentException(String.format("%s takes %d argument(s), received %d.", keywordName, + Iterables.get(keywordMap.keySet(), 0), argCount)); + } else { + throw new IllegalArgumentException( + String.format("No overload of %s takes %d argument(s).", keywordName, argCount)); + } + + } + + @Override public void addOverload(Method method) { + final int argCount = method.getParameterTypes().length; + if (hasVariableArgs(method)) { + LOG.warn(String.format("Overloads with variable arguments not supported. Ignoring overload %s", + method.toString())); + } else if (!keywordMap.containsKey(argCount)) { + keywordMap.put(argCount, new ArrayList<>()); + keywordMap.get(argCount).add(new CheckedKeywordImpl(keywordClass, method)); + } else { + keywordMap.get(argCount).add(new CheckedKeywordImpl(keywordClass, method)); + } + } + + @Override public String[] getArgumentNames() { + final int min = Collections.min(keywordMap.keySet()); + final int max = Collections.max(keywordMap.keySet()); + final String[] arguments = new String[max], minNames = Iterables.get(keywordMap.get(min), 0).getArgumentNames(), + maxNames = + Iterables.get(keywordMap.get(max), 0).getArgumentNames(); + for (int i = min; i < max; i++) { + if (i < min) + arguments[i] = minNames[i]; + else + arguments[i] = maxNames[i] + "="; + } + return arguments; + } + + private boolean hasVariableArgs(Method method) { + final int argCount = method.getParameterTypes().length; + return (argCount > 0 && method.getParameterTypes()[argCount - 1].isArray()); + } + + @Override public String getDocumentation() { + for (List keywords : keywordMap.values()) { + for (CheckedKeyword keyword : keywords) { + if (!keyword.getDocumentation().isEmpty()) { + return keyword.getDocumentation(); + } + } + } + return ""; + } +} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/AbstractClassLibrary.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/AbstractClassLibrary.java new file mode 100644 index 0000000..b669852 --- /dev/null +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/AbstractClassLibrary.java @@ -0,0 +1,67 @@ +/* Copyright 2014 Kevin Ormbrek + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* This code is derived from JavalibCore + * Copyright 2008 Nokia Siemens Networks Oyj + */ +package org.robotframework.remoteserver.library; + +import com.google.common.base.Preconditions; +import java.util.Map; +import org.robotframework.javalib.annotation.RobotKeyword; +import org.robotframework.javalib.annotation.RobotKeywords; +import org.robotframework.javalib.factory.KeywordFactory; +import org.robotframework.javalib.library.KeywordFactoryBasedLibrary; +import org.robotframework.remoteserver.RemoteServer; +import org.robotframework.remoteserver.keywords.OverloadedKeyword; +import org.robotframework.remoteserver.keywords.OverloadedKeywordExtractor; +import org.robotframework.remoteserver.keywords.OverloadedKeywordFactory; + +@RobotKeywords public abstract class AbstractClassLibrary extends KeywordFactoryBasedLibrary + implements RemoteLibrary { + + private KeywordFactory keywordFactory; + + protected AbstractClassLibrary(RemoteServer server) { + Preconditions.checkNotNull(server).putLibrary("/" + getURI().trim().replace(" ", "_"), this); + } + + @Override protected synchronized KeywordFactory createKeywordFactory() { + if (keywordFactory == null) { + keywordFactory = new OverloadedKeywordFactory(this, OverloadedKeywordExtractor.createInstance()); + } + return keywordFactory; + } + + @Override public synchronized Object runKeyword(String keywordName, Object[] args, Map kwargs) { + if (kwargs != null && !kwargs.isEmpty()) { + throw new RuntimeException("Keyword arguments not yet supported for static API libraries."); + } + return runKeyword(keywordName, args); + } + + @Override public synchronized String[] getKeywordArguments(String keywordName) { + return createKeywordFactory().createKeyword(keywordName).getArgumentNames(); + } + + @Override public synchronized String getKeywordDocumentation(String keywordName) { + return createKeywordFactory().createKeyword(keywordName).getDocumentation(); + } + + @Override public abstract String getURI(); + + @RobotKeyword public void libraryCleanup() { + close(); + } +} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactory.java deleted file mode 100644 index cefa82c..0000000 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactory.java +++ /dev/null @@ -1,113 +0,0 @@ -/* Copyright 2014 Kevin Ormbrek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.robotframework.remoteserver.library; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -public class DefaultRemoteLibraryFactory implements RemoteLibraryFactory { - - private static List[]> runKeywordParamArrays = new ArrayList<>(); - - static { - runKeywordParamArrays.add(new Class[] {String.class, Object[].class, Map.class}); - runKeywordParamArrays.add(new Class[] {String.class, List.class, Map.class}); - runKeywordParamArrays.add(new Class[] {String.class, Object[].class}); - runKeywordParamArrays.add(new Class[] {String.class, List.class}); - } - - public RemoteLibrary createRemoteLibrary(Object library) { - if (library instanceof RemoteLibrary) { - return (RemoteLibrary) library; - } - List methods = getPublicMethods(library.getClass()); - Method getKeywordNames = getGetKeywordNames(methods); - Method runKeyword = getRunKeyword(methods); - if (getKeywordNames == null || runKeyword == null) { - return new StaticApiRemoteLibrary(library); - } - Method getKeywordArguments = getGetKeywordArguments(methods); - Method getKeywordDocumentation = getGetKeywordDocumentation(methods); - return new DynamicApiRemoteLibrary(library, getKeywordNames, runKeyword, getKeywordArguments, - getKeywordDocumentation); - } - - private List getPublicMethods(Class clazz) { - List methods = new ArrayList<>(); - for (Method m : clazz.getMethods()) { - if (Modifier.isPublic(m.getModifiers())) { - methods.add(m); - } - } - return methods; - } - - private Method getGetKeywordNames(List methods) { - for (Method m : methods) { - if (((m.getName().equals("getKeywordNames") || (m.getName().equals("get_keyword_names"))) && ( - m.getReturnType() == String[].class || m.getReturnType() == List.class) - && m.getParameterTypes().length == 0)) { - return m; - } - } - return null; - } - - private Method getRunKeyword(List methods) { - Method matchingMethod = null; - for (Method m : methods) { - Class[] pTypes = m.getParameterTypes(); - if ((m.getName().equals("runKeyword") || m.getName().equals("run_keyword")) && m.getReturnType() - .equals(Object.class)) { - for (Class[] paramArray : runKeywordParamArrays) { - if (Arrays.equals(pTypes, paramArray)) { - if (pTypes.length == 3) { - return m; - } else { - matchingMethod = m; - } - break; - } - } - } - } - return matchingMethod; - } - - private Method getGetKeywordArguments(List methods) { - for (Method m : methods) { - if ((m.getName().equals("getKeywordArguments") || m.getName().equals("get_keyword_arguments")) && ( - m.getReturnType() == String[].class || m.getReturnType() == List.class) && Arrays.equals( - m.getParameterTypes(), new Class[] {String.class})) - return m; - } - return null; - } - - private Method getGetKeywordDocumentation(List methods) { - for (Method m : methods) { - if ((m.getName().equals("getKeywordDocumentation") || m.getName().equals("get_keyword_documentation")) - && m.getReturnType() == String.class && Arrays.equals(m.getParameterTypes(), - new Class[] {String.class})) - return m; - } - return null; - } - -} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibrary.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibrary.java deleted file mode 100644 index 5abb7df..0000000 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibrary.java +++ /dev/null @@ -1,102 +0,0 @@ -/* Copyright 2014 Kevin Ormbrek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.robotframework.remoteserver.library; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -public class DynamicApiRemoteLibrary implements RemoteLibrary { - - private Object library; - private Method getKeywordNames; - private Method runKeyword; - private Method getKeywordArguments; - private Method getKeywordDocumentation; - - protected DynamicApiRemoteLibrary(Object library, Method getKeywordNames, Method runKeyword, - Method getKeywordArguments, Method getKeywordDocumentation) { - this.library = library; - this.getKeywordNames = getKeywordNames; - this.runKeyword = runKeyword; - this.getKeywordArguments = getKeywordArguments; - this.getKeywordDocumentation = getKeywordDocumentation; - } - - @Override public String[] getKeywordNames() { - try { - Object names = getKeywordNames.invoke(library); - if (names instanceof List) { - return (String[]) ((List) names).toArray(); - } else { - return (String[]) names; - } - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - @Override public Object runKeyword(String keyword, Object[] args, Map kwargs) throws Throwable { - if (kwargs != null && !kwargs.isEmpty() && runKeyword.getParameterTypes().length == 2) { - throw new RuntimeException("This library does not support keyword arguments."); - } - Object[] invokeArgs = new Object[runKeyword.getParameterTypes().length]; - invokeArgs[0] = keyword; - invokeArgs[1] = runKeyword.getParameterTypes()[1].equals(List.class) ? Arrays.asList(args) : args; - if (invokeArgs.length == 3) { - invokeArgs[2] = kwargs; - } - try { - return runKeyword.invoke(library, invokeArgs); - } catch (InvocationTargetException e) { - throw e.getCause(); - } - } - - @Override public String[] getKeywordArguments(String keyword) { - if (getKeywordArguments == null) - return new String[] {"*args"}; - try { - Object args = getKeywordArguments.invoke(library, keyword); - if (args instanceof List) { - return (String[]) ((List) args).toArray(); - } else { - return (String[]) args; - } - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - @Override public String getKeywordDocumentation(String keyword) { - if (getKeywordDocumentation == null) - return ""; - try { - return (String) getKeywordDocumentation.invoke(library, keyword); - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - @Override public String getName() { - return library.getClass().getName(); - } - - @Override public Object getImplementation() { - return library; - } -} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibrary.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibrary.java index 1bd0a3b..d820239 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibrary.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/RemoteLibrary.java @@ -15,14 +15,15 @@ package org.robotframework.remoteserver.library; import java.util.Map; +import org.robotframework.javalib.library.KeywordDocumentationRepository; +import org.robotframework.javalib.library.RobotJavaLibrary; /** * An interface for handling libraries in jrobotremoteserver. There is no reason * for libraries to implement this. - * User libraries are wrapped so that they can be handled in the same way. Use - * {@link #getImplementation()} to access the wrapped library. + * User libraries are wrapped so that they can be handled in the same way. */ -public interface RemoteLibrary { +public interface RemoteLibrary extends KeywordDocumentationRepository, RobotJavaLibrary, AutoCloseable { /** * Returns the names of keywords in the library. @@ -41,7 +42,7 @@ public interface RemoteLibrary { * @param kwargs keyword arguments * @return value returned by the keyword */ - Object runKeyword(String name, Object[] arguments, Map kwargs) throws Throwable; + Object runKeyword(String name, Object[] arguments, Map kwargs); /** * Gets the argument descriptors for the given keyword name. @@ -65,15 +66,7 @@ public interface RemoteLibrary { * @return The name of the remote library, which is the same as the class * name */ - String getName(); - - /** - * Gets the underlying library implementation. The {@link RemoteLibrary} - * interface is intended to be used by wrapper classes. The original user - * library can be accessed with this method. - * - * @return The underlying library implementation - */ - Object getImplementation(); + String getURI(); + @Override void close(); } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/StaticApiRemoteLibrary.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/StaticApiRemoteLibrary.java deleted file mode 100644 index 787f6d2..0000000 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/StaticApiRemoteLibrary.java +++ /dev/null @@ -1,56 +0,0 @@ -/* Copyright 2014 Kevin Ormbrek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.robotframework.remoteserver.library; - -import java.util.Map; -import org.robotframework.remoteserver.javalib.SingleClassLibrary; - -public class StaticApiRemoteLibrary implements RemoteLibrary { - - private Object library; - private SingleClassLibrary handler; - - protected StaticApiRemoteLibrary(Object library) { - handler = new SingleClassLibrary(library); - this.library = library; - } - - @Override public String[] getKeywordNames() { - return handler.getKeywordNames(); - } - - @Override public Object runKeyword(String keywordName, Object[] args, Map kwargs) throws Throwable { - if (kwargs != null && !kwargs.isEmpty()) { - throw new RuntimeException("Keyword arguments not yet supported for static API libraries."); - } - return handler.runKeyword(keywordName, args); - } - - @Override public String[] getKeywordArguments(String keyword) { - return handler.getKeywordArguments(keyword); - } - - @Override public String getKeywordDocumentation(String keyword) { - return ""; - } - - @Override public String getName() { - return library.getClass().getName(); - } - - @Override public Object getImplementation() { - return library; - } -} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/logging/Jetty2Log4J.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/logging/Jetty2Log4J.java deleted file mode 100644 index 49a149a..0000000 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/logging/Jetty2Log4J.java +++ /dev/null @@ -1,123 +0,0 @@ -/* Copyright 2014 Kevin Ormbrek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.robotframework.remoteserver.logging; - -import org.apache.log4j.Level; -import org.eclipse.jetty.util.log.Logger; - -/** - * Jetty logger that redirects directly to Log4J without needing SLF4J on the classpath. This way users do not need to - * add more dependencies to get a unified logging solution. - */ -public class Jetty2Log4J implements Logger { - - private org.apache.log4j.Logger logger; - private Level configuredLevel; - - public Jetty2Log4J() { - this("org.eclipse.jetty.util.log"); - } - - public Jetty2Log4J(String name) { - logger = org.apache.log4j.Logger.getLogger(name); - } - - public String getName() { - return logger.getName(); - } - - public void warn(String msg, Object... args) { - logger.warn(format(msg, args)); - } - - public void warn(Throwable thrown) { - logger.warn("", thrown); - } - - public void warn(String msg, Throwable thrown) { - logger.warn(msg, thrown); - } - - public void info(String msg, Object... args) { - logger.info(format(msg, args)); - } - - public void info(Throwable thrown) { - logger.info(null, thrown); - } - - public void info(String msg, Throwable thrown) { - logger.info(msg, thrown); - } - - public boolean isDebugEnabled() { - return false; - } - - public void setDebugEnabled(boolean enabled) { - if (enabled) { - configuredLevel = logger.getLevel(); - logger.setLevel(Level.DEBUG); - } else { - logger.setLevel(configuredLevel); - } - } - - public void debug(String msg, Object... args) { - logger.debug(format(msg, args)); - } - - public void debug(Throwable thrown) { - logger.debug("", thrown); - } - - public void debug(String msg, Throwable thrown) { - logger.debug(msg, thrown); - } - - public Logger getLogger(String name) { - return new Jetty2Log4J(name); - } - - public void ignore(Throwable ignored) { - try { - logger.trace("", ignored); - } catch (NoSuchMethodError e) { - // ignore. can happen if Log4J version < 1.2.12 loaded at runtime - } - } - - private String format(String msg, Object... args) { - msg = String.valueOf(msg); // Avoids NPE - String braces = "{}"; - StringBuilder builder = new StringBuilder(); - int start = 0; - for (Object arg : args) { - int bracesIndex = msg.indexOf(braces, start); - if (bracesIndex < 0) { - builder.append(msg.substring(start)); - builder.append(" "); - builder.append(arg); - start = msg.length(); - } else { - builder.append(msg.substring(start, bracesIndex)); - builder.append(String.valueOf(arg)); - start = bracesIndex + braces.length(); - } - } - builder.append(msg.substring(start)); - return builder.toString(); - } -} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/IllegalPathException.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/IllegalPathException.java index 34e3f11..d5456d2 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/IllegalPathException.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/IllegalPathException.java @@ -3,7 +3,7 @@ /** * Thrown when a path is not valid for mapping to a library */ -@SuppressWarnings("serial") public class IllegalPathException extends RuntimeException { +public class IllegalPathException extends RuntimeException { public IllegalPathException(String message) { super(message); diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/JRobotServlet.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/JRobotServlet.java new file mode 100644 index 0000000..9710c56 --- /dev/null +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/JRobotServlet.java @@ -0,0 +1,52 @@ +package org.robotframework.remoteserver.servlet; + +import java.util.Map; + +/** + * Contains the XML-RPC methods for remote library interface. + */ +public interface JRobotServlet { + + /** + * Get an array containing the names of the keywords that the library + * implements. + * + * @return String array containing keyword names in the library + */ + String[] get_keyword_names(); + + /** + * Run the given keyword and return the results. + * + * @param keyword keyword to run + * @param args arguments packed in an array to pass to the keyword method + * @param kwargs keyword arguments to pass to the keyword method + * @return remote result Map containing the execution results + */ + Map run_keyword(String keyword, Object[] args, Map kwargs); + + /** + * Run the given keyword and return the results. + * + * @param keyword keyword to run + * @param args arguments packed in an array to pass to the keyword method + * @return remote result Map containing the execution results + */ + Map run_keyword(String keyword, Object[] args); + + /** + * Get an array of argument specifications for the given keyword. + * + * @param keyword The keyword to lookup. + * @return A string array of argument specifications for the given keyword. + */ + String[] get_keyword_arguments(String keyword); + + /** + * Get documentation for given keyword. + * + * @param keyword The keyword to get documentation for. + * @return A documentation string for the given keyword. + */ + String get_keyword_documentation(String keyword); +} diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/context/RemoteServerContext.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerContext.java similarity index 80% rename from jrobot-remote-server/src/main/java/org/robotframework/remoteserver/context/RemoteServerContext.java rename to jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerContext.java index 05631a8..1567aeb 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/context/RemoteServerContext.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerContext.java @@ -12,27 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.robotframework.remoteserver.context; +package org.robotframework.remoteserver.servlet; import java.util.Map; +import javax.servlet.Servlet; import javax.servlet.http.HttpServletRequest; import org.robotframework.remoteserver.library.RemoteLibrary; -public interface RemoteServerContext { - - /** - * Returns true if this server allows remote stopping. - * - * @return true if this server allows remote stopping - */ - boolean getAllowStop(); - - /** - * Allow or disallow stopping the server remotely. - * - * @param allowed true to allow stopping the server remotely - */ - void setAllowStop(boolean allowed); +public interface RemoteServerContext extends Servlet { /** * Gets a copy of the current library map. Keys in the map are the paths and @@ -67,7 +54,7 @@ public interface RemoteServerContext { * @return the previous library mapped to the path, or null if there was no * mapping for the path */ - RemoteLibrary putLibrary(String path, Object library); + RemoteLibrary putLibrary(String path, RemoteLibrary library); /** * Removes the library mapped to the given path if the mapping exists diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerRequestProcessorFactoryFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerRequestProcessorFactoryFactory.java index 486c0bf..cd0d62c 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerRequestProcessorFactoryFactory.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerRequestProcessorFactoryFactory.java @@ -21,7 +21,7 @@ public class RemoteServerRequestProcessorFactoryFactory implements RequestProcessorFactoryFactory { private final RequestProcessorFactory factory = new RemoteServerRequestProcessorFactory(); - private final ServerMethods serverMethods; + private final JRobotServlet serverMethods; public RemoteServerRequestProcessorFactoryFactory(RemoteServerServlet servlet) { this.serverMethods = new ServerMethods(servlet); @@ -34,7 +34,7 @@ public RemoteServerRequestProcessorFactoryFactory(RemoteServerServlet servlet) { private class RemoteServerRequestProcessorFactory implements RequestProcessorFactory { - public Object getRequestProcessor(XmlRpcRequest xmlRpcRequest) throws XmlRpcException { + public JRobotServlet getRequestProcessor(XmlRpcRequest xmlRpcRequest) throws XmlRpcException { return serverMethods; } } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java index a0bcf47..7ce15c3 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java @@ -14,9 +14,10 @@ */ package org.robotframework.remoteserver.servlet; +import com.google.common.base.Preconditions; import java.io.IOException; import java.io.PrintWriter; -import java.util.HashMap; +import java.util.Collections; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; @@ -29,10 +30,7 @@ import org.apache.xmlrpc.server.XmlRpcHandlerMapping; import org.apache.xmlrpc.webserver.XmlRpcServlet; import org.apache.xmlrpc.webserver.XmlRpcServletServer; -import org.robotframework.remoteserver.context.RemoteServerContext; -import org.robotframework.remoteserver.library.DefaultRemoteLibraryFactory; import org.robotframework.remoteserver.library.RemoteLibrary; -import org.robotframework.remoteserver.library.RemoteLibraryFactory; import org.robotframework.remoteserver.xmlrpc.ReflectiveHandlerMapping; import org.robotframework.remoteserver.xmlrpc.TypeFactory; @@ -44,11 +42,9 @@ */ public class RemoteServerServlet extends XmlRpcServlet implements RemoteServerContext { - private static final long serialVersionUID = -7981676271855172976L; private static final ThreadLocal request = new ThreadLocal<>(); private static final ThreadLocal currLibrary = new ThreadLocal<>(); - private Map libraryMap = new ConcurrentHashMap<>(); - private boolean allowStop = true; + private final Map libraryMap = new ConcurrentHashMap<>(); /** * Cleans up the path of an incoming request. Repeating /s are reduced to @@ -59,18 +55,20 @@ public class RemoteServerServlet extends XmlRpcServlet implements RemoteServerCo * @return cleaned up path */ private static String cleanPath(String path) { - path = path == null ? "/" : path; + if (path == null) { + return "/"; + } if (!path.startsWith("/")) { path = "/" + path; } path = path.replaceAll("/+", "/"); if (path.length() > 1 && path.endsWith("/")) { - path = path.substring(0, path.length() - 1); + return path.substring(0, path.length() - 1); } return path; } - private static void checkPath(String path) { + private static String checkPath(String path) { if (path == null || !path.startsWith("/")) { throw new IllegalPathException(String.format("Path [%s] does not start with a /.", path)); } else if (path.contains("//")) { @@ -82,13 +80,11 @@ private static void checkPath(String path) { "Path [%s] contains disallowed characters (must contain only alphanumeric or any of these: -._~/).", path)); } + return path; } - public RemoteLibrary putLibrary(String path, Object library) { - checkPath(path); - RemoteLibraryFactory libraryFactory = createLibraryFactory(); - RemoteLibrary remoteLibrary = libraryFactory.createRemoteLibrary(library); - return libraryMap.put(path, remoteLibrary); + public RemoteLibrary putLibrary(String path, RemoteLibrary library) { + return libraryMap.put(checkPath(path), Preconditions.checkNotNull(library)); } public RemoteLibrary removeLibrary(String path) { @@ -96,15 +92,7 @@ public RemoteLibrary removeLibrary(String path) { } public Map getLibraryMap() { - return new HashMap<>(libraryMap); - } - - public boolean getAllowStop() { - return allowStop; - } - - public void setAllowStop(boolean allowed) { - allowStop = allowed; + return Collections.unmodifiableMap(libraryMap); } @Override protected XmlRpcServletServer newXmlRpcServer(ServletConfig pConfig) throws XmlRpcException { @@ -123,8 +111,8 @@ public void setAllowStop(boolean allowed) { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - request.set(req); try { + request.set(req); super.service(req, resp); } finally { request.remove(); @@ -177,7 +165,7 @@ private String getPage() { sb.append(""); sb.append(path); sb.append(""); - sb.append(StringEscapeUtils.escapeHtml4(map.get(path).getName())); + sb.append(StringEscapeUtils.escapeHtml4(map.get(path).getURI())); sb.append(""); } } @@ -196,8 +184,4 @@ public RemoteLibrary getLibrary() { return currLibrary.get(); } - protected RemoteLibraryFactory createLibraryFactory() { - return new DefaultRemoteLibraryFactory(); - } - } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java index fa2d685..847ca08 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java @@ -20,78 +20,52 @@ import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.robotframework.javalib.util.StdStreamRedirecter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Contains the XML-RPC methods that implement the remote library interface. * * @author David Luu */ -public class ServerMethods { +public class ServerMethods implements JRobotServlet { - private static List + protected static final Logger LOG = LoggerFactory.getLogger(ServerMethods.class.getName()); + private static final List genericExceptions = Arrays.asList("AssertionError", "AssertionFailedError", "Exception", "Error", "RuntimeError", "RuntimeException", "DataError", "TimeoutError", "RemoteError"); - String[] logLevelPrefixes = new String[] {"*TRACE*", "*DEBUG*", "*INFO*", "*HTML*", "*WARN*"}; - private Log log; - private RemoteServerServlet servlet; + private static final String[] logLevelPrefixes = new String[] {"*TRACE*", "*DEBUG*", "*INFO*", "*HTML*", "*WARN*"}; + private final RemoteServerServlet servlet; public ServerMethods(RemoteServerServlet servlet) { - log = LogFactory.getLog(ServerMethods.class); this.servlet = servlet; } - /** - * Get an array containing the names of the keywords that the library - * implements. - * - * @return String array containing keyword names in the library - */ - public String[] get_keyword_names() { - try { - String[] names = servlet.getLibrary().getKeywordNames(); - if (names == null || names.length == 0) - throw new RuntimeException("No keywords found in the test library"); - String[] newNames = Arrays.copyOf(names, names.length + 1); - newNames[names.length] = "stop_remote_server"; - return newNames; - } catch (Throwable e) { - log.warn("", e); - throw new RuntimeException(e); - } + @Override public String[] get_keyword_names() { + final String[] names = servlet.getLibrary().getKeywordNames(); + if (names == null || names.length == 0) + throw new RuntimeException("No keywords found in the test library"); + return names; } - /** - * Run the given keyword and return the results. - * - * @param keyword keyword to run - * @param args arguments packed in an array to pass to the keyword method - * @param kwargs keyword arguments to pass to the keyword method - * @return remote result Map containing the execution results - */ - public Map run_keyword(String keyword, Object[] args, Map kwargs) { + @Override public Map run_keyword(String keyword, Object[] args, Map kwargs) { Map result = new HashMap<>(); StdStreamRedirecter redirector = new StdStreamRedirecter(); redirector.redirectStdStreams(); try { result.put("status", "PASS"); - Object retObj = ""; - if (keyword.equalsIgnoreCase("stop_remote_server")) { - retObj = stopRemoteServer(); - } else { - try { + Object retObj; + try { + retObj = servlet.getLibrary().runKeyword(keyword, args, kwargs); + } catch (Exception e) { + if (illegalArgumentIn(e)) { + for (int i = 0; i < args.length; i++) + args[i] = arraysToLists(args[i]); retObj = servlet.getLibrary().runKeyword(keyword, args, kwargs); - } catch (Exception e) { - if (illegalArgumentIn(e)) { - for (int i = 0; i < args.length; i++) - args[i] = arraysToLists(args[i]); - retObj = servlet.getLibrary().runKeyword(keyword, args, kwargs); - } else { - throw (e); - } + } else { + throw (e); } } if (retObj != null && !retObj.equals("")) { @@ -137,88 +111,24 @@ public Map run_keyword(String keyword, Object[] args, Map run_keyword(String keyword, Object[] args) { + @Override public Map run_keyword(String keyword, Object[] args) { + //TODO implement varargs return run_keyword(keyword, args, null); } - /** - * Get an array of argument specifications for the given keyword. - * - * @param keyword The keyword to lookup. - * @return A string array of argument specifications for the given keyword. - */ - public String[] get_keyword_arguments(String keyword) { - if (keyword.equalsIgnoreCase("stop_remote_server")) { - return new String[0]; - } - try { - String[] args = servlet.getLibrary().getKeywordArguments(keyword); - return args == null ? new String[0] : args; - } catch (Throwable e) { - log.warn("", e); - throw new RuntimeException(e); - } + @Override public String[] get_keyword_arguments(String keyword) { + final String[] args = servlet.getLibrary().getKeywordArguments(keyword); + return args == null ? new String[0] : args; } - /** - * Get documentation for given keyword. - * - * @param keyword The keyword to get documentation for. - * @return A documentation string for the given keyword. - */ - public String get_keyword_documentation(String keyword) { - if (keyword.equalsIgnoreCase("stop_remote_server")) { - return "Stops the remote server.\n\nThe server may be configured so that users cannot stop it."; - } - try { - String doc = servlet.getLibrary().getKeywordDocumentation(keyword); - return doc == null ? "" : doc; - } catch (Throwable e) { - log.warn("", e); - throw new RuntimeException(e); - } - } - - /** - * Stops the remote server if it is configured to allow that. - * - * @return remote result Map containing the execution results - */ - public Map stop_remote_server() { - return run_keyword("stop_remote_server", null); - } - - protected boolean stopRemoteServer() throws Exception { - if (servlet.getAllowStop()) { - System.out.print("Robot Framework remote server stopping"); - new Thread("remote-server-stopper") { - - @Override public void run() { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // ignore - } - System.exit(0); - } - }.start(); - } else { - System.out.print("This Robot Framework remote server does not allow stopping"); - } - return true; + @Override public String get_keyword_documentation(String keyword) { + final String doc = servlet.getLibrary().getKeywordDocumentation(keyword); + return doc == null ? "" : doc; } private String getError(Throwable thrown) { - String simpleName = thrown.getClass().getSimpleName(); - boolean suppressName = isFlagSet("ROBOT_SUPPRESS_NAME", thrown); - if (genericExceptions.contains(simpleName) || suppressName) { + final String simpleName = thrown.getClass().getSimpleName(); + if (genericExceptions.contains(simpleName) || isFlagSet("ROBOT_SUPPRESS_NAME", thrown)) { return StringUtils.defaultIfEmpty(thrown.getMessage(), simpleName); } else { return String.format("%s: %s", thrown.getClass().getName(), thrown.getMessage()); diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/MapSerializer.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/MapSerializer.java index a270a25..2128879 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/MapSerializer.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/MapSerializer.java @@ -14,7 +14,6 @@ */ package org.robotframework.remoteserver.xmlrpc; -import java.util.Iterator; import java.util.Map; import org.apache.xmlrpc.common.TypeFactory; import org.apache.xmlrpc.common.XmlRpcStreamConfig; @@ -57,9 +56,8 @@ private void writeValue(ContentHandler pHandler, Object pValue) throws SAXExcept protected void writeData(ContentHandler pHandler, Object pData) throws SAXException { Map map = (Map) pData; - for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) { - Map.Entry entry = (Map.Entry) iter.next(); - writeEntry(pHandler, entry.getKey(), entry.getValue()); + for (Map.Entry entry1 : map.entrySet()) { + writeEntry(pHandler, entry1.getKey(), entry1.getValue()); } } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/StringSerializer.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/StringSerializer.java index 4535cc9..14635b9 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/StringSerializer.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/StringSerializer.java @@ -25,35 +25,33 @@ public class StringSerializer extends TypeSerializerImpl { - public static final String STRING_TAG = "string"; public static final String BASE_64_TAG = "base64"; - private static Pattern pattern = Pattern.compile("[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]"); + private static final Pattern pattern = Pattern.compile("[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]"); public void write(ContentHandler pHandler, Object pObject) throws SAXException { String value = pObject.toString(); if (pattern.matcher(value).find()) { pHandler.startElement("", VALUE_TAG, VALUE_TAG, ZERO_ATTRIBUTES); pHandler.startElement("", BASE_64_TAG, BASE_64_TAG, ZERO_ATTRIBUTES); - byte[] buffer = null; try { - buffer = value.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e1) { - // ignore - } - if (buffer.length > 0) { - char[] charBuffer = new char[buffer.length >= 1024 ? 1024 : ((buffer.length + 3) / 4) * 4]; - Encoder encoder = new Base64.SAXEncoder(charBuffer, 0, null, pHandler); - try { - encoder.write(buffer, 0, buffer.length); - encoder.flush(); - } catch (Base64.SAXIOException e) { - throw e.getSAXException(); - } catch (IOException e) { - throw new SAXException(e); + byte[] buffer = value.getBytes("UTF-8"); + if (buffer.length > 0) { + char[] charBuffer = new char[buffer.length >= 1024 ? 1024 : ((buffer.length + 3) / 4) * 4]; + Encoder encoder = new Base64.SAXEncoder(charBuffer, 0, null, pHandler); + try { + encoder.write(buffer, 0, buffer.length); + encoder.flush(); + } catch (Base64.SAXIOException e) { + throw e.getSAXException(); + } catch (IOException e) { + throw new SAXException(e); + } } + pHandler.endElement("", BASE_64_TAG, BASE_64_TAG); + pHandler.endElement("", VALUE_TAG, VALUE_TAG); + } catch (UnsupportedEncodingException e1) { + // TODO log exception } - pHandler.endElement("", BASE_64_TAG, BASE_64_TAG); - pHandler.endElement("", VALUE_TAG, VALUE_TAG); } else { write(pHandler, null, value); } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java index 806adb4..fc18aff 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java @@ -53,7 +53,6 @@ public void write(ContentHandler pHandler, Object pObject) throws SAXException { } }; private static final TypeParser BYTE_ARRAY_PARSER = new ByteArrayToStringParser(); - private TypeSerializer primitiveArraySerializer; public TypeFactory(XmlRpcController pController) { super(pController); @@ -82,32 +81,31 @@ else if (pObject instanceof char[]) return CHAR_ARRAY_SERIALIZER; else if (pObject.getClass().isArray()) { // object[] & char[] handled // before this - primitiveArraySerializer = new ObjectArraySerializer(this, pConfig) { + return new ObjectArraySerializer(TypeFactory.this, pConfig) { - @Override protected void writeData(ContentHandler pHandler, Object pObject) throws SAXException { + @Override protected void writeData(ContentHandler pHandler, Object pObject1) throws SAXException { Object[] array; - if (pObject instanceof byte[]) - array = ArrayUtils.toObject((byte[]) pObject); - else if (pObject instanceof short[]) - array = ArrayUtils.toObject((short[]) pObject); - else if (pObject instanceof int[]) - array = ArrayUtils.toObject((int[]) pObject); - else if (pObject instanceof long[]) - array = ArrayUtils.toObject((long[]) pObject); - else if (pObject instanceof float[]) - array = ArrayUtils.toObject((float[]) pObject); - else if (pObject instanceof double[]) - array = ArrayUtils.toObject((double[]) pObject); - else if (pObject instanceof boolean[]) - array = ArrayUtils.toObject((boolean[]) pObject); + if (pObject1 instanceof byte[]) + array = ArrayUtils.toObject((byte[]) pObject1); + else if (pObject1 instanceof short[]) + array = ArrayUtils.toObject((short[]) pObject1); + else if (pObject1 instanceof int[]) + array = ArrayUtils.toObject((int[]) pObject1); + else if (pObject1 instanceof long[]) + array = ArrayUtils.toObject((long[]) pObject1); + else if (pObject1 instanceof float[]) + array = ArrayUtils.toObject((float[]) pObject1); + else if (pObject1 instanceof double[]) + array = ArrayUtils.toObject((double[]) pObject1); + else if (pObject1 instanceof boolean[]) + array = ArrayUtils.toObject((boolean[]) pObject1); else // should never happen throw new SAXException(String.format("Array of type %s[] not handled!", - pObject.getClass().getComponentType().getName())); + pObject1.getClass().getComponentType().getName())); super.writeData(pHandler, array); } }; - return primitiveArraySerializer; } else return STRING_SERIALIZER; } diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteLibraryClient.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteLibraryClient.java deleted file mode 100644 index 3b78a58..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteLibraryClient.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.robotframework.remoteserver; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Map; - -import org.apache.xmlrpc.XmlRpcException; -import org.apache.xmlrpc.client.XmlRpcClient; -import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; - -public class RemoteLibraryClient { - - public static XmlRpcClient getClient(String path) { - return getClient(path, 8270); - } - - public static XmlRpcClient getClient(String path, int port) { - XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); - try { - config.setServerURL(new URL("http://127.0.0.1:" + Integer.toString(port) + path)); - } catch (MalformedURLException e) { - // ignore - } - XmlRpcClient client = new XmlRpcClient(); - client.setConfig(config); - return client; - } - - public static Map runKeyword(String path, String keywordName, Object... params) { - return runKeyword(8270, path, keywordName, params); - } - - public static Map runKeyword(int port, String path, String keywordName, Object... params) { - XmlRpcClient client = getClient(path, port); - Map result = null; - try { - result = (Map) client.execute("run_keyword", new Object[] { keywordName, params }); - } catch (XmlRpcException e) { - e.printStackTrace(); - } - return result; - } - -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteServerImplTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteServerImplTest.java deleted file mode 100644 index 5fb8ac2..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/RemoteServerImplTest.java +++ /dev/null @@ -1,96 +0,0 @@ -package org.robotframework.remoteserver; - -import java.util.Map; -import org.robotframework.remoteserver.testlibraries.StaticOne; -import org.robotframework.remoteserver.testlibraries.StaticTwo; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import static org.robotframework.remoteserver.RemoteLibraryClient.runKeyword; - -public class RemoteServerImplTest { - RemoteServerImpl server; - - @Test - public void allowRemoteStop() throws Exception { - Assert.assertEquals(server.getAllowStop(), true); - server.setAllowStop(false); - server.putLibrary("/", new StaticOne()); - server.start(); - String result = (String) runKeyword("/", "stop_remote_server").get("output"); - Assert.assertEquals(result, "This Robot Framework remote server does not allow stopping"); - Thread.sleep(2000); - result = (String) runKeyword("/", "getName").get("return"); - Assert.assertEquals(result, "StaticOne"); - server.setAllowStop(true); - // actually stopping the server through the keyword will exit the JVM - // executing the acceptance tests will stop the server - } - - @Test - public void serverIsRestartable() throws Exception { - server.putLibrary("/1", new StaticOne()); - server.start(); - String result = (String) runKeyword("/1", "getName").get("return"); - Assert.assertEquals(result, "StaticOne"); - server.stop(); - server.putLibrary("/2", new StaticTwo()); - server.start(); - result = (String) runKeyword("/2", "getName").get("return"); - Assert.assertEquals(result, "StaticTwo"); - server.stop(); - } - - @Test - public void putLibrariesAfterStarting() throws Exception { - server.start(); - server.putLibrary("/1", new StaticOne()); - String result = (String) runKeyword("/1", "getName").get("return"); - Assert.assertEquals(result, "StaticOne"); - } - - @Test - public void ephemeralPort() throws Exception { - RemoteServerImpl server = new RemoteServerImpl(); - Assert.assertEquals(server.getPort(), -1); - server.putLibrary("/", new StaticOne()); - server.start(); - int port = server.getPort(); - String result = (String) runKeyword(port, "/", "getName").get("return"); - Assert.assertEquals(result, "StaticOne"); - server.stop(); - Assert.assertEquals(server.getPort(), -2); - } - - @Test - public void libraryMap() { - server.putLibrary("/", new StaticOne()); - Assert.assertTrue(server.getLibraryMap().containsKey("/")); - } - - @Test - public void onlyRequiredEntriesInResultsWhenPassed() throws Exception { - server.putLibrary("/1", new StaticOne()); - server.start(); - Map results = runKeyword("/1", "noReturnValue"); - Assert.assertEquals(results.get("status"), "PASS"); - Assert.assertEquals(results.size(), 1); - } - - @BeforeMethod - public void setup() throws Exception { - server = new RemoteServerImpl(); - server.setPort(8270); - } - - @AfterMethod - public void cleanup() throws InterruptedException { - try { - server.stop(); - } catch (Throwable t) { - // ignore - } - } -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/cli/CommandLineHelpertTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/cli/CommandLineHelpertTest.java deleted file mode 100644 index 5bebb10..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/cli/CommandLineHelpertTest.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.robotframework.remoteserver.cli; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class CommandLineHelpertTest { - - @Test - public void libraryRequired() { - CommandLineHelper clh = new CommandLineHelper(new String[] { "-H", "host" }); - Assert.assertEquals(clh.getError(), "You must specify at least one library"); - } - - @Test - public void moreThanOneLibrary() { - CommandLineHelper clh = new CommandLineHelper(new String[] { "-l", "java.lang.String:/one", "--library", - "java.lang.Object:/two" }); - Assert.assertEquals(clh.getLibraryMap().size(), 2); - Assert.assertEquals(clh.getLibraryMap().get("/one").getClass(), String.class); - Assert.assertEquals(clh.getLibraryMap().get("/two").getClass(), Object.class); - } - - @Test - public void setPort() { - CommandLineHelper clh = new CommandLineHelper(new String[] { "--library", "java.lang.String:/one", "--port", - "4444" }); - Assert.assertEquals(clh.getError(), null); - Assert.assertEquals(clh.getPort(), 4444); - } - - @Test - public void missingValues() { - CommandLineHelper clh = new CommandLineHelper(new String[] { "-l", "java.lang.String:5", "--host" }); - Assert.assertEquals(clh.getError(), "Missing value for option host"); - clh = new CommandLineHelper(new String[] { "-l", "java.lang.String:5", "-a", "-H", "host" }); - Assert.assertEquals(clh.getError(), "Missing value for option allowstop"); - } - - @Test - public void badValues() { - CommandLineHelper clh = new CommandLineHelper(new String[] { "--port", "blah" }); - Assert.assertEquals(clh.getError(), "Port must be 1-65535"); - clh = new CommandLineHelper(new String[] { "--allowstop", "yes" }); - Assert.assertEquals(clh.getError(), "Value for option allowstop must be true or false"); - } - - @Test - public void defaultPath() { - CommandLineHelper clh = new CommandLineHelper(new String[] { "-l", "java.lang.String" }); - Assert.assertEquals(clh.getError(), null); - Assert.assertEquals(clh.getLibraryMap().size(), 1); - Assert.assertEquals(clh.getLibraryMap().get("/").getClass(), String.class); - } - - @Test - public void samePath() { - CommandLineHelper clh = new CommandLineHelper(new String[] { "-l", "java.lang.String:/5", "--library", - "java.lang.Object:/5" }); - Assert.assertEquals(clh.getError(), "Duplicate path [/5]"); - } - - @Test - public void missingPath() { - CommandLineHelper clh = new CommandLineHelper(new String[] { "-l", "java.lang.String:" }); - Assert.assertEquals(clh.getError(), "Missing path for library java.lang.String"); - clh = new CommandLineHelper(new String[] { "-l", "java.lang.String: " }); - Assert.assertEquals(clh.getError(), "Missing path for library java.lang.String"); - } - - @Test - public void badClassName() { - CommandLineHelper clh = new CommandLineHelper(new String[] { "-l", "BadClassName" }); - Assert.assertEquals(clh.getError(), - "Failed to load class with name BadClassName: java.lang.ClassNotFoundException: BadClassName"); - } - - @Test - public void libraryWithPort() { - CommandLineHelper clh = new CommandLineHelper(new String[] { "-l", "java.lang.String:8270" }); - Assert.assertEquals(clh.getError(), null); - Assert.assertEquals(clh.getLibraryMap().size(), 1); - Assert.assertEquals(clh.getLibraryMap().get("/").getClass(), String.class); - Assert.assertEquals(clh.getPort(), 8270); - } - - @Test - public void multipleLibrariesWithPort() { - CommandLineHelper clh = new CommandLineHelper(new String[] { "-l", "java.lang.String:8270", "-l", - "java.lang.String:8271" }); - Assert.assertEquals(clh.getError(), - "Cannot use the port option or use multiple libraries when specifying libraries in the form classname:port"); - } - - @Test - public void setPortAndLibraryWithPort() { - CommandLineHelper clh = new CommandLineHelper(new String[] { "-l", "java.lang.String:8270", "-p", - "8270" }); - Assert.assertEquals(clh.getError(), - "Cannot use the port option or use multiple libraries when specifying libraries in the form classname:port"); - } - -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/OverloadableKeywordTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/OverloadableKeywordTest.java deleted file mode 100644 index d37a713..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/OverloadableKeywordTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.robotframework.remoteserver.javalib; - -import java.lang.reflect.Method; - -import org.robotframework.remoteserver.testlibraries.OverloadedMethods; -import org.testng.Assert; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -public class OverloadableKeywordTest -{ - private OverloadedMethods library = new OverloadedMethods(); - private Method shortOverload; - private Method intOverload; - private OverloadableKeyword keyword; - - @BeforeTest - public void setup() throws Exception { - shortOverload = library.getClass().getDeclaredMethod("numberType", short.class); - intOverload = library.getClass().getDeclaredMethod("numberType", int.class); - keyword = new OverloadableKeyword(library, shortOverload); - keyword.addOverload(intOverload); - } - - // this needs to be tested here because there are no guarantees about the - // order of methods returned by getMethods() - @Test - public void picksFirstCompatibleOverload() throws Exception { - String result = (String) keyword.execute(new Object[] {"32767"}); - Assert.assertEquals(result, "short overload"); - result = (String) keyword.execute(new Object[] {"32768"}); - Assert.assertEquals(result, "int overload"); - } - - @Test - public void noCompatibleOverload() throws Exception { - String message = null; - Class exceptionClass = null; - try { - keyword.execute(new Object[] {"SNARF"}); - } catch (Exception e) { - exceptionClass = e.getClass(); - message = e.getMessage(); - } - Assert.assertEquals(exceptionClass, IllegalArgumentException.class); - Assert.assertEquals(message, "No overload of numberType can take the given arguments"); - } -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractorTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractorTest.java deleted file mode 100644 index 45eeda5..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordExtractorTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.robotframework.remoteserver.javalib; - -import java.util.Map; - -import org.robotframework.javalib.keyword.Keyword; -import org.robotframework.remoteserver.testlibraries.ConflictingOverloadVariableArguments; -import org.robotframework.remoteserver.testlibraries.OverloadedMethods; -import org.robotframework.remoteserver.testlibraries.StaticOne; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class SimpleKeywordExtractorTest { - - @Test - public void overloadedMethodWrongNumberOfArgs() { - SimpleKeywordExtractor keywordExtractor = new SimpleKeywordExtractor(); - Map keywordMap = keywordExtractor.extractKeywords(new OverloadedMethods()); - try { - keywordMap.get("myKeyword").execute(new Object[] {"name", 42}); - } catch (RuntimeException e) { - Assert.assertEquals(e.getMessage(), "No overload of myKeyword takes 2 argument(s)."); - return; - } - throw new RuntimeException("No exception thrown"); - } - - @Test - public void nonOverloadedMethodWrongNumberOfArgs() { - SimpleKeywordExtractor keywordExtractor = new SimpleKeywordExtractor(); - Map keywordMap = keywordExtractor.extractKeywords(new StaticOne()); - try { - keywordMap.get("getName").execute(new Object[] {"badArg"}); - } catch (RuntimeException e) { - Assert.assertEquals(e.getMessage(), "getName takes 0 argument(s), received 1."); - return; - } - throw new RuntimeException("No exception thrown"); - } - -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactoryTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactoryTest.java deleted file mode 100644 index d0e80bb..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SimpleKeywordFactoryTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.robotframework.remoteserver.javalib; - -import org.robotframework.javalib.factory.KeywordFactory; -import org.robotframework.remoteserver.testlibraries.DuplicateKeywords; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class SimpleKeywordFactoryTest { - - @Test - public void duplicateKeywords() { - String msg = ""; - try { - KeywordFactory keywordFactory = new SimpleKeywordFactory(new DuplicateKeywords()); - } catch (RuntimeException e) { - msg = e.getMessage(); - } - Assert.assertTrue(msg.matches("Two keywords with name 'my(_k|K)eyword' found!")); - } -} \ No newline at end of file diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SingleClassLibraryTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SingleClassLibraryTest.java deleted file mode 100644 index 05fe379..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/javalib/SingleClassLibraryTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.robotframework.remoteserver.javalib; - -import org.robotframework.remoteserver.testlibraries.OverloadedMethods; -import org.robotframework.remoteserver.testlibraries.StaticOne; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class SingleClassLibraryTest { - - @Test - public void getKeywordArgumentsWithOverloadedMethods() { - SingleClassLibrary lib = new SingleClassLibrary(new OverloadedMethods()); - String[] args = lib.getKeywordArguments("defaults"); - Assert.assertEquals(args, new String[] {"arg1", "arg2="}); - args = lib.getKeywordArguments("numberType"); - Assert.assertEquals(args, new String[] {"arg1"}); - args = lib.getKeywordArguments("myKeyword"); - Assert.assertEquals(args, new String[] {"arg1="}); - } - - @Test - public void getKeywordArgumentsSingleMethod() { - SingleClassLibrary lib = new SingleClassLibrary(new StaticOne()); - String[] args = lib.getKeywordArguments("getName"); - Assert.assertEquals(args, new String[] {}); - args = lib.getKeywordArguments("squareOf"); - Assert.assertEquals(args, new String[] {"arg1"}); - args = lib.getKeywordArguments("variableArgs"); - Assert.assertEquals(args, new String[] {"arg1", "*varargs"}); - args = lib.getKeywordArguments("onlyVariableArgs"); - Assert.assertEquals(args, new String[] {"*varargs"}); - } - -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactoryTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactoryTest.java deleted file mode 100644 index bd619fc..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DefaultRemoteLibraryFactoryTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.robotframework.remoteserver.library; - -import org.robotframework.remoteserver.testlibraries.DynamicOneRunKeywordNoKwargs; -import org.robotframework.remoteserver.testlibraries.DynamicUsingLists; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class DefaultRemoteLibraryFactoryTest { - - @Test - public void wrappedLibrariesAreNotWrapped() { - DefaultRemoteLibraryFactory fact = new DefaultRemoteLibraryFactory(); - RemoteLibrary first = fact.createRemoteLibrary(new DynamicOneRunKeywordNoKwargs()); - RemoteLibrary second = fact.createRemoteLibrary(first); - Assert.assertFalse(second.getImplementation() instanceof RemoteLibrary); - } - - @Test - public void dynamicLibrariesUsingLists() { - DefaultRemoteLibraryFactory fact = new DefaultRemoteLibraryFactory(); - RemoteLibrary lib = fact.createRemoteLibrary(new DynamicUsingLists()); - Assert.assertTrue(lib instanceof DynamicApiRemoteLibrary); - } - -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibraryTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibraryTest.java deleted file mode 100644 index 64ca166..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/DynamicApiRemoteLibraryTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.robotframework.remoteserver.library; - -import static org.testng.Assert.assertEquals; - -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.testng.Assert; - -import org.robotframework.remoteserver.testlibraries.DynamicOneRunKeywordKwargs; -import org.robotframework.remoteserver.testlibraries.DynamicOneRunKeywordKwargsList; -import org.robotframework.remoteserver.testlibraries.DynamicOneRunKeywordNoKwargs; -import org.robotframework.remoteserver.testlibraries.DynamicUsingLists; -import org.testng.annotations.Test; - -public class DynamicApiRemoteLibraryTest { - - private static Object[] noPosArgs = new Object[] {}; - private static Map noKwargs = new HashMap(); - - @Test - public void getDynamicAPILibraryImplementation() throws Exception { - DynamicOneRunKeywordNoKwargs lib = new DynamicOneRunKeywordNoKwargs(); - Method gkn = DynamicOneRunKeywordNoKwargs.class.getMethod("getKeywordNames"); - Method rk = DynamicOneRunKeywordNoKwargs.class.getMethod("runKeyword", String.class, Object[].class); - DynamicApiRemoteLibrary wrapper = new DynamicApiRemoteLibrary(lib, gkn, rk, null, null); - assertEquals(wrapper.getImplementation(), lib); - } - - @Test - public void libraryUsingLists() throws Throwable { - DynamicUsingLists lib = new DynamicUsingLists(); - Method gkn = DynamicUsingLists.class.getMethod("getKeywordNames"); - Method rk = DynamicUsingLists.class.getMethod("runKeyword", String.class, List.class); - Method gka = DynamicUsingLists.class.getMethod("getKeywordArguments", String.class); - DynamicApiRemoteLibrary wrapper = new DynamicApiRemoteLibrary(lib, gkn, rk, gka, null); - Assert.assertEquals(wrapper.getKeywordNames(), new String[] { "go" }); - Assert.assertEquals(wrapper.runKeyword("go", new Object[] { "there" }, noKwargs), "there"); - Assert.assertEquals(wrapper.getKeywordArguments("go"), new String[] { "where" }); - } - - @Test - public void kwargsNotSupported() throws Throwable { - DynamicApiRemoteLibrary wrapper = getWrapper(DynamicOneRunKeywordNoKwargs.class); - String msg = null; - try { - wrapper.runKeyword("getArgs", noPosArgs, getKwargs("number", 42)); - } catch (RuntimeException e) { - msg = e.getMessage(); - } - Assert.assertEquals(msg, "This library does not support keyword arguments."); - } - - @Test - public void oneRunKeywordNoKwargs() throws Throwable { - DynamicApiRemoteLibrary wrapper = getWrapper(DynamicOneRunKeywordNoKwargs.class); - String result = (String) wrapper.runKeyword("getArgs", new Object[] { "eggs" }, new HashMap()); - Assert.assertEquals(result, "['eggs']"); - } - - @Test - public void oneRunKeywordWithKwargs() throws Throwable { - DynamicApiRemoteLibrary wrapper = getWrapper(DynamicOneRunKeywordKwargs.class); - String result = (String) wrapper.runKeyword("getArgs", new Object[] { "spam" }, noKwargs); - Assert.assertEquals(result, "['spam']{}"); - result = (String) wrapper.runKeyword("getArgs", noPosArgs, getKwargs("number", 42)); - Assert.assertEquals(result, "[]{'number':'42'}"); - } - - @Test - public void oneRunKeywordWithKwargsWithList() throws Throwable { - DynamicApiRemoteLibrary wrapper = getWrapper(DynamicOneRunKeywordKwargsList.class); - String result = (String) wrapper.runKeyword("getArgs", new Object[] { "spam" }, noKwargs); - Assert.assertEquals(result, "['spam']{}"); - result = (String) wrapper.runKeyword("getArgs", noPosArgs, getKwargs("number", 42)); - Assert.assertEquals(result, "[]{'number':'42'}"); - } - - private DynamicApiRemoteLibrary getWrapper(Class clazz) { - DefaultRemoteLibraryFactory fact = new DefaultRemoteLibraryFactory(); - try { - return (DynamicApiRemoteLibrary) fact.createRemoteLibrary(clazz.newInstance()); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private Map getKwargs(Object... items) { - Map map = new HashMap(); - for (int i = 0; i < items.length; i += 2) { - map.put((String) items[i], items[i + 1]); - } - return map; - } - -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/StaticApiRemoteLibraryTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/StaticApiRemoteLibraryTest.java deleted file mode 100644 index 2792d1c..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/library/StaticApiRemoteLibraryTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.robotframework.remoteserver.library; - -import static org.testng.Assert.assertEquals; - -import org.robotframework.remoteserver.testlibraries.StaticOne; -import org.testng.annotations.Test; - -public class StaticApiRemoteLibraryTest { - - @Test - public void keywordNaming() throws Throwable { - StaticApiRemoteLibrary lib = new StaticApiRemoteLibrary(new StaticOne()); - assertEquals(lib.runKeyword("get name", new Object[] {}, null), "StaticOne"); - assertEquals(lib.runKeyword("_g e tn_a __ m_e_", new Object[] {}, null), "StaticOne"); - assertEquals(lib.runKeyword(" G E T N A M E", new Object[] {}, null), "StaticOne"); - } - - @Test - public void getStaticAPILibraryImplementation() { - StaticOne lib = new StaticOne(); - StaticApiRemoteLibrary wrapper = new StaticApiRemoteLibrary(lib); - assertEquals(wrapper.getImplementation(), lib); - } - -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/servlet/AlternativeContainerTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/servlet/AlternativeContainerTest.java deleted file mode 100644 index c9bc8bf..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/servlet/AlternativeContainerTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.robotframework.remoteserver.servlet; - -import static org.robotframework.remoteserver.RemoteLibraryClient.runKeyword; - -import java.util.Properties; - -import org.robotframework.remoteserver.testlibraries.StaticOne; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.Test; - -import Acme.Serve.Serve; - -public class AlternativeContainerTest { - - private Serve server = null; - - @Test - public void nonDefaultServletInTjws() throws Exception { - server = new Serve(); - Properties properties = new Properties(); - properties.put("port", 9999); - server.arguments = properties; - RemoteServerServlet servlet = new RemoteServerServlet(); - servlet.putLibrary("/one", new StaticOne()); - server.addServlet("/foo/bar", servlet); - server.addDefaultServlets(null); - server.runInBackground(); - String name = (String) runKeyword(9999, "/foo/bar/one", "getName").get("return"); - Assert.assertEquals(name, "StaticOne"); - } - - @AfterMethod - public void stopServer() throws Exception { - if (server != null) { - server.notifyStop(); - } - } - -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/servlet/RemoteServerServletTest.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/servlet/RemoteServerServletTest.java deleted file mode 100644 index 07543b2..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/servlet/RemoteServerServletTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.robotframework.remoteserver.servlet; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.Socket; -import java.net.SocketException; - -import org.robotframework.remoteserver.RemoteServerImpl; -import org.robotframework.remoteserver.library.RemoteLibrary; -import org.robotframework.remoteserver.testlibraries.StaticOne; -import org.robotframework.remoteserver.testlibraries.StaticTwo; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class RemoteServerServletTest { - - @Test - public void serverClosesHttp10Connections() throws Exception { - RemoteServerImpl server = new RemoteServerImpl(); - try { - server.setPort(8270); - server.putLibrary("/", new StaticOne()); - server.start(); - Socket s = new Socket((String) null, 8270); - - PrintWriter writer = new PrintWriter(s.getOutputStream()); - BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream())); - - String head = "POST / HTTP/1.0\r\nUser-Agent: test\r\nHost: localhost\r\nContent-Type: text/xml\r\nContent-length: "; - writer.print(head); - writer.print(Integer.toString(body.length())); - writer.print("\r\n\r\n"); - writer.print(body); - writer.flush(); - - StringBuilder output = new StringBuilder(); - String inputLine; - while ((inputLine = reader.readLine()) != null) - output.append(inputLine + "\n"); - Assert.assertTrue(output.toString().contains("stop_remote_server")); - boolean closed = false; - try { // should fail on first write when in CLOSE_WAIT but doesn't - for (int i = 0; i < 100; i++) { - s.getOutputStream().write(5); - Thread.sleep(200); - s.getOutputStream().flush(); - } - } catch (SocketException e) { - closed = true; - } - Assert.assertTrue(closed); - reader.close(); - writer.close(); - s.close(); - } finally { - server.stop(); - } - } - - @Test - public void putLibrary() { - RemoteServerServlet servlet = new RemoteServerServlet(); - RemoteLibrary lib = servlet.putLibrary("/", new StaticOne()); - Assert.assertNull(lib); - RemoteLibrary origLib = servlet.getLibraryMap().get("/"); - lib = servlet.putLibrary("/", new StaticTwo()); - Assert.assertEquals(lib, origLib); - } - - @Test - public void removeLibrary() { - RemoteServerServlet servlet = new RemoteServerServlet(); - RemoteLibrary lib = servlet.removeLibrary("/"); - Assert.assertNull(lib); - servlet.putLibrary("/", new StaticOne()); - RemoteLibrary origLib = servlet.getLibraryMap().get("/"); - lib = servlet.removeLibrary("/"); - Assert.assertEquals(lib, origLib); - } - - private final String body = "get_keyword_names"; -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/ConflictingOverloadVariableArguments.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/ConflictingOverloadVariableArguments.java deleted file mode 100644 index 37cd365..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/ConflictingOverloadVariableArguments.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.robotframework.remoteserver.testlibraries; - -public class ConflictingOverloadVariableArguments -{ - public void myKeyword() {} - public void myKeyword(float[] numbers) {} -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DuplicateKeywords.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DuplicateKeywords.java deleted file mode 100644 index 1713eb6..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DuplicateKeywords.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.robotframework.remoteserver.testlibraries; - -public class DuplicateKeywords { - public void myKeyword() { - } - - public void my_keyword(String it) { - } -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargs.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargs.java deleted file mode 100644 index a0349bd..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargs.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.robotframework.remoteserver.testlibraries; - -import java.util.Map; - -public class DynamicOneRunKeywordKwargs extends StaticOne { - - public String[] getKeywordNames() { - return new String[] {"getArgs"}; - } - - public Object runKeyword(String name, Object[] args, Map kwargs) { - if (name.equals("getArgs")) { - return getArgs(args, kwargs); - } else { - throw new RuntimeException(); - } - } - - public String[] getKeywordArguments(String name) { - return new String[] {"*args", "**kwargs"}; - } - -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargsList.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargsList.java deleted file mode 100644 index d0e0a92..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordKwargsList.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.robotframework.remoteserver.testlibraries; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -public class DynamicOneRunKeywordKwargsList extends StaticOne { - - public String[] getKeywordNames() { - return new String[] {"getArgs"}; - } - - public Object runKeyword(String name, List args, Map kwargs) { - if (name.equals("getArgs")) { - return getArgs(args.toArray(), kwargs); - } else { - throw new RuntimeException(); - } - } - - public List getKeywordArguments(String name) { - return Arrays.asList("*args", "**kwargs"); - } - -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordNoKwargs.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordNoKwargs.java deleted file mode 100644 index 729fcdb..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicOneRunKeywordNoKwargs.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.robotframework.remoteserver.testlibraries; - -public class DynamicOneRunKeywordNoKwargs extends StaticOne { - - public String[] getKeywordNames() { - return new String[] {"getArgs"}; - } - - public Object runKeyword(String name, Object[] args) { - if (name.equals("getArgs")) { - return getArgs(args); - } else { - throw new RuntimeException(); - } - } - -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicUsingLists.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicUsingLists.java deleted file mode 100644 index 68c1603..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/DynamicUsingLists.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.robotframework.remoteserver.testlibraries; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.List; - -public class DynamicUsingLists { - - public List getKeywordNames() { - return Arrays.asList("go"); - } - - public Object runKeyword(String name, List arguments) { - Method[] methods = this.getClass().getMethods(); - try { - for (Method meth : methods) { - if (meth.getName().equals(name)) { - return meth.invoke(this, arguments.toArray()); - } - } - } catch (Exception e) { - throw new RuntimeException(e); - } - throw new RuntimeException("bad keyword"); - } - - public List getKeywordArguments(String name) { - if (name.equals("go")) { - return Arrays.asList("where"); - } - throw new RuntimeException("bad keyword"); - } - - public String go(String where) { - return where; - } - -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/OverloadedMethods.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/OverloadedMethods.java deleted file mode 100644 index 9181bbc..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/OverloadedMethods.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.robotframework.remoteserver.testlibraries; - -public class OverloadedMethods { - public void myKeyword() { - } - - public void myKeyword(String name) { - } - - public String numberType(short number) { - return "short overload"; - } - public String numberType(int number) { - return "int overload"; - } - - public String defaults(String required) { - return defaults("default"); - } - - public String defaults(String required, String optional) { - return String.format("%s,%s", required, optional); - } - -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/StaticOne.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/StaticOne.java deleted file mode 100644 index 2f49903..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/StaticOne.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.robotframework.remoteserver.testlibraries; - -import java.util.Map; -import java.util.TreeMap; - -public class StaticOne { - - public String getName() { - return this.getClass().getSimpleName(); - } - - public int squareOf(int number) { - return number * number; - } - - public void variableArgs(String str, String... strings) { - } - - public void onlyVariableArgs(String... strings) { - } - - public void noReturnValue() { - } - - protected String getArgs(Object[] args) { - return getArgs(args, null, false); - } - - protected String getArgs(Object[] args, Map kwargs) { - return getArgs(args, kwargs, true); - } - - private String getArgs(Object[] args, Map kwargs, boolean evalKwargs) { - StringBuilder sb = new StringBuilder(); - boolean first = true; - sb.append("["); - for (Object arg : args) { - if (!first) { - sb.append(","); - } - first = false; - sb.append("'").append(arg).append("'"); - } - sb.append("]"); - if (evalKwargs) { - first = true; - sb.append("{"); - Map map = new TreeMap(kwargs); - for (String key : map.keySet()) { - if (!first) { - sb.append(","); - } - first = false; - sb.append("'").append(key).append("':'").append(map.get(key)).append("'"); - } - sb.append("}"); - } - return sb.toString(); - } - -} diff --git a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/StaticTwo.java b/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/StaticTwo.java deleted file mode 100644 index e195961..0000000 --- a/jrobot-remote-server/src/test/java/org/robotframework/remoteserver/testlibraries/StaticTwo.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.robotframework.remoteserver.testlibraries; - -public class StaticTwo { - public String getName() { - return this.getClass().getSimpleName(); - } -} From 3779cae177c96891e5829628368b44a70038e087 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Mih=C3=A1lek?= Date: Fri, 14 Oct 2016 20:25:34 +0200 Subject: [PATCH 08/11] Add jrobot acceptance test library MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Martin Mihálek --- jrobot-test-library/pom.xml | 4 +- .../org/robotframework/test/BaseLibrary.java | 46 +++++++++++++++++++ .../robotframework/test/ExtendedLibrary.java | 25 ++++++++++ .../org/robotframework/test/TestLibrary.java | 11 ----- .../test/TestLibraryService.java | 22 +++++++++ .../blueprint/jrobot-test-library.xml | 7 ++- 6 files changed, 101 insertions(+), 14 deletions(-) create mode 100644 jrobot-test-library/src/main/java/org/robotframework/test/BaseLibrary.java create mode 100644 jrobot-test-library/src/main/java/org/robotframework/test/ExtendedLibrary.java delete mode 100644 jrobot-test-library/src/main/java/org/robotframework/test/TestLibrary.java create mode 100644 jrobot-test-library/src/main/java/org/robotframework/test/TestLibraryService.java diff --git a/jrobot-test-library/pom.xml b/jrobot-test-library/pom.xml index 1dab5da..ec0869c 100644 --- a/jrobot-test-library/pom.xml +++ b/jrobot-test-library/pom.xml @@ -24,8 +24,8 @@ org.apache.maven.plugins maven-compiler-plugin - 1.7 - 1.7 + ${java.version} + ${java.version} diff --git a/jrobot-test-library/src/main/java/org/robotframework/test/BaseLibrary.java b/jrobot-test-library/src/main/java/org/robotframework/test/BaseLibrary.java new file mode 100644 index 0000000..abadc35 --- /dev/null +++ b/jrobot-test-library/src/main/java/org/robotframework/test/BaseLibrary.java @@ -0,0 +1,46 @@ +package org.robotframework.test; + +import org.robotframework.remoteserver.RemoteServer; +import org.robotframework.remoteserver.library.AbstractClassLibrary; + +public class BaseLibrary extends AbstractClassLibrary implements TestLibraryService { + + public BaseLibrary(RemoteServer server) { + super(server); + } + + @Override public String getURI() { + return getClass().getSimpleName(); + } + + @Override public void close() { + } + + @Override public String getName() { + return "Base Library"; + } + + @Override public double add(double a, double b) { + return a + b; + } + + @Override public int add(int a, int b) { + return a + b; + } + + @Override public String concat(String input1, String input2) { + return input1 + " " + input2; + } + + @Override public String concat(String input1, int input2) { + return input1 + " " + (input2 + 1); + } + + @Override public String concat(int input1, String input2) { + return (input1 + 1) + " " + input2; + } + + @Override public String concat(String input1, String input2, String input3) { + return input1 + " " + input2 + " " + input3; + } +} diff --git a/jrobot-test-library/src/main/java/org/robotframework/test/ExtendedLibrary.java b/jrobot-test-library/src/main/java/org/robotframework/test/ExtendedLibrary.java new file mode 100644 index 0000000..e821509 --- /dev/null +++ b/jrobot-test-library/src/main/java/org/robotframework/test/ExtendedLibrary.java @@ -0,0 +1,25 @@ +package org.robotframework.test; + +import org.robotframework.javalib.annotation.RobotKeyword; +import org.robotframework.javalib.annotation.RobotKeywords; +import org.robotframework.remoteserver.RemoteServer; + +@RobotKeywords public class ExtendedLibrary extends BaseLibrary { + + public ExtendedLibrary(RemoteServer server) { + super(server); + } + + @Override public String getURI() { + return getClass().getSimpleName(); + } + + @Override public String getName() { + return "Extended Library"; + } + + @RobotKeyword public double getPi() { + return 3.14; + } + +} diff --git a/jrobot-test-library/src/main/java/org/robotframework/test/TestLibrary.java b/jrobot-test-library/src/main/java/org/robotframework/test/TestLibrary.java deleted file mode 100644 index 05992b1..0000000 --- a/jrobot-test-library/src/main/java/org/robotframework/test/TestLibrary.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.robotframework.test; - -import org.robotframework.remoteserver.RemoteServer; - -public class TestLibrary { - - public TestLibrary(RemoteServer server) { - server.putLibrary("/" + getClass().getSimpleName(), this); - } - -} diff --git a/jrobot-test-library/src/main/java/org/robotframework/test/TestLibraryService.java b/jrobot-test-library/src/main/java/org/robotframework/test/TestLibraryService.java new file mode 100644 index 0000000..f15ae2a --- /dev/null +++ b/jrobot-test-library/src/main/java/org/robotframework/test/TestLibraryService.java @@ -0,0 +1,22 @@ +package org.robotframework.test; + +import org.robotframework.javalib.annotation.RobotKeyword; +import org.robotframework.javalib.annotation.RobotKeywordOverload; +import org.robotframework.javalib.annotation.RobotKeywords; + +@RobotKeywords public interface TestLibraryService { + + @RobotKeyword String getName(); + + @RobotKeyword double add(double a, double b); + + @RobotKeywordOverload int add(int a, int b); + + @RobotKeyword String concat(String input1, String input2); + + @RobotKeywordOverload String concat(String input1, int input2); + + @RobotKeywordOverload String concat(int input1, String input2); + + @RobotKeywordOverload String concat(String input1, String input2, String input3); +} diff --git a/jrobot-test-library/src/main/resources/OSGI-INF/blueprint/jrobot-test-library.xml b/jrobot-test-library/src/main/resources/OSGI-INF/blueprint/jrobot-test-library.xml index b5e0cbc..fbf245a 100644 --- a/jrobot-test-library/src/main/resources/OSGI-INF/blueprint/jrobot-test-library.xml +++ b/jrobot-test-library/src/main/resources/OSGI-INF/blueprint/jrobot-test-library.xml @@ -2,9 +2,14 @@ - + + + + + + From d9be1ca5bda8439f2968409fa106a85eb5cf5797 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Mih=C3=A1lek?= Date: Fri, 14 Oct 2016 20:44:02 +0200 Subject: [PATCH 09/11] Bump jrobotremotserver version MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Martin Mihálek --- jrobot-features/pom.xml | 2 +- jrobot-karaf/pom.xml | 2 +- jrobot-remote-server/pom.xml | 2 +- jrobot-test-library/pom.xml | 2 +- pom.xml | 3 ++- 5 files changed, 6 insertions(+), 5 deletions(-) diff --git a/jrobot-features/pom.xml b/jrobot-features/pom.xml index 34bce00..494dafb 100644 --- a/jrobot-features/pom.xml +++ b/jrobot-features/pom.xml @@ -6,7 +6,7 @@ jrobot-parent com.github.aenniw - 3.2-SNAPSHOT + ${deploy.version} jrobot-features jar diff --git a/jrobot-karaf/pom.xml b/jrobot-karaf/pom.xml index 99768f9..fe02611 100755 --- a/jrobot-karaf/pom.xml +++ b/jrobot-karaf/pom.xml @@ -6,7 +6,7 @@ jrobot-parent com.github.aenniw - 3.2-SNAPSHOT + ${deploy.version} jrobot-karaf karaf-assembly diff --git a/jrobot-remote-server/pom.xml b/jrobot-remote-server/pom.xml index 2fcd96b..3167d07 100644 --- a/jrobot-remote-server/pom.xml +++ b/jrobot-remote-server/pom.xml @@ -6,7 +6,7 @@ jrobot-parent com.github.aenniw - 3.2-SNAPSHOT + ${deploy.version} jrobot-remote-server bundle diff --git a/jrobot-test-library/pom.xml b/jrobot-test-library/pom.xml index ec0869c..28e4d0b 100644 --- a/jrobot-test-library/pom.xml +++ b/jrobot-test-library/pom.xml @@ -6,7 +6,7 @@ jrobot-parent com.github.aenniw - 3.2-SNAPSHOT + ${deploy.version} jrobot-test-library bundle diff --git a/pom.xml b/pom.xml index e23187d..aa45c2d 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.github.aenniw jrobot-parent - 3.2-SNAPSHOT + ${deploy.version} jrobot-remote-server jrobot-test-library @@ -39,6 +39,7 @@ 7 + 3.3-SNAPSHOT UTF-8 1.8 19.0 From 59fed50049664081c218b4f9b299d106d1ddc349 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Mih=C3=A1lek?= Date: Fri, 14 Oct 2016 22:41:48 +0200 Subject: [PATCH 10/11] Remove unused dependencies. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Unused dependencies were removed, updated inforfiles and TRAVIS jdk uses ony jdk8 from now on. Signed-off-by: Martin Mihálek --- .travis.yml | 1 - BUILD.rest | 5 +- jrobot-remote-server/pom.xml | 33 +---------- .../servlet/RemoteServerServlet.java | 4 +- .../remoteserver/servlet/ServerMethods.java | 12 ++-- .../remoteserver/xmlrpc/TypeFactory.java | 58 +++++++++++++++---- pom.xml | 34 ----------- 7 files changed, 59 insertions(+), 88 deletions(-) diff --git a/.travis.yml b/.travis.yml index a7dfd71..a86961e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,7 +7,6 @@ cache: language: java jdk: - oraclejdk8 - - oraclejdk7 before_deploy: - mvn javadoc:jar - export BIN=$(ls target/jrobotremoteserver-*-SNAPSHOT.jar) diff --git a/BUILD.rest b/BUILD.rest index 09cbe27..03b36cf 100644 --- a/BUILD.rest +++ b/BUILD.rest @@ -2,10 +2,9 @@ Building -------- Maven is used as build tool for jrobotremoteserver. -You can simply do a 'mvn clean package assembly:single' in the project directory. +You can simply do a 'mvn clean install' in the project directory. Robot Tests ----------- -There are some number of robot acceptance tests under `atest`. -They are executed by running `run.py`. +There are some number of robot acceptance tests under `jrobot-kataf/src`. diff --git a/jrobot-remote-server/pom.xml b/jrobot-remote-server/pom.xml index 3167d07..074b7de 100644 --- a/jrobot-remote-server/pom.xml +++ b/jrobot-remote-server/pom.xml @@ -11,10 +11,6 @@ jrobot-remote-server bundle - - org.apache.aries.blueprint - org.apache.aries.blueprint - org.apache.xmlrpc @@ -25,38 +21,14 @@ org.robotframework javalib-core - - - org.apache.ws.commons.util - ws-commons-util - org.eclipse.jetty jetty-servlet - - org.apache.commons - commons-lang3 - org.slf4j slf4j-api - - org.apache.xmlrpc - xmlrpc-client - test - - - org.testng - testng - test - - - org.jboss.resteasy - tjws - test - com.google.guava guava @@ -91,20 +63,17 @@ ${project.groupId}.${project.artifactId} - !org.apache.commons.lang3.*, - !org.apache.ws.commons.*, !org.robotframework.*, !org.apache.xmlrpc.*, * - org.apache.commons.lang3.*, org.apache.ws.commons.*, org.robotframework.*, org.apache.xmlrpc.* - *;artifactId=xmlrpc-server|javalib-core|ws-commons-util + *;artifactId=xmlrpc-server|javalib-core diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java index 7ce15c3..7504cc4 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java @@ -15,6 +15,7 @@ package org.robotframework.remoteserver.servlet; import com.google.common.base.Preconditions; +import com.google.common.html.HtmlEscapers; import java.io.IOException; import java.io.PrintWriter; import java.util.Collections; @@ -25,7 +26,6 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.commons.lang3.StringEscapeUtils; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.server.XmlRpcHandlerMapping; import org.apache.xmlrpc.webserver.XmlRpcServlet; @@ -165,7 +165,7 @@ private String getPage() { sb.append(""); sb.append(path); sb.append(""); - sb.append(StringEscapeUtils.escapeHtml4(map.get(path).getURI())); + sb.append(HtmlEscapers.htmlEscaper().escape(map.get(path).getURI())); sb.append(""); } } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java index 847ca08..013a5ec 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java @@ -14,12 +14,12 @@ */ package org.robotframework.remoteserver.servlet; +import com.google.common.base.Strings; +import com.google.common.base.Throwables; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.exception.ExceptionUtils; import org.robotframework.javalib.util.StdStreamRedirecter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -75,7 +75,7 @@ public ServerMethods(RemoteServerServlet servlet) { result.put("status", "FAIL"); Throwable thrown = e.getCause() == null ? e : e.getCause(); result.put("error", getError(thrown)); - result.put("traceback", ExceptionUtils.getStackTrace(thrown)); + result.put("traceback", Throwables.getStackTraceAsString(thrown)); boolean continuable = isFlagSet("ROBOT_CONTINUE_ON_FAILURE", thrown); if (continuable) { result.put("continuable", true); @@ -85,8 +85,8 @@ public ServerMethods(RemoteServerServlet servlet) { result.put("fatal", true); } } finally { - String stdOut = StringUtils.defaultString(redirector.getStdOutAsString()); - String stdErr = StringUtils.defaultString(redirector.getStdErrAsString()); + String stdOut = Strings.nullToEmpty(redirector.getStdOutAsString()); + String stdErr = Strings.nullToEmpty(redirector.getStdErrAsString()); if (!stdOut.isEmpty() || !stdErr.isEmpty()) { StringBuilder output = new StringBuilder(stdOut); if (!stdOut.isEmpty() && !stdErr.isEmpty()) { @@ -129,7 +129,7 @@ public ServerMethods(RemoteServerServlet servlet) { private String getError(Throwable thrown) { final String simpleName = thrown.getClass().getSimpleName(); if (genericExceptions.contains(simpleName) || isFlagSet("ROBOT_SUPPRESS_NAME", thrown)) { - return StringUtils.defaultIfEmpty(thrown.getMessage(), simpleName); + return thrown.getMessage() == null || thrown.getMessage().isEmpty() ? simpleName : thrown.getMessage(); } else { return String.format("%s: %s", thrown.getClass().getName(), thrown.getMessage()); } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java index fc18aff..bfc655a 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/xmlrpc/TypeFactory.java @@ -14,9 +14,12 @@ */ package org.robotframework.remoteserver.xmlrpc; +import java.util.Arrays; import java.util.List; import java.util.Map; -import org.apache.commons.lang3.ArrayUtils; +import java.util.stream.DoubleStream; +import java.util.stream.IntStream; +import java.util.stream.LongStream; import org.apache.ws.commons.util.NamespaceContextImpl; import org.apache.xmlrpc.common.TypeFactoryImpl; import org.apache.xmlrpc.common.XmlRpcController; @@ -58,6 +61,42 @@ public TypeFactory(XmlRpcController pController) { super(pController); } + public static Byte[] toObject(final byte[] primitives) { + final Byte[] bytes = new Byte[primitives.length]; + Arrays.setAll(bytes, n -> primitives[n]); + return bytes; + } + + public static Short[] toObject(final short[] primitives) { + final Short[] bytes = new Short[primitives.length]; + Arrays.setAll(bytes, n -> primitives[n]); + return bytes; + } + + public static Integer[] toObject(final int[] primitives) { + return IntStream.of(primitives).boxed().toArray(Integer[]::new); + } + + public static Long[] toObject(final long[] primitives) { + return LongStream.of(primitives).boxed().toArray(Long[]::new); + } + + public static Float[] toObject(final float[] primitives) { + final Float[] bytes = new Float[primitives.length]; + Arrays.setAll(bytes, n -> primitives[n]); + return bytes; + } + + public static Double[] toObject(final double[] primitives) { + return DoubleStream.of(primitives).boxed().toArray(Double[]::new); + } + + public static Boolean[] toObject(final boolean[] primitives) { + final Boolean[] bytes = new Boolean[primitives.length]; + Arrays.setAll(bytes, n -> primitives[n]); + return bytes; + } + public TypeSerializer getSerializer(XmlRpcStreamConfig pConfig, Object pObject) throws SAXException { if (pObject == null) return NULL_SERIALIZER; @@ -79,26 +118,25 @@ else if (pObject instanceof Iterable) return new IterableSerializer(this, pConfig); else if (pObject instanceof char[]) return CHAR_ARRAY_SERIALIZER; - else if (pObject.getClass().isArray()) { // object[] & char[] handled - // before this + else if (pObject.getClass().isArray()) { return new ObjectArraySerializer(TypeFactory.this, pConfig) { @Override protected void writeData(ContentHandler pHandler, Object pObject1) throws SAXException { Object[] array; if (pObject1 instanceof byte[]) - array = ArrayUtils.toObject((byte[]) pObject1); + array = toObject((byte[]) pObject1); else if (pObject1 instanceof short[]) - array = ArrayUtils.toObject((short[]) pObject1); + array = toObject((short[]) pObject1); else if (pObject1 instanceof int[]) - array = ArrayUtils.toObject((int[]) pObject1); + array = toObject((int[]) pObject1); else if (pObject1 instanceof long[]) - array = ArrayUtils.toObject((long[]) pObject1); + array = toObject((long[]) pObject1); else if (pObject1 instanceof float[]) - array = ArrayUtils.toObject((float[]) pObject1); + array = toObject((float[]) pObject1); else if (pObject1 instanceof double[]) - array = ArrayUtils.toObject((double[]) pObject1); + array = toObject((double[]) pObject1); else if (pObject1 instanceof boolean[]) - array = ArrayUtils.toObject((boolean[]) pObject1); + array = toObject((boolean[]) pObject1); else // should never happen throw new SAXException(String.format("Array of type %s[] not handled!", diff --git a/pom.xml b/pom.xml index aa45c2d..46d1850 100644 --- a/pom.xml +++ b/pom.xml @@ -46,11 +46,6 @@ - - org.apache.aries.blueprint - org.apache.aries.blueprint - 1.1.0 - org.apache.xmlrpc @@ -63,45 +58,16 @@ javalib-core 1.2.1 - - - org.apache.ws.commons.util - ws-commons-util - 1.0.2 - org.eclipse.jetty jetty-servlet 8.0.4.v20111024 - - org.apache.commons - commons-lang3 - 3.4 - org.slf4j slf4j-api 1.7.21 - - org.apache.xmlrpc - xmlrpc-client - 3.1.3 - test - - - org.testng - testng - 6.3.1 - test - - - org.jboss.resteasy - tjws - 2.3.2.Final - test - org.apache.karaf.features framework From 3373158d30da440804e2ed8a750fbb0997356741 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Mih=C3=A1lek?= Date: Mon, 31 Oct 2016 22:09:08 +0100 Subject: [PATCH 11/11] Add basic support for KWARGS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added simple support for KWARGS, library needs to be compiled with argument "-parameters" to enable KWARGS. Added acceptance test to cover simple KWARG scenario. Signed-off-by: Martin Mihálek --- .../acceptance/020_jrobot_tests.robot | 27 +++++++++++++------ .../remoteserver/RemoteServerImpl.java | 4 +-- .../keywords/OverloadedKeywordExtractor.java | 4 +-- .../keywords/OverloadedKeywordFactory.java | 6 ++--- .../keywords/OverloadedKeywordImpl.java | 11 +++----- .../library/AbstractClassLibrary.java | 13 ++++++--- .../servlet/RemoteServerServlet.java | 4 +-- .../remoteserver/servlet/ServerMethods.java | 13 ++++++--- jrobot-test-library/pom.xml | 1 + .../org/robotframework/test/BaseLibrary.java | 8 ++++++ .../test/TestLibraryService.java | 4 +++ 11 files changed, 64 insertions(+), 31 deletions(-) diff --git a/jrobot-karaf/src/test/robotframework/acceptance/020_jrobot_tests.robot b/jrobot-karaf/src/test/robotframework/acceptance/020_jrobot_tests.robot index b2c918c..50f1939 100644 --- a/jrobot-karaf/src/test/robotframework/acceptance/020_jrobot_tests.robot +++ b/jrobot-karaf/src/test/robotframework/acceptance/020_jrobot_tests.robot @@ -1,5 +1,5 @@ *** Settings *** -Documentation Test suite to verify OSGI capabilities of jrobot-remoe-server +Documentation Test suite to verify functionality of jrobot-remoe-server Suite Setup Setup Suite Suite Teardown Clean Suite Resource ../karaf_keywords.robot @@ -8,7 +8,7 @@ Resource ../karaf_keywords.robot *** Test Cases *** Library Type Override Test - [Documentation] TODO + [Documentation] Tests if Keyword overloads works properly ${result} BaseLib.Concat Concat me together. Should Be Equal As Strings ${result} Concat me together. ${result} BaseLib.Concat Number 5 @@ -19,14 +19,25 @@ Library Type Override Test Should Be Equal As Strings ${result} Concat me together. Library Numeric Type Override Test - [Documentation] TODO + [Documentation] Tests if Keyword overloads works properly ${sum} BaseLib.Add 5.2 1.3 Should be equal as numbers 6.5 ${sum} ${sum} BaseLib.Add 5 1 Should Be Equal As Integers 6 ${sum} +Library Numeric Type KWARGS Test + [Documentation] Tests if Keyword KWARGS works properly + ${sum} BaseLib.Sub 5.2 b=1.3 + Should be equal as numbers 3.9 ${sum} + ${sum} BaseLib.Sub b=5.2 a=1.3 + Should be equal as numbers -3.9 ${sum} + ${sum} BaseLib.Sub b=5 a=1 + Should Be Equal As Integers -4 ${sum} + ${sum} BaseLib.Sub 5 b=1 + Should Be Equal As Integers 4 ${sum} + Library Inheritance Test - [Documentation] + [Documentation] Tests if Class inheritance of keywordds works properly ${name_1} BaseLib.Get Name ${name_2} ExtendedLib.Get Name Should Not Be Equal As Strings ${name_1} ${name_2} @@ -37,7 +48,7 @@ Library Inheritance Test *** Keywords *** Setup Suite - [Documentation] TODO + [Documentation] Initialize Suite resources Start Karaf Verify Feature Installed On Karaf jrobot-remote-server Verify Feature Started On Karaf jrobot-remote-server @@ -45,11 +56,11 @@ Setup Suite Verify Bundle Installed On Karaf jrobot-test-library Start Bundle On Karaf jrobot-test-library Verify Bundle Started On Karaf jrobot-test-library - Import Library Remote http://localhost:8270/BaseLibrary WITH NAME BaseLib - Import Library Remote http://localhost:8270/ExtendedLibrary WITH NAME ExtendedLib + Import Library Remote http://localhost:8270/BaseLibrary WITH NAME BaseLib + Import Library Remote http://localhost:8270/ExtendedLibrary WITH NAME ExtendedLib Clean Suite - [Documentation] + [Documentation] Cleans Suites resources BaseLib.Library Cleanup ExtendedLib.Library Cleanup Stop Karaf diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java index bd82319..19aa1ab 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/RemoteServerImpl.java @@ -14,8 +14,8 @@ */ package org.robotframework.remoteserver; -import com.google.common.base.Preconditions; import java.util.Map; +import java.util.Objects; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.nio.SelectChannelConnector; @@ -98,7 +98,7 @@ public void setHost(String hostName) { @Override public void putLibrary(String path, RemoteLibrary library) { final RemoteLibrary oldLibrary = - servlet.putLibrary(Preconditions.checkNotNull(path), Preconditions.checkNotNull(library)); + servlet.putLibrary(Objects.requireNonNull(path), Objects.requireNonNull(library)); if (oldLibrary != null) { oldLibrary.close(); LOG.info("Closed library {} om path {}", library.getClass().getSimpleName(), path); diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordExtractor.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordExtractor.java index ad888ff..1cd7a11 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordExtractor.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordExtractor.java @@ -17,12 +17,12 @@ */ package org.robotframework.remoteserver.keywords; -import com.google.common.base.Preconditions; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.stream.Stream; import org.robotframework.javalib.annotation.RobotKeyword; @@ -59,7 +59,7 @@ public static Stream getMethods(Class obj) { } @Override public Map extractKeywords(final RemoteLibrary keywordBean) { - Preconditions.checkNotNull(keywordBean); + Objects.requireNonNull(keywordBean); LOG.warn("Extracting {}", keywordBean.getURI()); IKeywordNameNormalizer keywordNameNormalizer = new KeywordNameNormalizer(); final Map overloadableKeywords = new HashMap<>(); diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordFactory.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordFactory.java index a4a1e42..67ad6de 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordFactory.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordFactory.java @@ -17,9 +17,9 @@ */ package org.robotframework.remoteserver.keywords; -import com.google.common.base.Preconditions; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import org.robotframework.javalib.factory.KeywordFactory; import org.robotframework.javalib.util.IKeywordNameNormalizer; import org.robotframework.javalib.util.KeywordNameNormalizer; @@ -32,8 +32,8 @@ public class OverloadedKeywordFactory implements KeywordFactory extractor) { - this.extractor = Preconditions.checkNotNull(extractor); - extractKeywordsFromKeywordBean(Preconditions.checkNotNull(keywordBean)); + this.extractor = Objects.requireNonNull(extractor); + extractKeywordsFromKeywordBean(Objects.requireNonNull(keywordBean)); } @Override public OverloadedKeyword createKeyword(String keywordName) { diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordImpl.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordImpl.java index 346bb1d..3439b01 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordImpl.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/keywords/OverloadedKeywordImpl.java @@ -48,15 +48,12 @@ public OverloadedKeywordImpl(Object keywordClass, Method method) { if (checkedKeyword.canExecute(arguments)) return checkedKeyword.execute(arguments); } - } - if (keywordMap.size() == 1) { + } else if (keywordMap.size() == 1) { throw new IllegalArgumentException(String.format("%s takes %d argument(s), received %d.", keywordName, Iterables.get(keywordMap.keySet(), 0), argCount)); - } else { - throw new IllegalArgumentException( - String.format("No overload of %s takes %d argument(s).", keywordName, argCount)); } - + throw new IllegalArgumentException( + String.format("No overload of %s takes %d argument(s).", keywordName, argCount)); } @Override public void addOverload(Method method) { @@ -78,7 +75,7 @@ public OverloadedKeywordImpl(Object keywordClass, Method method) { final String[] arguments = new String[max], minNames = Iterables.get(keywordMap.get(min), 0).getArgumentNames(), maxNames = Iterables.get(keywordMap.get(max), 0).getArgumentNames(); - for (int i = min; i < max; i++) { + for (int i = 0; i < max; i++) { if (i < min) arguments[i] = minNames[i]; else diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/AbstractClassLibrary.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/AbstractClassLibrary.java index b669852..98770df 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/AbstractClassLibrary.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/library/AbstractClassLibrary.java @@ -17,8 +17,8 @@ */ package org.robotframework.remoteserver.library; -import com.google.common.base.Preconditions; import java.util.Map; +import java.util.Objects; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; import org.robotframework.javalib.factory.KeywordFactory; @@ -34,7 +34,7 @@ private KeywordFactory keywordFactory; protected AbstractClassLibrary(RemoteServer server) { - Preconditions.checkNotNull(server).putLibrary("/" + getURI().trim().replace(" ", "_"), this); + Objects.requireNonNull(server).putLibrary("/" + getURI().trim().replace(" ", "_"), this); } @Override protected synchronized KeywordFactory createKeywordFactory() { @@ -45,8 +45,13 @@ protected AbstractClassLibrary(RemoteServer server) { } @Override public synchronized Object runKeyword(String keywordName, Object[] args, Map kwargs) { - if (kwargs != null && !kwargs.isEmpty()) { - throw new RuntimeException("Keyword arguments not yet supported for static API libraries."); + if (Objects.nonNull(kwargs) && !kwargs.isEmpty()) { + String[] argsNames = getKeywordArguments(keywordName); + for (int i = 0; i < argsNames.length; i++) { + if (kwargs.containsKey(argsNames[i])) { + args[i] = kwargs.get(argsNames[i]); + } + } } return runKeyword(keywordName, args); } diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java index 7504cc4..6112409 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/RemoteServerServlet.java @@ -14,12 +14,12 @@ */ package org.robotframework.remoteserver.servlet; -import com.google.common.base.Preconditions; import com.google.common.html.HtmlEscapers; import java.io.IOException; import java.io.PrintWriter; import java.util.Collections; import java.util.Map; +import java.util.Objects; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.ServletConfig; @@ -84,7 +84,7 @@ private static String checkPath(String path) { } public RemoteLibrary putLibrary(String path, RemoteLibrary library) { - return libraryMap.put(checkPath(path), Preconditions.checkNotNull(library)); + return libraryMap.put(checkPath(path), Objects.requireNonNull(library)); } public RemoteLibrary removeLibrary(String path) { diff --git a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java index 013a5ec..4df05fe 100644 --- a/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java +++ b/jrobot-remote-server/src/main/java/org/robotframework/remoteserver/servlet/ServerMethods.java @@ -17,9 +17,11 @@ import com.google.common.base.Strings; import com.google.common.base.Throwables; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import org.robotframework.javalib.util.StdStreamRedirecter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -112,8 +114,13 @@ public ServerMethods(RemoteServerServlet servlet) { } @Override public Map run_keyword(String keyword, Object[] args) { - //TODO implement varargs - return run_keyword(keyword, args, null); + Map kwargs = new HashMap<>(); + for (Object arg : Objects.requireNonNull(args)) { + if (arg.toString().contains("=")) { + kwargs.put(arg.toString().split("=")[0] + "=", arg.toString().split("=")[1]); + } + } + return run_keyword(keyword, args, kwargs.isEmpty() ? Collections.emptyMap() : kwargs); } @Override public String[] get_keyword_arguments(String keyword) { @@ -163,7 +170,7 @@ protected Object arraysToLists(Object arg) { } private boolean illegalArgumentIn(Throwable t) { - if (t.getClass().equals(IllegalArgumentException.class)) { + if (!Objects.nonNull(t) || t.getClass().equals(IllegalArgumentException.class)) { return true; } Throwable inner = t; diff --git a/jrobot-test-library/pom.xml b/jrobot-test-library/pom.xml index 28e4d0b..764b4e1 100644 --- a/jrobot-test-library/pom.xml +++ b/jrobot-test-library/pom.xml @@ -26,6 +26,7 @@ ${java.version} ${java.version} + -parameters diff --git a/jrobot-test-library/src/main/java/org/robotframework/test/BaseLibrary.java b/jrobot-test-library/src/main/java/org/robotframework/test/BaseLibrary.java index abadc35..85c1f93 100644 --- a/jrobot-test-library/src/main/java/org/robotframework/test/BaseLibrary.java +++ b/jrobot-test-library/src/main/java/org/robotframework/test/BaseLibrary.java @@ -28,6 +28,14 @@ public BaseLibrary(RemoteServer server) { return a + b; } + @Override public double sub(double a, double b) { + return a - b; + } + + @Override public int sub(int a, int b) { + return a - b; + } + @Override public String concat(String input1, String input2) { return input1 + " " + input2; } diff --git a/jrobot-test-library/src/main/java/org/robotframework/test/TestLibraryService.java b/jrobot-test-library/src/main/java/org/robotframework/test/TestLibraryService.java index f15ae2a..fd2d1fb 100644 --- a/jrobot-test-library/src/main/java/org/robotframework/test/TestLibraryService.java +++ b/jrobot-test-library/src/main/java/org/robotframework/test/TestLibraryService.java @@ -12,6 +12,10 @@ @RobotKeywordOverload int add(int a, int b); + @RobotKeyword double sub(double a, double b); + + @RobotKeywordOverload int sub(int a, int b); + @RobotKeyword String concat(String input1, String input2); @RobotKeywordOverload String concat(String input1, int input2);