text:
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content.browser;

import android.os.Handler;
import android.os.Looper;
import android.test.suitebuilder.annotation.SmallTest;

import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.Feature;
import org.chromium.content.browser.test.util.TestCallbackHelperContainer;
import org.chromium.content_shell_apk.ContentShellActivity;

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.ref.WeakReference;

/**
 * Part of the test suite for the Java Bridge. Tests a number of features including ...
 * - The type of injected objects
 * - The type of their methods
 * - Replacing objects
 * - Removing objects
 * - Access control
 * - Calling methods on returned objects
 * - Multiply injected objects
 * - Threading
 * - Inheritance
 */
public class JavaBridgeBasicsTest extends JavaBridgeTestBase {
    private class TestController extends Controller {
        private int mIntValue;
        private long mLongValue;
        private String mStringValue;
        private boolean mBooleanValue;

        public synchronized void setIntValue(int x) {
            mIntValue = x;
            notifyResultIsReady();
        }
        public synchronized void setLongValue(long x) {
            mLongValue = x;
            notifyResultIsReady();
        }
        public synchronized void setStringValue(String x) {
            mStringValue = x;
            notifyResultIsReady();
        }
        public synchronized void setBooleanValue(boolean x) {
            mBooleanValue = x;
            notifyResultIsReady();
        }

        public synchronized int waitForIntValue() {
            waitForResult();
            return mIntValue;
        }
        public synchronized long waitForLongValue() {
            waitForResult();
            return mLongValue;
        }
        public synchronized String waitForStringValue() {
            waitForResult();
            return mStringValue;
        }
        public synchronized boolean waitForBooleanValue() {
            waitForResult();
            return mBooleanValue;
        }

        public synchronized String getStringValue() {
            return mStringValue;
        }
    }

    private static class ObjectWithStaticMethod {
        public static String staticMethod() {
            return "foo";
        }
    }

