{"id":4822,"date":"2014-03-30T15:37:28","date_gmt":"2014-03-30T15:37:28","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2014\/03\/30\/imposing-constraints-or-restrictions-on-method-body-in-java-collection-of-common-programming-errors\/"},"modified":"2014-03-30T15:37:28","modified_gmt":"2014-03-30T15:37:28","slug":"imposing-constraints-or-restrictions-on-method-body-in-java-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2014\/03\/30\/imposing-constraints-or-restrictions-on-method-body-in-java-collection-of-common-programming-errors\/","title":{"rendered":"Imposing constraints or restrictions on method body, in Java-Collection of common programming errors"},"content":{"rendered":"<ul>\n<li><img decoding=\"async\" src=\"http:\/\/i.stack.imgur.com\/D9tx3.jpg?s=32&amp;g=1\" \/><br \/>\nafsantos<\/p>\n<p>Some clarification was on demand, so I&#8217;ll try to sum up what influences the question.<\/p>\n<ul>\n<li>\n<p>The goal of the project is to provide a certain functionality to programmers, most probably in the form of a library (a JAR with class files, I guess).<\/p>\n<\/li>\n<li>\n<p>To use said functionality, programmers would have to conform to the constraints that <em>must<\/em> (should) be satisfied. Otherwise it won&#8217;t function as expected (just like the locks from <code>java.util.concurrent<\/code>, that must be acquired \/ freed at the appropriate time and place).<\/p>\n<\/li>\n<li>\n<p>This code won&#8217;t be the entry point to the applications using it (<em>ie<\/em>, has no <code>main<\/code>).<\/p>\n<\/li>\n<li>\n<p>There&#8217;s a limited (and small) amount of operations exposed in the API.<\/p>\n<\/li>\n<\/ul>\n<p><strong>Examples:<\/strong><\/p>\n<ol>\n<li>\n<p>Think of a small game, where almost everything is implemented and managed by the already implemented classes. The only thing left for the programmer to do, is to write a method, or a couple of them, that describe what the character will do (walk, change direction, stop, inspect object). I would want to make sure that their methods (possibly marked with an annotation?) just <code>walk<\/code>, or <code>changeDirection<\/code>, or calculate <code>diff = desiredValue - x<\/code>, and not, say, write to some file, or open a socket connection.<\/p>\n<\/li>\n<li>\n<p>Think of a transaction manager. The manager would be provided by this library, as well as some constant attributes of transactions (their isolation level, time-outs, &#8230;). Now, the programmers would like to have transactions and use this manager. I would want to make sure that they only <code>read<\/code>, <code>write<\/code>, <code>commit<\/code>, or <code>rollback<\/code> on some resources, known to the manager. I wouldn&#8217;t want them to <code>launchRocket<\/code> in the middle of the transaction, if the manager does not control any rockets to launch.<\/p>\n<\/li>\n<\/ol>\n<h2>The Problem<\/h2>\n<p>I want to impose some invariants \/ restrictions \/ constraints on the body of a method (or group of methods), to be later implemented by some other programmer, in some other package\/location. Say, I give them something along the lines of:<\/p>\n<pre><code>public abstract class ToBeExtended {\n    \/\/ some private stuff they should not modify\n    \/\/ ...\n    public abstract SomeReturnType safeMethod();\n}\n<\/code><\/pre>\n<p>It is important (probably imperative), for the purposes of this project, that the method body satisfies some invariants. Or rather, it is imperative that the set of commands this method&#8217;s implementation uses is limited. Examples of these constraints:<\/p>\n<ul>\n<li>This method must not perform any I\/O.<\/li>\n<li>This method must not instantiate any unknown (<em>potentially dangerous<\/em>) objects.<\/li>\n<li>&#8230;<\/li>\n<\/ul>\n<p>Put another way:<\/p>\n<ul>\n<li>This method can call the methods of a known (specific) class.<\/li>\n<li>This method can execute some <em>basic<\/em> instructions (maths, assign local variables, <code>if<\/code>s, loops&#8230;).<\/li>\n<\/ul>\n<p>I&#8217;ve been looking through Annotations, and there seems to be nothing close to this.<br \/>\nMy options so far:<\/p>\n<ol>\n<li>\n<p>Define some annotation, <code>@SafeAnnotation<\/code>, and apply it to the method, defining a contract with the implementer, that he will follow the rules imposed, or else the system will malfunction.<\/p>\n<\/li>\n<li>\n<p>Define an <code>Enum<\/code> with the allowed operations. Instead of exposing the allowed methods, only a method is exposed, that accepts a list of these enum objects (or something similar to a Control Flow Graph?) and executes it, giving me the control of what can be done.<\/p>\n<\/li>\n<\/ol>\n<p>Example:<\/p>\n<pre><code>public enum AllowedOperations { OP1, OP2 }\n\npublic class TheOneKnown {\n    public void executeMyStuff (List ops) {\n        \/\/ ...\n    }\n}\n<\/code><\/pre>\n<h2>My Question<\/h2>\n<p>Is there any feature in the language, such as annotations, reflection, or otherwise, allowing me to inspect (either at compile time or runtime) if a method is valid (<em>ie<\/em>, satisfies my constraints)?<br \/>\nOr rather, is there any way to enforce it to call only a limited set of other methods?<\/p>\n<p>If not (and I think not), would this second approach be a suitable alternative?<br \/>\nSuitable, as in intuitive, well designed and\/or good practice.<\/p>\n<h2>Update (Progress)<\/h2>\n<p>Having had a look at some related questions, I&#8217;m also considering (as a third option, maybe) following the steps given in the accepted answer of this question. Although, this may require some rethinking on the architecture.<\/p>\n<p>The whole idea of using annotations to impose restrictions seems to require implementing my own annotation processor. If this is true, I might as well consider a small domain-specific language, so that the programmer would use these limited operations, later translating the code to Java. This way, I would also have control over what is specified.<\/p>\n<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/i.stack.imgur.com\/bA1dl.jpg?s=32&amp;g=1\" \/><br \/>\nGaborSch<\/p>\n<p>I think that the direction in this question is good.<\/p>\n<ul>\n<li>Use a specific <code>ClassLoader<\/code> lo load the class. Beware, that they&#8217;re an interesting type of horse, it usually happens that the class itself is loaded by a parent classloader. Probably you want some sort of UrlClassLoader, and the parent classloader would be set to the Root classloader It is not enough, though.<\/li>\n<li>Use <code>threads<\/code> to avoid infinite loops (rather implementing <code>Runnable<\/code> than extending <code>Thread<\/code>, like there) &#8211; this may be unnecessary if you&#8217;re not worrying about it.<\/li>\n<li>Use SecurityManager to avoid <code>java.io<\/code> operations<\/li>\n<\/ul>\n<p>In addition to the above, I recommend 2 options:<\/p>\n<p><strong>Give the method a <em>controller<\/em>, that would contain the functions it can call<\/strong><\/p>\n<p>For example:<\/p>\n<pre><code>public void foo(Controller ctrl) {\n}\n\npublic class Controller {\n   public boolean commit();\n   public boolean rollback();\n}\n<\/code><\/pre>\n<p>This can give the user a handle, what operations are allowed.<\/p>\n<p><strong>Use an <code>Intent<\/code>-like command pattern<\/strong><\/p>\n<p>In Android, the components of the system are quite closed. They cannot directly communicate to each other, they only can fire an event, that &#8220;this happened&#8221;, or &#8220;I want to do that&#8221;.<\/p>\n<p>This way the set of the usable commands are not restricted. Usually, if the methods do only small business logic, that is enough.<\/p>\n<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/f87a659d1d01c81bd340c09f181eb90b?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\ndigitaljoel<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/18dd8455317d67a71c0978e944c2af24?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nmeriton<\/p>\n<p>You can restrict the classes used by untrusted code with a custom class loader:<\/p>\n<pre><code>public class SafeClassLoader extends ClassLoader {\n\n    Set safe = new HashSet();\n\n    {\n        String[] s = {\n            \"java.lang.Object\",\n            \"java.lang.String\",\n            \"java.lang.Integer\"\n        };\n        safe.addAll(Arrays.asList(s));\n    }\n\n    @Override\n    protected Class loadClass(String name, boolean resolve)\n            throws ClassNotFoundException {\n        if (safe.contains(name)) {\n            return super.loadClass(name, resolve);\n        } else {\n            throw new ClassNotFoundException(name);\n        }\n    }\n}\n\npublic class Sandboxer {\n    public static void main(String[] args) throws Exception {\n        File f = new File(\"bin\/\");\n        URL[] urls = {f.toURI().toURL()};\n        ClassLoader loader = new URLClassLoader(urls, new SafeClassLoader());\n        Class good = loader.loadClass(\"tools.sandbox.Good\");\n        System.out.println(good.newInstance().toString());\n        Class evil = loader.loadClass(\"tools.sandbox.Evil\");\n        System.out.println(evil.newInstance().toString());\n    }\n}\n\npublic class Good {\n    @Override\n    public String toString() {\n        return \"I am good\";\n    }\n}\n\npublic class Evil {\n    @Override\n    public String toString() {\n        new Thread().start();\n        return \"I am evil.\";\n    }\n}\n<\/code><\/pre>\n<p>Running this will result in<\/p>\n<pre><code>I am good\nException in thread \"main\" java.lang.NoClassDefFoundError: java\/lang\/Thread\n    at tools.sandbox.Evil.toString(Evil.java:7)\n    at tools.sandbox.Sandboxer.main(Sandboxer.java:18)\nCaused by: java.lang.ClassNotFoundException: java.lang.Thread\n    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)\n    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)\n    at java.security.AccessController.doPrivileged(Native Method)\n    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)\n    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)\n    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)\n    ... 2 more\n<\/code><\/pre>\n<p>Of course, this assumes care is taken with the classes you white list. It also can&#8217;t prevent denial of service stuff such as<\/p>\n<pre><code>while (true) {}\n<\/code><\/pre>\n<p>or<\/p>\n<pre><code>new long[1000000000];\n<\/code><\/pre>\n<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/b07efcf8fe5d27ff8091d0d7b131d6f4?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nGab<\/p>\n<p>Another alternative will be to use en embedded script interpreter, for example groovy one (http:\/\/groovy.codehaus.org\/Embedding+Groovy) and to evaluate the third-party methods content at runtime with a pre-execution validation.<\/p>\n<p>Advantage is that you will be able to limit access to only the variables you will bind for the script execution.<\/p>\n<p>You could also write your own validation dsl and apply it, for example using custom annotation, to the method that will execute the script.<\/p>\n<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/a65afd5c01a3afa2e75e2cb866fc02d0?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nZim-Zam O&#8217;Pootertoot<\/p>\n<p>There are several design by contract libraries available for Java, but I&#8217;m not able to recommend one in particular. Java Argument Validation appears to be a lightweight solution, but again, I don&#8217;t have first-hand experience with it.<\/p>\n<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>afsantos Some clarification was on demand, so I&#8217;ll try to sum up what influences the question. The goal of the project is to provide a certain functionality to programmers, most probably in the form of a library (a JAR with class files, I guess). To use said functionality, programmers would have to conform to the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-4822","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/4822","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=4822"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/4822\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=4822"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=4822"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=4822"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}