    TestController mTestController;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        mTestController = new TestController();
        setUpContentView(mTestController, "testController");
    }

    @Override
    protected ContentShellActivity launchContentShellWithUrl(String url) {
        // Expose a global function "gc()" into pages.
        return launchContentShellWithUrlAndCommandLineArgs(
                url, new String[]{ "--js-flags=--expose-gc" });
    }

    // Note that this requires that we can pass a JavaScript string to Java.
    protected String executeJavaScriptAndGetStringResult(String script) throws Throwable {
        executeJavaScript("testController.setStringValue(" + script + ");");
        return mTestController.waitForStringValue();
    }

    protected void injectObjectAndReload(final Object object, final String name) throws Throwable {
        injectObjectAndReload(object, name, null);
    }

    protected void injectObjectAndReload(final Object object, final String name,
            final Class<? extends Annotation> requiredAnnotation) throws Throwable {
        TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                mTestCallbackHelperContainer.getOnPageFinishedHelper();
        int currentCallCount = onPageFinishedHelper.getCallCount();
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                getContentViewCore().addPossiblyUnsafeJavascriptInterface(object,
                        name, requiredAnnotation);
                getContentViewCore().reload(true);
            }
        });
        onPageFinishedHelper.waitForCallback(currentCallCount);
    }

    protected void synchronousPageReload() throws Throwable {
        TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                mTestCallbackHelperContainer.getOnPageFinishedHelper();
        int currentCallCount = onPageFinishedHelper.getCallCount();
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                getContentViewCore().reload(true);
            }
        });
        onPageFinishedHelper.waitForCallback(currentCallCount);
    }

    // Note that this requires that we can pass a JavaScript boolean to Java.
    private void assertRaisesException(String script) throws Throwable {
        executeJavaScript("try {" +
                          script + ";" +
                          "  testController.setBooleanValue(false);" +
                          "} catch (exception) {" +
                          "  testController.setBooleanValue(true);" +
                          "}");
        assertTrue(mTestController.waitForBooleanValue());
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testTypeOfInjectedObject() throws Throwable {
        assertEquals("object", executeJavaScriptAndGetStringResult("typeof testController"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testAdditionNotReflectedUntilReload() throws Throwable {
        assertEquals("undefined", executeJavaScriptAndGetStringResult("typeof testObject"));
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                getContentViewCore().addPossiblyUnsafeJavascriptInterface(
                        new Object(), "testObject", null);
            }
        });
        assertEquals("undefined", executeJavaScriptAndGetStringResult("typeof testObject"));
        synchronousPageReload();
        assertEquals("object", executeJavaScriptAndGetStringResult("typeof testObject"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testRemovalNotReflectedUntilReload() throws Throwable {
        injectObjectAndReload(new Object(), "testObject");
        assertEquals("object", executeJavaScriptAndGetStringResult("typeof testObject"));
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                getContentViewCore().removeJavascriptInterface("testObject");
            }
        });
        assertEquals("object", executeJavaScriptAndGetStringResult("typeof testObject"));
        synchronousPageReload();
        assertEquals("undefined", executeJavaScriptAndGetStringResult("typeof testObject"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testRemoveObjectNotAdded() throws Throwable {
        TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                mTestCallbackHelperContainer.getOnPageFinishedHelper();
        int currentCallCount = onPageFinishedHelper.getCallCount();
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                getContentViewCore().removeJavascriptInterface("foo");
                getContentViewCore().reload(true);
            }
        });
        onPageFinishedHelper.waitForCallback(currentCallCount);
        assertEquals("undefined", executeJavaScriptAndGetStringResult("typeof foo"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testTypeOfMethod() throws Throwable {
        assertEquals("function",
                executeJavaScriptAndGetStringResult("typeof testController.setStringValue"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testTypeOfInvalidMethod() throws Throwable {
        assertEquals("undefined", executeJavaScriptAndGetStringResult("typeof testController.foo"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testCallingInvalidMethodRaisesException() throws Throwable {
        assertRaisesException("testController.foo()");
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testUncaughtJavaExceptionRaisesJavaScriptException() throws Throwable {
        injectObjectAndReload(new Object() {
            public void method() { throw new RuntimeException("foo"); }
        }, "testObject");
        assertRaisesException("testObject.method()");
    }

    // Note that this requires that we can pass a JavaScript string to Java.
    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testTypeOfStaticMethod() throws Throwable {
        injectObjectAndReload(new ObjectWithStaticMethod(), "testObject");
        executeJavaScript("testController.setStringValue(typeof testObject.staticMethod)");
        assertEquals("function", mTestController.waitForStringValue());
    }

    // Note that this requires that we can pass a JavaScript string to Java.
    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testCallStaticMethod() throws Throwable {
        injectObjectAndReload(new ObjectWithStaticMethod(), "testObject");
        executeJavaScript("testController.setStringValue(testObject.staticMethod())");
        assertEquals("foo", mTestController.waitForStringValue());
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testPrivateMethodNotExposed() throws Throwable {
        injectObjectAndReload(new Object() {
            private void method() {}
            protected void method2() {}
        }, "testObject");
        assertEquals("undefined",
                executeJavaScriptAndGetStringResult("typeof testObject.method"));
        assertEquals("undefined",
                executeJavaScriptAndGetStringResult("typeof testObject.method2"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testReplaceInjectedObject() throws Throwable {
        injectObjectAndReload(new Object() {
            public void method() { mTestController.setStringValue("object 1"); }
        }, "testObject");
        executeJavaScript("testObject.method()");
        assertEquals("object 1", mTestController.waitForStringValue());

        injectObjectAndReload(new Object() {
            public void method() { mTestController.setStringValue("object 2"); }
        }, "testObject");
        executeJavaScript("testObject.method()");
        assertEquals("object 2", mTestController.waitForStringValue());
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testInjectNullObjectIsIgnored() throws Throwable {
        injectObjectAndReload(null, "testObject");
        assertEquals("undefined", executeJavaScriptAndGetStringResult("typeof testObject"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testReplaceInjectedObjectWithNullObjectIsIgnored() throws Throwable {
        injectObjectAndReload(new Object(), "testObject");
        assertEquals("object", executeJavaScriptAndGetStringResult("typeof testObject"));
        injectObjectAndReload(null, "testObject");
        assertEquals("object", executeJavaScriptAndGetStringResult("typeof testObject"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testCallOverloadedMethodWithDifferentNumberOfArguments() throws Throwable {
        injectObjectAndReload(new Object() {
            public void method() { mTestController.setStringValue("0 args"); }
            public void method(int x) { mTestController.setStringValue("1 arg"); }
            public void method(int x, int y) { mTestController.setStringValue("2 args"); }
        }, "testObject");
        executeJavaScript("testObject.method()");
        assertEquals("0 args", mTestController.waitForStringValue());
        executeJavaScript("testObject.method(42)");
        assertEquals("1 arg", mTestController.waitForStringValue());
        executeJavaScript("testObject.method(null)");
        assertEquals("1 arg", mTestController.waitForStringValue());
        executeJavaScript("testObject.method(undefined)");
        assertEquals("1 arg", mTestController.waitForStringValue());
        executeJavaScript("testObject.method(42, 42)");
        assertEquals("2 args", mTestController.waitForStringValue());
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testCallMethodWithWrongNumberOfArgumentsRaisesException() throws Throwable {
        assertRaisesException("testController.setIntValue()");
        assertRaisesException("testController.setIntValue(42, 42)");
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testObjectPersistsAcrossPageLoads() throws Throwable {
        assertEquals("object", executeJavaScriptAndGetStringResult("typeof testController"));
        synchronousPageReload();
        assertEquals("object", executeJavaScriptAndGetStringResult("typeof testController"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testCustomPropertiesCleanedUpOnPageReloads() throws Throwable {
        assertEquals("object", executeJavaScriptAndGetStringResult("typeof testController"));
        executeJavaScript("testController.myProperty = 42;");
        assertEquals("42", executeJavaScriptAndGetStringResult("testController.myProperty"));
        synchronousPageReload();
        assertEquals("object", executeJavaScriptAndGetStringResult("typeof testController"));
        assertEquals("undefined", executeJavaScriptAndGetStringResult("testController.myProperty"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testSameObjectInjectedMultipleTimes() throws Throwable {
        class TestObject {
            private int mNumMethodInvocations;
            public void method() { mTestController.setIntValue(++mNumMethodInvocations); }
        }
        final TestObject testObject = new TestObject();
        TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                mTestCallbackHelperContainer.getOnPageFinishedHelper();
        int currentCallCount = onPageFinishedHelper.getCallCount();
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                getContentViewCore().addPossiblyUnsafeJavascriptInterface(
                        testObject, "testObject1", null);
                getContentViewCore().addPossiblyUnsafeJavascriptInterface(
                        testObject, "testObject2", null);
                getContentViewCore().reload(true);
            }
        });
        onPageFinishedHelper.waitForCallback(currentCallCount);
        executeJavaScript("testObject1.method()");
        assertEquals(1, mTestController.waitForIntValue());
        executeJavaScript("testObject2.method()");
        assertEquals(2, mTestController.waitForIntValue());
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testCallMethodOnReturnedObject() throws Throwable {
        injectObjectAndReload(new Object() {
            public Object getInnerObject() {
                return new Object() {
                    public void method(int x) { mTestController.setIntValue(x); }
                };
            }
        }, "testObject");
        executeJavaScript("testObject.getInnerObject().method(42)");
        assertEquals(42, mTestController.waitForIntValue());
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testReturnedObjectInjectedElsewhere() throws Throwable {
        class InnerObject {
            private int mNumMethodInvocations;
            public void method() { mTestController.setIntValue(++mNumMethodInvocations); }
        }
        final InnerObject innerObject = new InnerObject();
        final Object object = new Object() {
            public InnerObject getInnerObject() {
                return innerObject;
            }
        };
        TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                mTestCallbackHelperContainer.getOnPageFinishedHelper();
        int currentCallCount = onPageFinishedHelper.getCallCount();
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                getContentViewCore().addPossiblyUnsafeJavascriptInterface(
                        object, "testObject", null);
                getContentViewCore().addPossiblyUnsafeJavascriptInterface(
                        innerObject, "innerObject", null);
                getContentViewCore().reload(true);
            }
        });
        onPageFinishedHelper.waitForCallback(currentCallCount);
        executeJavaScript("testObject.getInnerObject().method()");
        assertEquals(1, mTestController.waitForIntValue());
        executeJavaScript("innerObject.method()");
        assertEquals(2, mTestController.waitForIntValue());
    }

    // Verify that Java objects returned from bridge object methods are dereferenced
    // on the Java side once they have been fully dereferenced on the JS side.
    // Failing this test would mean that methods returning objects effectively create a memory
    // leak.
    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testReturnedObjectIsGarbageCollected() throws Throwable {
        // Make sure V8 exposes "gc" property on the global object (enabled with --expose-gc flag)
        assertEquals("function", executeJavaScriptAndGetStringResult("typeof gc"));
        class InnerObject {
        }
        class TestObject {
            public InnerObject getInnerObject() {
                InnerObject inner = new InnerObject();
                weakRefForInner = new WeakReference<InnerObject>(inner);
                return inner;
            }
            // A weak reference is used to check InnerObject instance reachability.
            WeakReference<InnerObject> weakRefForInner;
        }
        TestObject object = new TestObject();
        injectObjectAndReload(object, "testObject");
        // Initially, store a reference to the inner object in JS to make sure it's not
        // garbage-collected prematurely.
        assertEquals("object", executeJavaScriptAndGetStringResult(
                        "(function() { " +
                        "globalInner = testObject.getInnerObject(); return typeof globalInner; " +
                        "})()"));
        assertTrue(object.weakRefForInner.get() != null);
        // Check that returned Java object is being held by the Java bridge, thus it's not
        // collected.  Note that despite that what JavaDoc says about invoking "gc()", both Dalvik
        // and ART actually run the collector.
        Runtime.getRuntime().gc();
        assertTrue(object.weakRefForInner.get() != null);
        // Now dereference the inner object in JS and run GC to collect the interface object.
        assertEquals("true", executeJavaScriptAndGetStringResult(
                        "(function() { " +
                        "delete globalInner; gc(); return (typeof globalInner == 'undefined'); " +
                        "})()"));
        // Force GC on the Java side again. The bridge had to release the inner object, so it must
        // be collected this time.
        Runtime.getRuntime().gc();
        assertEquals(null, object.weakRefForInner.get());
    }

    /*
     * The current Java bridge implementation doesn't reuse JS wrappers when returning
     * the same object from a method. That looks wrong. For example, in the case of DOM,
     * wrappers are reused, which allows JS code to attach custom properties to interface
     * objects and use them regardless of the way the reference has been obtained:
     * via copying a JS reference or by calling the method one more time (assuming that
     * the method is supposed to return a reference to the same object each time).
     * TODO(mnaganov): Fix this in the new implementation.
     *
     * @SmallTest
     * @Feature({"AndroidWebView", "Android-JavaBridge"})
     */
    @DisabledTest
    public void testSameReturnedObjectUsesSameWrapper() throws Throwable {
        class InnerObject {
        }
        final InnerObject innerObject = new InnerObject();
        final Object injectedTestObject = new Object() {
            public InnerObject getInnerObject() {
                return innerObject;
            }
        };
        injectObjectAndReload(injectedTestObject, "injectedTestObject");
        executeJavaScript("inner1 = injectedTestObject.getInnerObject()");
        executeJavaScript("inner2 = injectedTestObject.getInnerObject()");
        assertEquals("object", executeJavaScriptAndGetStringResult("typeof inner1"));
        assertEquals("object", executeJavaScriptAndGetStringResult("typeof inner2"));
        assertEquals("true", executeJavaScriptAndGetStringResult("inner1 === inner2"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testMethodInvokedOnBackgroundThread() throws Throwable {
        injectObjectAndReload(new Object() {
            public void captureThreadId() {
                mTestController.setLongValue(Thread.currentThread().getId());
            }
        }, "testObject");
        executeJavaScript("testObject.captureThreadId()");
        final long threadId = mTestController.waitForLongValue();
        assertFalse(threadId == Thread.currentThread().getId());
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                assertFalse(threadId == Thread.currentThread().getId());
            }
        });
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testPublicInheritedMethod() throws Throwable {
        class Base {
            public void method(int x) { mTestController.setIntValue(x); }
        }
        class Derived extends Base {
        }
        injectObjectAndReload(new Derived(), "testObject");
        assertEquals("function", executeJavaScriptAndGetStringResult("typeof testObject.method"));
        executeJavaScript("testObject.method(42)");
        assertEquals(42, mTestController.waitForIntValue());
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testPrivateInheritedMethod() throws Throwable {
        class Base {
            private void method() {}
        }
        class Derived extends Base {
        }
        injectObjectAndReload(new Derived(), "testObject");
        assertEquals("undefined", executeJavaScriptAndGetStringResult("typeof testObject.method"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testOverriddenMethod() throws Throwable {
        class Base {
            public void method() { mTestController.setStringValue("base"); }
        }
        class Derived extends Base {
            @Override
            public void method() { mTestController.setStringValue("derived"); }
        }
        injectObjectAndReload(new Derived(), "testObject");
        executeJavaScript("testObject.method()");
        assertEquals("derived", mTestController.waitForStringValue());
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testEnumerateMembers() throws Throwable {
        injectObjectAndReload(new Object() {
            public void method() {}
            private void privateMethod() {}
            public int field;
            private int privateField;
        }, "testObject");
        executeJavaScript(
                "var result = \"\"; " +
                "for (x in testObject) { result += \" \" + x } " +
                "testController.setStringValue(result);");
        assertEquals(" equals getClass hashCode method notify notifyAll toString wait",
                mTestController.waitForStringValue());
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testReflectPublicMethod() throws Throwable {
        injectObjectAndReload(new Object() {
            public Class<?> myGetClass() { return getClass(); }
            public String method() { return "foo"; }
        }, "testObject");
        assertEquals("foo", executeJavaScriptAndGetStringResult(
                "testObject.myGetClass().getMethod('method', null).invoke(testObject, null)" +
                ".toString()"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testReflectPublicField() throws Throwable {
        injectObjectAndReload(new Object() {
            public Class<?> myGetClass() { return getClass(); }
            public String field = "foo";
        }, "testObject");
        assertEquals("foo", executeJavaScriptAndGetStringResult(
                "testObject.myGetClass().getField('field').get(testObject).toString()"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testReflectPrivateMethodRaisesException() throws Throwable {
        injectObjectAndReload(new Object() {
            public Class<?> myGetClass() { return getClass(); }
            private void method() {};
        }, "testObject");
        assertRaisesException("testObject.myGetClass().getMethod('method', null)");
        // getDeclaredMethod() is able to access a private method, but invoke()
        // throws a Java exception.
        assertRaisesException(
                "testObject.myGetClass().getDeclaredMethod('method', null)." +
                "invoke(testObject, null)");
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testReflectPrivateFieldRaisesException() throws Throwable {
        injectObjectAndReload(new Object() {
            public Class<?> myGetClass() { return getClass(); }
            private int field;
        }, "testObject");
        assertRaisesException("testObject.myGetClass().getField('field')");
        // getDeclaredField() is able to access a private field, but getInt()
        // throws a Java exception.
        assertRaisesException(
                "testObject.myGetClass().getDeclaredField('field').getInt(testObject)");
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testAllowNonAnnotatedMethods() throws Throwable {
        injectObjectAndReload(new Object() {
            public String allowed() { return "foo"; }
        }, "testObject", null);

        // Test calling a method of an explicitly inherited class (Base#allowed()).
        assertEquals("foo", executeJavaScriptAndGetStringResult("testObject.allowed()"));

        // Test calling a method of an implicitly inherited class (Object#toString()).
        assertEquals("string", executeJavaScriptAndGetStringResult("typeof testObject.toString()"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testAllowOnlyAnnotatedMethods() throws Throwable {
        injectObjectAndReload(new Object() {
            @JavascriptInterface
            public String allowed() { return "foo"; }

            public String disallowed() { return "bar"; }
        }, "testObject", JavascriptInterface.class);

        // getClass() is an Object method and does not have the @JavascriptInterface annotation and
        // should not be able to be called.
        assertRaisesException("testObject.getClass()");
        assertEquals("undefined", executeJavaScriptAndGetStringResult(
                "typeof testObject.getClass"));

        // allowed() is marked with the @JavascriptInterface annotation and should be allowed to be
        // called.
        assertEquals("foo", executeJavaScriptAndGetStringResult("testObject.allowed()"));

        // disallowed() is not marked with the @JavascriptInterface annotation and should not be
        // able to be called.
        assertRaisesException("testObject.disallowed()");
        assertEquals("undefined", executeJavaScriptAndGetStringResult(
                "typeof testObject.disallowed"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testAnnotationRequirementRetainsPropertyAcrossObjects() throws Throwable {
        class Test {
            @JavascriptInterface
            public String safe() { return "foo"; }

            public String unsafe() { return "bar"; }
        }

        class TestReturner {
            @JavascriptInterface
            public Test getTest() { return new Test(); }
        }

        // First test with safe mode off.
        injectObjectAndReload(new TestReturner(), "unsafeTestObject", null);

        // safe() should be able to be called regardless of whether or not we are in safe mode.
        assertEquals("foo", executeJavaScriptAndGetStringResult(
                "unsafeTestObject.getTest().safe()"));
        // unsafe() should be able to be called because we are not in safe mode.
        assertEquals("bar", executeJavaScriptAndGetStringResult(
                "unsafeTestObject.getTest().unsafe()"));

        // Now test with safe mode on.
        injectObjectAndReload(new TestReturner(), "safeTestObject", JavascriptInterface.class);

        // safe() should be able to be called regardless of whether or not we are in safe mode.
        assertEquals("foo", executeJavaScriptAndGetStringResult(
                "safeTestObject.getTest().safe()"));
        // unsafe() should not be able to be called because we are in safe mode.
        assertRaisesException("safeTestObject.getTest().unsafe()");
        assertEquals("undefined", executeJavaScriptAndGetStringResult(
                "typeof safeTestObject.getTest().unsafe"));
        // getClass() is an Object method and does not have the @JavascriptInterface annotation and
        // should not be able to be called.
        assertRaisesException("safeTestObject.getTest().getClass()");
        assertEquals("undefined", executeJavaScriptAndGetStringResult(
                "typeof safeTestObject.getTest().getClass"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testAnnotationDoesNotGetInherited() throws Throwable {
        class Base {
            @JavascriptInterface
            public void base() { }
        }

        class Child extends Base {
            @Override
            public void base() { }
        }

        injectObjectAndReload(new Child(), "testObject", JavascriptInterface.class);

        // base() is inherited.  The inherited method does not have the @JavascriptInterface
        // annotation and should not be able to be called.
        assertRaisesException("testObject.base()");
        assertEquals("undefined", executeJavaScriptAndGetStringResult(
                "typeof testObject.base"));
    }

    @SuppressWarnings("javadoc")
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD})
    @interface TestAnnotation {
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testCustomAnnotationRestriction() throws Throwable {
        class Test {
            @TestAnnotation
            public String checkTestAnnotationFoo() { return "bar"; }

            @JavascriptInterface
            public String checkJavascriptInterfaceFoo() { return "bar"; }
        }

        // Inject javascriptInterfaceObj and require the JavascriptInterface annotation.
        injectObjectAndReload(new Test(), "javascriptInterfaceObj", JavascriptInterface.class);

        // Test#testAnnotationFoo() should fail, as it isn't annotated with JavascriptInterface.
        assertRaisesException("javascriptInterfaceObj.checkTestAnnotationFoo()");
        assertEquals("undefined", executeJavaScriptAndGetStringResult(
                "typeof javascriptInterfaceObj.checkTestAnnotationFoo"));

        // Test#javascriptInterfaceFoo() should pass, as it is annotated with JavascriptInterface.
        assertEquals("bar", executeJavaScriptAndGetStringResult(
                "javascriptInterfaceObj.checkJavascriptInterfaceFoo()"));

        // Inject testAnnotationObj and require the TestAnnotation annotation.
        injectObjectAndReload(new Test(), "testAnnotationObj", TestAnnotation.class);

        // Test#testAnnotationFoo() should pass, as it is annotated with TestAnnotation.
        assertEquals("bar", executeJavaScriptAndGetStringResult(
                "testAnnotationObj.checkTestAnnotationFoo()"));

        // Test#javascriptInterfaceFoo() should fail, as it isn't annotated with TestAnnotation.
        assertRaisesException("testAnnotationObj.checkJavascriptInterfaceFoo()");
        assertEquals("undefined", executeJavaScriptAndGetStringResult(
                "typeof testAnnotationObj.checkJavascriptInterfaceFoo"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testAddJavascriptInterfaceIsSafeByDefault() throws Throwable {
        class Test {
            public String blocked() { return "bar"; }

            @JavascriptInterface
            public String allowed() { return "bar"; }
        }

        // Manually inject the Test object, making sure to use the
        // ContentViewCore#addJavascriptInterface, not the possibly unsafe version.
        TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
                mTestCallbackHelperContainer.getOnPageFinishedHelper();
        int currentCallCount = onPageFinishedHelper.getCallCount();
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                getContentViewCore().addJavascriptInterface(new Test(),
                        "testObject");
                getContentViewCore().reload(true);
            }
        });
        onPageFinishedHelper.waitForCallback(currentCallCount);

        // Test#allowed() should pass, as it is annotated with JavascriptInterface.
        assertEquals("bar", executeJavaScriptAndGetStringResult(
                "testObject.allowed()"));

        // Test#blocked() should fail, as it isn't annotated with JavascriptInterface.
        assertRaisesException("testObject.blocked()");
        assertEquals("undefined", executeJavaScriptAndGetStringResult(
                "typeof testObject.blocked"));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testObjectsInspection() throws Throwable {
        class Test {
            @JavascriptInterface
            public String m1() { return "foo"; }

            @JavascriptInterface
            public String m2() { return "bar"; }

            @JavascriptInterface
            public String m2(int x) { return "bar " + x; }
        }

        final String jsObjectKeysTestTemplate = "Object.keys(%s).toString()";
        final String jsForInTestTemplate =
                "(function(){" +
                "  var s=[]; for(var m in %s) s.push(m); return s.join(\",\")" +
                "})()";
        final String inspectableObjectName = "testObj1";
        final String nonInspectableObjectName = "testObj2";

        // Inspection is enabled by default.
        injectObjectAndReload(new Test(), inspectableObjectName, JavascriptInterface.class);

        assertEquals("m1,m2", executeJavaScriptAndGetStringResult(
                        String.format(jsObjectKeysTestTemplate, inspectableObjectName)));
        assertEquals("m1,m2", executeJavaScriptAndGetStringResult(
                        String.format(jsForInTestTemplate, inspectableObjectName)));

        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                getContentViewCore().setAllowJavascriptInterfacesInspection(false);
            }
        });

        injectObjectAndReload(new Test(), nonInspectableObjectName, JavascriptInterface.class);

        assertEquals("", executeJavaScriptAndGetStringResult(
                        String.format(jsObjectKeysTestTemplate, nonInspectableObjectName)));
        assertEquals("", executeJavaScriptAndGetStringResult(
                        String.format(jsForInTestTemplate, nonInspectableObjectName)));
    }

    @SmallTest
    @Feature({"AndroidWebView", "Android-JavaBridge"})
    public void testAccessToObjectGetClassIsBlocked() throws Throwable {
        injectObjectAndReload(new Object(), "testObject");
        assertEquals("function", executeJavaScriptAndGetStringResult("typeof testObject.getClass"));
        boolean securityExceptionThrown = false;
        try {
            final String result = executeJavaScriptAndWaitForExceptionSynchronously(
                    "typeof testObject.getClass()");
            fail("A call to java.lang.Object.getClass has been allowed, result: '" + result + "'");
        } catch (SecurityException exception) {
            securityExceptionThrown = true;
        }
        assertTrue(securityExceptionThrown);
    }

    // Unlike executeJavaScriptAndGetStringResult, this method is sitting on the UI thread
    // until a non-null result is obtained or a Java exception has been thrown. This method is
    // capable of catching Java RuntimeExceptions happening on the UI thread asynchronously.
    private String executeJavaScriptAndWaitForExceptionSynchronously(final String script)
            throws Throwable {
        class ExitLoopException extends RuntimeException {
        }
        mTestController.setStringValue(null);
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                getContentViewCore().loadUrl(new LoadUrlParams("javascript:(function() { " +
                                "testController.setStringValue(" + script + ") })()"));
                do {
                    final Boolean[] deactivateExitLoopTask = new Boolean[1];
                    deactivateExitLoopTask[0] = false;
                    // We can't use Loop.quit(), as this is the main looper, so we throw
                    // an exception to bail out from the loop.
                    new Handler(Looper.myLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            if (!deactivateExitLoopTask[0]) {
                                throw new ExitLoopException();
                            }
                        }
                    });
                    try {
                        Looper.loop();
                    } catch (ExitLoopException e) {
                        // Intentionally empty.
                    } catch (RuntimeException e) {
                        // Prevent the task that throws the ExitLoopException from exploding
                        // on the main loop outside of this function.
                        deactivateExitLoopTask[0] = true;
                        throw e;
                    }
                } while (mTestController.getStringValue() == null ||
                        // When an exception in an injected method happens, the function returns
                        // null. We ignore this and wait until the exception on the browser side
                        // will be thrown.
                        mTestController.getStringValue().equals("null"));
            }
        });
        return mTestController.getStringValue();
    }
}


text:
<?php

namespace Parc\PuffinsBagBundle\Entity;

use Symfony\Component\HttpFoundation\File\File;
//use Doctrine\ORM\Mapping as ORM;@ORM\Entity @ORM\GeneratedValue(strategy="AUTO")
use Symfony\Component\Validator\Constraints as Assert;

/**
 * ImportDonneesCSV
 *
 *
 */
class ImportDonneesCSV
{
	/**
	*
	*/
	protected $id;

	/**
    * @Assert\File(
	*	maxSize = "500k",
	*	mimeTypes = {"text/csv", "application/csv", "text/comma-separated-values", "text/plain"} ,
	*	mimeTypesMessage = "Choisissez un fichier CSV valide" )
    */
    protected $fichierCSV;

    /**
     * Set fichierCSV
     *
     * @param $fichierCSV
     * @return fichierCSV
     */
    public function setFichierCSV(File $file)
    {
        $this->fichierCSV = $file;
    }

    /**
     * Get fichierCSV
     *
     * @return fichierCSV
     */
    public function getFichierCSV()
    {
        return $this->fichierCSV;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
// Heading
$_['heading_title']       = 'Bestsellers';

// Text
$_['text_module']         = 'Modules';
$_['text_success']        = 'Success: You have modified module bestsellers!';
$_['text_content_top']    = 'Content Top';
$_['text_content_bottom'] = 'Content Bottom';
$_['text_column_left']    = 'Column Left';
$_['text_column_right']   = 'Column Right';

// Entry
$_['entry_limit']         = 'Limit:';
$_['entry_image']         = 'Image (W x H) and Resize Type:';
$_['entry_layout']        = 'Layout:';
$_['entry_position']      = 'Position:';
$_['entry_status']        = 'Status:';
$_['entry_sort_order']    = 'Sort Order:';

// Error
$_['error_permission']    = 'Warning: You do not have permission to modify module bestsellers!';
$_['error_image']         = 'Image width & height dimensions required!';
?>


text:
package edu.pdx.cs410J.airline;

import edu.pdx.cs410J.AbstractAirline;

import java.util.Collection;

public class Airline extends AbstractAirline<Flight> {
  private final String name;

  public Airline(String name) {
    this.name = name;
  }

  @Override
  public String getName() {
    return this.name;
  }

  @Override
  public void addFlight(Flight flight) {
    throw new UnsupportedOperationException("This method is not implemented yet");
  }

  @Override
  public Collection<Flight> getFlights() {
    throw new UnsupportedOperationException("This method is not implemented yet");
  }
}


text:
package com.amazonaws.services.elasticfilesystem;

import com.amazonaws.*;
import com.amazonaws.regions.*;

import com.amazonaws.services.elasticfilesystem.model.*;

/**
 * Interface for accessing EFS.
 *

 * <fullname>Amazon Elastic File System</fullname>
 */
public interface AmazonElasticFileSystem {

    /**
     * Overrides the default endpoint for this client
     * ("https://elasticfilesystem.us-east-1.amazonaws.com"). Callers can use
     * this method to control which AWS region they want to work with.
     *

     * Callers can pass in just the endpoint (ex:
     * "elasticfilesystem.us-east-1.amazonaws.com") or a full URL, including the
     * protocol (ex: "https://elasticfilesystem.us-east-1.amazonaws.com"). If
     * the protocol is not specified here, the default protocol from this
     * client's {@link ClientConfiguration} will be used, which by default is
     * HTTPS.
     *

     * For more information on using AWS regions with the AWS SDK for Java, and
     * a complete list of all available endpoints for all AWS services, see:  http://developer.amazonwebservices.com/connect/entry.jspa?externalID=
     * 3912
     *

     * This method is not threadsafe. An endpoint should be configured when
     * the client is created and before any service requests are made. Changing
     * it afterwards creates inevitable race conditions for any service requests
     * in transit or retrying.
     *
     * @param endpoint
     *        The endpoint (ex: "elasticfilesystem.us-east-1.amazonaws.com") or
     *        a full URL, including the protocol (ex:
     *        "https://elasticfilesystem.us-east-1.amazonaws.com") of the region
     *        specific AWS endpoint this client will communicate with.
     */
    void setEndpoint(String endpoint);

    /**
     * An alternative to {@link AmazonElasticFileSystem#setEndpoint(String)},
     * sets the regional endpoint for this client's service calls. Callers can
     * use this method to control which AWS region they want to work with.
     *

     * By default, all service endpoints in all regions use the https protocol.
     * To use http instead, specify it in the {@link ClientConfiguration}
     * supplied at construction.
     *

     * This method is not threadsafe. A region should be configured when the
     * client is created and before any service requests are made. Changing it
     * afterwards creates inevitable race conditions for any service requests in
     * transit or retrying.
     *
     * @param region
     *        The region this client will communicate with. See
     *        {@link Region#getRegion(com.amazonaws.regions.Regions)} for
     *        accessing a given region. Must not be null and must be a region
     *        where the service is available.
     *
     * @see Region#getRegion(com.amazonaws.regions.Regions)
     * @see Region#createClient(Class,
     *      com.amazonaws.auth.AWSCredentialsProvider, ClientConfiguration)
     * @see Region#isServiceSupported(String)
     */
    void setRegion(Region region);

    /**
     *

     * Creates a new, empty file system. The operation requires a creation token
     * in the request that Amazon EFS uses to ensure idempotent creation
     * (calling the operation with same creation token has no effect). If a file
     * system does not currently exist that is owned by the caller's AWS account
     * with the specified creation token, this operation does the following:
     *

     *

     *
Creates a new, empty file system. The file system will have an Amazon
     * EFS assigned ID, and an initial lifecycle state "creating".

     *
Returns with the description of the created file system.

     *

     *

     * Otherwise, this operation returns a FileSystemAlreadyExists
     * error with the ID of the existing file system.
     *

     * <note>For basic use cases, you can use a randomly generated UUID for the
     * creation token.</note>
     *

     * The idempotent operation allows you to retry a
     * CreateFileSystem call without risk of creating an extra file
     * system. This can happen when an initial call fails in a way that leaves
     * it uncertain whether or not a file system was actually created. An
     * example might be that a transport level timeout occurred or your
     * connection was reset. As long as you use the same creation token, if the
     * initial call had succeeded in creating a file system, the client can
     * learn of its existence from the FileSystemAlreadyExists
     * error.
     *

     * <note>The CreateFileSystem call returns while the file
     * system's lifecycle state is still "creating". You can check the file
     * system creation status by calling the DescribeFileSystems API,
     * which among other things returns the file system state.</note>
     *

     * After the file system is fully created, Amazon EFS sets its lifecycle
     * state to "available", at which point you can create one or more mount
     * targets for the file system (CreateMountTarget) in your VPC. You
     * mount your Amazon EFS file system on an EC2 instances in your VPC via the
     * mount target. For more information, see Amazon
     * EFS: How it Works
     *

     *

     * This operation requires permission for the
     * elasticfilesystem:CreateFileSystem action.
     *

     *
     * @param createFileSystemRequest
     *        null
     * @return Result of the CreateFileSystem operation returned by the service.
     * @throws BadRequestException
     *         Returned if the request is malformed or contains an error such as
     *         an invalid parameter value or a missing required parameter.
     * @throws InternalServerErrorException
     *         Returned if an error occurred on the server side.
     * @throws FileSystemAlreadyExistsException
     *         Returned if the file system you are trying to create already
     *         exists, with the creation token you provided.
     * @throws FileSystemLimitExceededException
     *         Returned if the AWS account has already created maximum number of
     *         file systems allowed per account.
     */
    CreateFileSystemResult createFileSystem(
            CreateFileSystemRequest createFileSystemRequest);

    /**
     *

     * Creates a mount target for a file system. You can then mount the file
     * system on EC2 instances via the mount target.
     *

     *

     * You can create one mount target in each Availability Zone in your VPC.
     * All EC2 instances in a VPC within a given Availability Zone share a
     * single mount target for a given file system. If you have multiple subnets
     * in an Availability Zone, you create a mount target in one of the subnets.
     * EC2 instances do not need to be in the same subnet as the mount target in
     * order to access their file system. For more information, see Amazon
     * EFS: How it Works.
     *

     *

     * In the request, you also specify a file system ID for which you are
     * creating the mount target and the file system's lifecycle state must be
     * "available" (see DescribeFileSystems).
     *

     *

     * In the request, you also provide a subnet ID, which serves several
     * purposes:
     *

     *

     *
It determines the VPC in which Amazon EFS creates the mount target.

     *
It determines the Availability Zone in which Amazon EFS creates the
     * mount target.

     *
It determines the IP address range from which Amazon EFS selects the
     * IP address of the mount target if you don't specify an IP address in the
     * request.

     *

     *

     * After creating the mount target, Amazon EFS returns a response that
     * includes, a MountTargetId and an IpAddress. You
     * use this IP address when mounting the file system in an EC2 instance. You
     * can also use the mount target's DNS name when mounting the file system.
     * The EC2 instance on which you mount the file system via the mount target
     * can resolve the mount target's DNS name to its IP address. For more
     * information, see How it Works: Implementation Overview.
     *

     *

     * Note that you can create mount targets for a file system in only one VPC,
     * and there can be only one mount target per Availability Zone. That is, if
     * the file system already has one or more mount targets created for it, the
     * request to add another mount target must meet the following requirements:
     *

     *

     *

     *

     * The subnet specified in the request must belong to the same VPC as the
     * subnets of the existing mount targets.
     *

     *

     *
The subnet specified in the request must not be in the same
     * Availability Zone as any of the subnets of the existing mount targets.

     *

     *

     * If the request satisfies the requirements, Amazon EFS does the following:
     *

     *

     *
Creates a new mount target in the specified subnet.

     *
Also creates a new network interface in the subnet as follows:
     *

     *
If the request provides an IpAddress, Amazon EFS assigns
     * that IP address to the network interface. Otherwise, Amazon EFS assigns a
     * free address in the subnet (in the same way that the Amazon EC2
     * CreateNetworkInterface call does when a request does not
     * specify a primary private IP address).

     *
If the request provides SecurityGroups, this network
     * interface is associated with those security groups. Otherwise, it belongs
     * to the default security group for the subnet's VPC.

     *
Assigns the description
     * "Mount target fsmt-id for file system fs-id"
     * where fsmt-id is the mount target ID, and
     * fs-id is the FileSystemId.

     *
Sets the requesterManaged property of the network
     * interface to "true", and the requesterId value to "EFS".

     *

     *

     * Each Amazon EFS mount target has one corresponding requestor-managed EC2
     * network interface. After the network interface is created, Amazon EFS
     * sets the NetworkInterfaceId field in the mount target's
     * description to the network interface ID, and the IpAddress
     * field to its address. If network interface creation fails, the entire
     * CreateMountTarget operation fails.
     *

     *

     *

     * <note>The CreateMountTarget call returns only after creating
     * the network interface, but while the mount target state is still
     * "creating". You can check the mount target creation status by calling the
     * DescribeFileSystems API, which among other things returns the
     * mount target state.</note>
     *

     * We recommend you create a mount target in each of the Availability Zones.
     * There are cost considerations for using a file system in an Availability
     * Zone through a mount target created in another Availability Zone. For
     * more information, go to Amazon
     * EFS product detail page. In addition, by always using a mount target
     * local to the instance's Availability Zone, you eliminate a partial
     * failure scenario; if the Availability Zone in which your mount target is
     * created goes down, then you won't be able to access your file system
     * through that mount target.
     *

     *

     * This operation requires permission for the following action on the file
     * system:
     *

     *

     *
 elasticfilesystem:CreateMountTarget

     *

     *

     * This operation also requires permission for the following Amazon EC2
     * actions:
     *

     *

     *
 ec2:DescribeSubnets

     *
 ec2:DescribeNetworkInterfaces

     *
 ec2:CreateNetworkInterface

     *

     *
     * @param createMountTargetRequest
     *        null
     * @return Result of the CreateMountTarget operation returned by the
     *         service.
     * @throws BadRequestException
     *         Returned if the request is malformed or contains an error such as
     *         an invalid parameter value or a missing required parameter.
     * @throws InternalServerErrorException
     *         Returned if an error occurred on the server side.
     * @throws FileSystemNotFoundException
     *         Returned if the specified FileSystemId does not
     *         exist in the requester's AWS account.
     * @throws IncorrectFileSystemLifeCycleStateException
     *         Returned if the file system's life cycle state is not "created".
     * @throws MountTargetConflictException
     *         Returned if the mount target would violate one of the specified
     *         restrictions based on the file system's existing mount targets.
     * @throws SubnetNotFoundException
     *         Returned if there is no subnet with ID SubnetId
     *         provided in the request.
     * @throws NoFreeAddressesInSubnetException
     *         Returned if IpAddress was not specified in the
     *         request and there are no free IP addresses in the subnet.
     * @throws IpAddressInUseException
     *         Returned if the request specified an IpAddress that
     *         is already in use in the subnet.
     * @throws NetworkInterfaceLimitExceededException
     *         The calling account has reached the ENI limit for the specific
     *         AWS region. Client should try to delete some ENIs or get its
     *         account limit raised. For more information, go to Amazon VPC Limits in the Amazon Virtual Private Cloud User
     *         Guide (see the Network interfaces per VPC entry in the table).
     * @throws SecurityGroupLimitExceededException
     *         Returned if the size of SecurityGroups specified in
     *         the request is greater than five.
     * @throws SecurityGroupNotFoundException
     *         Returned if one of the specified security groups does not exist
     *         in the subnet's VPC.
     * @throws UnsupportedAvailabilityZoneException
     *         null
     */
    CreateMountTargetResult createMountTarget(
            CreateMountTargetRequest createMountTargetRequest);

    /**
     *

     * Creates or overwrites tags associated with a file system. Each tag is a
     * key-value pair. If a tag key specified in the request already exists on
     * the file system, this operation overwrites its value with the value
     * provided in the request. If you add the "Name" tag to your file system,
     * Amazon EFS returns it in the response to the DescribeFileSystems
     * API.
     *

     *

     * This operation requires permission for the
     * elasticfilesystem:CreateTags action.
     *

     *
     * @param createTagsRequest
     *        null
     * @throws BadRequestException
     *         Returned if the request is malformed or contains an error such as
     *         an invalid parameter value or a missing required parameter.
     * @throws InternalServerErrorException
     *         Returned if an error occurred on the server side.
     * @throws FileSystemNotFoundException
     *         Returned if the specified FileSystemId does not
     *         exist in the requester's AWS account.
     */
    void createTags(CreateTagsRequest createTagsRequest);

    /**
     *

     * Deletes a file system, permanently severing access to its contents. Upon
     * return, the file system no longer exists and you will not be able to
     * access any contents of the deleted file system.
     *

     *

     * You cannot delete a file system that is in use. That is, if the file
     * system has any mount targets, you must first delete them. For more
     * information, see DescribeMountTargets and
     * DeleteMountTarget.
     *

     * <note>The DeleteFileSystem call returns while the file
     * system state is still "deleting". You can check the file system deletion
     * status by calling the DescribeFileSystems API, which returns a
     * list of file systems in your account. If you pass file system ID or
     * creation token for the deleted file system, the
     * DescribeFileSystems will return a 404 "FileSystemNotFound"
     * error.</note>
     *

     * This operation requires permission for the
     * elasticfilesystem:DeleteFileSystem action.
     *

     *
     * @param deleteFileSystemRequest
     *        null
     * @throws BadRequestException
     *         Returned if the request is malformed or contains an error such as
     *         an invalid parameter value or a missing required parameter.
     * @throws InternalServerErrorException
     *         Returned if an error occurred on the server side.
     * @throws FileSystemNotFoundException
     *         Returned if the specified FileSystemId does not
     *         exist in the requester's AWS account.
     * @throws FileSystemInUseException
     *         Returned if a file system has mount targets.
     */
    void deleteFileSystem(DeleteFileSystemRequest deleteFileSystemRequest);

    /**
     *

     * Deletes the specified mount target.
     *

     *

     * This operation forcibly breaks any mounts of the file system via the
     * mount target being deleted, which might disrupt instances or applications
     * using those mounts. To avoid applications getting cut off abruptly, you
     * might consider unmounting any mounts of the mount target, if feasible.
     * The operation also deletes the associated network interface. Uncommitted
     * writes may be lost, but breaking a mount target using this operation does
     * not corrupt the file system itself. The file system you created remains.
     * You can mount an EC2 instance in your VPC using another mount target.
     *

     *

     * This operation requires permission for the following action on the file
     * system:
     *

     *

     *
 elasticfilesystem:DeleteMountTarget

     *

     * <note>The DeleteMountTarget call returns while the mount
     * target state is still "deleting". You can check the mount target deletion
     * by calling the DescribeMountTargets API, which returns a list of
     * mount target descriptions for the given file system. </note>
     *

     * The operation also requires permission for the following Amazon EC2
     * action on the mount target's network interface:
     *

     *

     *
 ec2:DeleteNetworkInterface

     *

     *
     * @param deleteMountTargetRequest
     *        null
     * @throws BadRequestException
     *         Returned if the request is malformed or contains an error such as
     *         an invalid parameter value or a missing required parameter.
     * @throws InternalServerErrorException
     *         Returned if an error occurred on the server side.
     * @throws DependencyTimeoutException
     *         The service timed out trying to fulfill the request, and the
     *         client should try the call again.
     * @throws MountTargetNotFoundException
     *         Returned if there is no mount target with the specified ID found
     *         in the caller's account.
     */
    void deleteMountTarget(DeleteMountTargetRequest deleteMountTargetRequest);

    /**
     *

     * Deletes the specified tags from a file system. If the
     * DeleteTags request includes a tag key that does not exist,
     * Amazon EFS ignores it; it is not an error. For more information about
     * tags and related restrictions, go to Tag Restrictions in the AWS Billing and Cost Management User
     * Guide.
     *

     *

     * This operation requires permission for the
     * elasticfilesystem:DeleteTags action.
     *

     *
     * @param deleteTagsRequest
     *        null
     * @throws BadRequestException
     *         Returned if the request is malformed or contains an error such as
     *         an invalid parameter value or a missing required parameter.
     * @throws InternalServerErrorException
     *         Returned if an error occurred on the server side.
     * @throws FileSystemNotFoundException
     *         Returned if the specified FileSystemId does not
     *         exist in the requester's AWS account.
     */
    void deleteTags(DeleteTagsRequest deleteTagsRequest);

    /**
     *

     * Returns the description of a specific Amazon EFS file system if either
     * the file system CreationToken or the
     * FileSystemId is provided; otherwise, returns descriptions of
     * all file systems owned by the caller's AWS account in the AWS region of
     * the endpoint that you're calling.
     *

     *

     * When retrieving all file system descriptions, you can optionally specify
     * the MaxItems parameter to limit the number of descriptions
     * in a response. If more file system descriptions remain, Amazon EFS
     * returns a NextMarker, an opaque token, in the response. In
     * this case, you should send a subsequent request with the
     * Marker request parameter set to the value of
     * NextMarker.
     *

     *

     * So to retrieve a list of your file system descriptions, the expected
     * usage of this API is an iterative process of first calling
     * DescribeFileSystems without the Marker and then
     * continuing to call it with the Marker parameter set to the
     * value of the NextMarker from the previous response until the
     * response has no NextMarker.
     *

     *

     * Note that the implementation may return fewer than MaxItems
     * file system descriptions while still including a NextMarker
     * value.
     *

     *

     * The order of file systems returned in the response of one
     * DescribeFileSystems call, and the order of file systems
     * returned across the responses of a multi-call iteration, is unspecified.
     *

     *

     * This operation requires permission for the
     * elasticfilesystem:DescribeFileSystems action.
     *

     *
     * @param describeFileSystemsRequest
     *        null
     * @return Result of the DescribeFileSystems operation returned by the
     *         service.
     * @throws BadRequestException
     *         Returned if the request is malformed or contains an error such as
     *         an invalid parameter value or a missing required parameter.
     * @throws InternalServerErrorException
     *         Returned if an error occurred on the server side.
     * @throws FileSystemNotFoundException
     *         Returned if the specified FileSystemId does not
     *         exist in the requester's AWS account.
     */
    DescribeFileSystemsResult describeFileSystems(
            DescribeFileSystemsRequest describeFileSystemsRequest);

    /**
     * Simplified method form for invoking the DescribeFileSystems operation.
     *
     * @see #describeFileSystems(DescribeFileSystemsRequest)
     */
    DescribeFileSystemsResult describeFileSystems();

    /**
     *

     * Returns the security groups currently in effect for a mount target. This
     * operation requires that the network interface of the mount target has
     * been created and the life cycle state of the mount target is not
     * "deleted".
     *

     *

     * This operation requires permissions for the following actions:
     *

     *

     *
 elasticfilesystem:DescribeMountTargetSecurityGroups
     * action on the mount target's file system.

     *
 ec2:DescribeNetworkInterfaceAttribute action on the
     * mount target's network interface.

     *

     *
     * @param describeMountTargetSecurityGroupsRequest
     *        null
     * @return Result of the DescribeMountTargetSecurityGroups operation
     *         returned by the service.
     * @throws BadRequestException
     *         Returned if the request is malformed or contains an error such as
     *         an invalid parameter value or a missing required parameter.
     * @throws InternalServerErrorException
     *         Returned if an error occurred on the server side.
     * @throws MountTargetNotFoundException
     *         Returned if there is no mount target with the specified ID found
     *         in the caller's account.
     * @throws IncorrectMountTargetStateException
     *         Returned if the mount target is not in the correct state for the
     *         operation.
     */
    DescribeMountTargetSecurityGroupsResult describeMountTargetSecurityGroups(
            DescribeMountTargetSecurityGroupsRequest describeMountTargetSecurityGroupsRequest);

    /**
     *

     * Returns the descriptions of all the current mount targets, or a specific
     * mount target, for a file system. When requesting all of the current mount
     * targets, the order of mount targets returned in the response is
     * unspecified.
     *

     *

     * This operation requires permission for the
     * elasticfilesystem:DescribeMountTargets action, on either the
     * file system id that you specify in FileSystemId, or on the
     * file system of the mount target that you specify in
     * MountTargetId.
     *

     *
     * @param describeMountTargetsRequest
     *        null
     * @return Result of the DescribeMountTargets operation returned by the
     *         service.
     * @throws BadRequestException
     *         Returned if the request is malformed or contains an error such as
     *         an invalid parameter value or a missing required parameter.
     * @throws InternalServerErrorException
     *         Returned if an error occurred on the server side.
     * @throws FileSystemNotFoundException
     *         Returned if the specified FileSystemId does not
     *         exist in the requester's AWS account.
     * @throws MountTargetNotFoundException
     *         Returned if there is no mount target with the specified ID found
     *         in the caller's account.
     */
    DescribeMountTargetsResult describeMountTargets(
            DescribeMountTargetsRequest describeMountTargetsRequest);

    /**
     *

     * Returns the tags associated with a file system. The order of tags
     * returned in the response of one DescribeTags call, and the
     * order of tags returned across the responses of a multi-call iteration
     * (when using pagination), is unspecified.
     *

     *

     * This operation requires permission for the
     * elasticfilesystem:DescribeTags action.
     *

     *
     * @param describeTagsRequest
     *        null
     * @return Result of the DescribeTags operation returned by the service.
     * @throws BadRequestException
     *         Returned if the request is malformed or contains an error such as
     *         an invalid parameter value or a missing required parameter.
     * @throws InternalServerErrorException
     *         Returned if an error occurred on the server side.
     * @throws FileSystemNotFoundException
     *         Returned if the specified FileSystemId does not
     *         exist in the requester's AWS account.
     */
    DescribeTagsResult describeTags(DescribeTagsRequest describeTagsRequest);

    /**
     *

     * Modifies the set of security groups in effect for a mount target.
     *

     *

     * When you create a mount target, Amazon EFS also creates a new network
     * interface (see CreateMountTarget). This operation replaces the
     * security groups in effect for the network interface associated with a
     * mount target, with the SecurityGroups provided in the
     * request. This operation requires that the network interface of the mount
     * target has been created and the life cycle state of the mount target is
     * not "deleted".
     *

     *

     * The operation requires permissions for the following actions:
     *

     *

     *
 elasticfilesystem:ModifyMountTargetSecurityGroups action
     * on the mount target's file system.

     *
 ec2:ModifyNetworkInterfaceAttribute action on the mount
     * target's network interface.

     *

     *
     * @param modifyMountTargetSecurityGroupsRequest
     *        null
     * @throws BadRequestException
     *         Returned if the request is malformed or contains an error such as
     *         an invalid parameter value or a missing required parameter.
     * @throws InternalServerErrorException
     *         Returned if an error occurred on the server side.
     * @throws MountTargetNotFoundException
     *         Returned if there is no mount target with the specified ID found
     *         in the caller's account.
     * @throws IncorrectMountTargetStateException
     *         Returned if the mount target is not in the correct state for the
     *         operation.
     * @throws SecurityGroupLimitExceededException
     *         Returned if the size of SecurityGroups specified in
     *         the request is greater than five.
     * @throws SecurityGroupNotFoundException
     *         Returned if one of the specified security groups does not exist
     *         in the subnet's VPC.
     */
    void modifyMountTargetSecurityGroups(
            ModifyMountTargetSecurityGroupsRequest modifyMountTargetSecurityGroupsRequest);

    /**
     * Shuts down this client object, releasing any resources that might be held
     * open. This is an optional method, and callers are not expected to call
     * it, but can if they want to explicitly release any open resources. Once a
     * client has been shutdown, it should not be used to make any more
     * requests.
     */
    void shutdown();

    /**
     * Returns additional metadata for a previously executed successful request,
     * typically used for debugging issues where a service isn't acting as
     * expected. This data isn't considered part of the result data returned by
     * an operation, so it's available through this separate, diagnostic
     * interface.
     *

     * Response metadata is only cached for a limited period of time, so if you
     * need to access this extra diagnostic information for an executed request,
     * you should use this method to retrieve it as soon as possible after
     * executing a request.
     *
     * @param request
     *        The originally executed request.
     *
     * @return The response metadata for the specified request, or null if none
     *         is available.
     */
    ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request);
}


text:
use Box;
use Container;
use Orientable;
use RecentChooser;
use RecentManager;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::translate::*;

glib_wrapper! {
    pub struct RecentChooserWidget(Object<ffi::GtkRecentChooserWidget>): Box, Container, Widget, Orientable, RecentChooser;

    match fn {
        get_type => || ffi::gtk_recent_chooser_widget_get_type(),
    }
}

impl RecentChooserWidget {
    pub fn new() -> RecentChooserWidget {
        assert_initialized_main_thread!();
        unsafe {
            Widget::from_glib_none(ffi::gtk_recent_chooser_widget_new()).downcast_unchecked()
        }
    }

    pub fn new_for_manager(manager: &RecentManager) -> RecentChooserWidget {
        skip_assert_initialized!();
        unsafe {
            Widget::from_glib_none(ffi::gtk_recent_chooser_widget_new_for_manager(manager.to_glib_none().0)).downcast_unchecked()
        }
    }
}


text:
<?php

namespace app\models;

use Yii;
use \app\models\base\TblTeacher as BaseTblTeacher;

/**
 * This is the model class for table "tbl_teacher".
 */
class TblTeacher extends BaseTblTeacher
{
}


text:
import React, { Component } from 'react';
import { connect } from 'react-redux';

import { fetchGene } from '../../actions/genes';
import { selectGene } from '../../selectors/geneSelectors';

import BasicGeneInfo from './basicGeneInfo';
import GenePageHeader from './genePageHeader';
import { OrthologyTable } from '../../components/orthology';
import DiseaseTable from '../../components/disease';
import GeneOntologyRibbon from '../../components/geneOntologyRibbon';
import Subsection from '../../components/subsection';
import HeadMetaTags from '../../components/headMetaTags';
import TranscriptInlineViewer from './transcriptInlineViewer';

class GenePage extends Component {

  componentDidMount() {
    this.props.dispatch(fetchGene(this.props.params.geneId));
  }

  componentDidUpdate(prevProps) {
    if (this.props.params.geneId !== prevProps.params.geneId) {
      this.props.dispatch(fetchGene(this.props.params.geneId));
    }
  }

  render() {
    if (this.props.loading) {
      return loading...;
    }

    if (this.props.error) {
      return
{this.props.error}
;
    }

    if (!this.props.data) {
      return null;
    }

    let title = 'AGR gene page for ' + this.props.data.species + ' gene: ' + this.props.data.symbol;

    // todo, add chromosome
    let genomeLocation = {};
    if(this.props.data.genomeLocations){
      if(this.props.data.genomeLocations.length==1){
        genomeLocation = this.props.data.genomeLocations[0];
      }
      else
      if(this.props.data.genomeLocations.length>1){
        // TODO: figure out the proper assembly
        for(var i in this.props.data.genomeLocations){
          let tempGenomeLocation = this.props.data.genomeLocations[i];
          if(tempGenomeLocation.start && tempGenomeLocation.end){
            genomeLocation = tempGenomeLocation;
          }
        }
      }
    }

    let now = new Date();
    let date = now.getFullYear() + '-' + ('0' + (now.getMonth() + 1)).slice(-2) + '-' + ('0' + now.getDate()).slice(-2);

    return (

        <HeadMetaTags title={title} />
        <GenePageHeader symbol={this.props.data.symbol} />

        <Subsection>
          <BasicGeneInfo geneData={this.props.data} />
        </Subsection>

        <Subsection hasData={typeof genomeLocation.start !== 'undefined' && typeof genomeLocation.end !== 'undefined'} title='Gene Model'>
          <TranscriptInlineViewer
            chromosome={genomeLocation.chromosome}
            fmax={genomeLocation.end}
            fmin={genomeLocation.start}
            geneSymbol={this.props.data.symbol}
            species={this.props.data.species}
          />
        </Subsection>

        <Subsection title='Function'>
          <GeneOntologyRibbon id={this.props.data.primaryId} />
        </Subsection>

        <Subsection hasData={(this.props.data.orthology || []).length > 0} title='Orthology'>
          <OrthologyTable data={this.props.data.orthology} />
        </Subsection>

        <Subsection hasData={this.props.data.diseases.length > 0} title='Disease Associations'>
          <DiseaseTable data={this.props.data.diseases} filename={`${this.props.data.symbol}-Disease-Associations-${date}`} />
        </Subsection>

    );
  }
}

GenePage.propTypes = {
  data: React.PropTypes.object,
  dispatch: React.PropTypes.func,
  error: React.PropTypes.object,
  loading: React.PropTypes.bool,
  params: React.PropTypes.object,
};

function mapStateToProps(state) {
  return selectGene(state);
}

export { GenePage as GenePage };
export default connect(mapStateToProps)(GenePage);


text:
import { CanActivate, Component, ChangeDetectionStrategy } from "../core";
import { RegistrationActionCreator } from "./registration.actions";

@Component({
    template: require("./registration.component.html"),
    styles: [require("./registration.component.css")],
    selector: "registration",
    viewProviders: ["invokeAsync", "registrationActionCreator"],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class RegistrationComponent {
    constructor(private invokeAsync, private registrationActionCreator: RegistrationActionCreator) { }

    tryToRegister = () => {
        this.invokeAsync({
            action: this.registrationActionCreator.register,
            params: {
                data: this.entity
            }
        }).then(() => {
            this.registrationActionCreator.registrationSuccess({ entity: this.entity });
        });
    }

    entity;
}


text:
"""Test for vm providers."""

import mock
import six

from rally.common import sshutils
from rally.deploy import serverprovider
from rally import exceptions
from tests.unit import test

ProviderFactory = serverprovider.ProviderFactory

class ProviderMixIn(object):
    def create_servers(self, image_uuid=None, amount=1):
        pass

    def destroy_servers(self):
        pass

class ProviderA(ProviderMixIn, ProviderFactory):
    """Fake server provider.

    Used for tests.
    """
    pass

class ProviderB(ProviderMixIn, ProviderFactory):
    """Fake server provider.

    Used for tests.
    """
    pass

class ProviderC(ProviderB):
    """Fake server provider.

    Used for tests.
    """
    pass

FAKE_PROVIDERS = [ProviderA, ProviderB, ProviderC]

class ProviderTestCase(test.TestCase):

    @mock.patch.object(ProviderFactory, "validate")
    def test_init(self, fake_validate):
        ProviderA(None, None)
        fake_validate.assert_called_once_with()

    def test_get_provider_not_found(self):
        self.assertRaises(exceptions.NoSuchVMProvider,
                          ProviderFactory.get_provider,
                          {"type": "fail"}, None)

    def test_get_provider(self):
        for p in FAKE_PROVIDERS:
                p_inst = ProviderFactory.get_provider({"type": p.__name__},
                                                      None)
                self.assertIsInstance(p_inst, p)

    def test_get_by_name(self):
        for p in FAKE_PROVIDERS:
            self.assertEqual(p, ProviderFactory.get_by_name(p.__name__))

    def test_get_by_name_not_found(self):
        self.assertRaises(exceptions.NoSuchVMProvider,
                          ProviderFactory.get_by_name,
                          "NonExistingServers")

    def test_get_available_providers(self):
        providers = set([p.__name__ for p in FAKE_PROVIDERS])
        real_providers = set(ProviderFactory.get_available_providers())
        self.assertEqual(providers & real_providers, providers)

    def test_vm_prvoider_factory_is_abstract(self):
        self.assertRaises(TypeError, ProviderFactory)

class ServerTestCase(test.TestCase):
    def setUp(self):
        super(ServerTestCase, self).setUp()
        self.vals = ["192.168.1.1", "admin", "some_key", "pwd"]
        self.keys = ["host", "user", "key", "password"]

    def test_init_server_dto(self):
        server = serverprovider.Server(*self.vals)
        for k, v in six.iteritems(dict(zip(self.keys, self.vals))):
            self.assertEqual(getattr(server, k), v)
        self.assertIsInstance(server.ssh, sshutils.SSH)

    def test_credentials(self):
        server_one = serverprovider.Server(*self.vals)
        creds = server_one.get_credentials()
        server_two = serverprovider.Server.from_credentials(creds)
        for k in self.keys:
            self.assertEqual(getattr(server_one, k), getattr(server_two, k))

class ResourceManagerTestCase(test.TestCase):
    def setUp(self):
        super(ResourceManagerTestCase, self).setUp()
        self.deployment = mock.Mock()
        self.resources = serverprovider.ResourceManager(self.deployment,
                                                        "provider")

    def test_create(self):
        self.resources.create("info", type="type")
        self.deployment.add_resource.assert_called_once_with("provider",
                                                             type="type",
                                                             info="info")

    def test_get_all(self):
        self.resources.get_all(type="type")
        self.deployment.get_resources.assert_called_once_with(
            provider_name="provider", type="type")

    def test_delete(self):
        self.resources.delete("resource_id")
        self.deployment.delete_resource.assert_called_once_with("resource_id")


text:
/**
 * @fileoverview Tests for the email change revocation page.
 */

goog.provide('firebaseui.auth.ui.page.EmailChangeRevokeTest');
goog.setTestOnly('firebaseui.auth.ui.page.EmailChangeRevokeTest');

goog.require('firebaseui.auth.ui.element.FormTestHelper');
goog.require('firebaseui.auth.ui.element.InfoBarTestHelper');
goog.require('firebaseui.auth.ui.page.EmailChangeRevoke');
goog.require('firebaseui.auth.ui.page.PageTestHelper');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.testing.MockClock');
goog.require('goog.testing.events');
goog.require('goog.testing.jsunit');

var mockClock;
var root;
var component;
var formTestHelper = new firebaseui.auth.ui.element.FormTestHelper().
    excludeTests('testOnLinkClick_', 'testOnLinkEnter_').
    registerTests();
var infoBarTestHelper =
    new firebaseui.auth.ui.element.InfoBarTestHelper().registerTests();
var pageTestHelper =
    new firebaseui.auth.ui.page.PageTestHelper().registerTests();

var updateClicked;
var onClick;

function setUp() {
  // Set up clock.
  mockClock = new goog.testing.MockClock();
  mockClock.install();
  updateClicked = false;
  onClick = function() {
    updateClicked = true;
  };
  root = goog.dom.createDom(goog.dom.TagName.DIV);
  document.body.appendChild(root);
  component = new firebaseui.auth.ui.page.EmailChangeRevoke(
      'user@example.com',
      onClick,
      goog.bind(
          firebaseui.auth.ui.element.FormTestHelper.prototype.onSubmit,
          formTestHelper));
  component.render(root);
  formTestHelper.setComponent(component);
  // Reset previous state of form helper.
  formTestHelper.resetState();
  infoBarTestHelper.setComponent(component);
  pageTestHelper.setClock(mockClock).setComponent(component);
}

function tearDown() {
  // Tear down clock.
  mockClock.tick(Infinity);
  mockClock.reset();
  component.dispose();
  goog.dom.removeNode(root);
}

function testEmailChangeRevoke_resetPassword() {
  var link = component.getResetPasswordElement();
  assertNotNull(link);
  assertFalse(updateClicked);
  goog.testing.events.fireClickSequence(link);
  assertTrue(updateClicked);
}

function testEmailChangeRevoke_pageEvents() {
  // Run page event tests.
  // Dispose previously created container since test must run before rendering
  // the component in document.
  component.dispose();
  // Initialize component.
  component = new firebaseui.auth.ui.page.EmailChangeRevoke(
      'user@example.com',
      onClick,
      goog.bind(
          firebaseui.auth.ui.element.FormTestHelper.prototype.onSubmit,
          formTestHelper));
  // Run all page helper tests.
  pageTestHelper.runTests(component, root);
}

function testEmailChangeRevoke_getPageId() {
  assertEquals('emailChangeRevoke', component.getPageId());
}


text:
const faker = require('faker');
const uuid = require('uuid-v4');

const generateTransaction = (sender, receiver) => ({
  amount: faker.random.number(),
  created_at: faker.date.past().getTime(),
  description: faker.lorem.words(),
  id: uuid(),
  receiver,
  sender,
});

const generateTransactions = (num, sender, receiver, transactions) => {
  if (num === 0) {
    return transactions;
  }

  return [
    ...generateTransactions(num - 1, receiver, sender, transactions),
    generateTransaction(sender, receiver)
  ];
};

module.exports = () => ({
  transactions: generateTransactions(10, uuid(), uuid(), [])
});