Search in sources :

Example 26 with Field

use of java.lang.reflect.Field in project camel by apache.

the class Mina2ProducerShutdownMockTest method testProducerShutdownTestingWithMock.

@Test
public void testProducerShutdownTestingWithMock() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedBodiesReceived("Hello World");
    // create our mock and record expected behavior = that worker timeout should be set to 0
    SocketConnector mockConnector = createMock(SocketConnector.class);
    mockConnector.dispose(true);
    replay(mockConnector);
    // normal camel code to get a producer
    Endpoint endpoint = context.getEndpoint(String.format("mina2:tcp://localhost:%1$s?textline=true&sync=false", getPort()));
    Exchange exchange = endpoint.createExchange();
    Producer producer = endpoint.createProducer();
    producer.start();
    // set input and execute it
    exchange.getIn().setBody("Hello World");
    producer.process(exchange);
    // insert our mock instead of real MINA IoConnector
    Field field = producer.getClass().getDeclaredField("connector");
    field.setAccessible(true);
    field.set(producer, mockConnector);
    //
    // Everything is asynchronous.
    // We need to wait a second to make sure we get the message.
    //
    Thread.sleep(1000);
    // stop using our mock
    producer.stop();
    verify(mockConnector);
    assertMockEndpointsSatisfied();
}
Also used : Exchange(org.apache.camel.Exchange) Field(java.lang.reflect.Field) Endpoint(org.apache.camel.Endpoint) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) Producer(org.apache.camel.Producer) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) SocketConnector(org.apache.mina.transport.socket.SocketConnector) Test(org.junit.Test)

Example 27 with Field

use of java.lang.reflect.Field in project groovy by apache.

the class BindPathSnooper method createBinding.

public FullBinding createBinding(SourceBinding source, TargetBinding target) {
    if (source != this) {
        throw new RuntimeException("Source binding must the Trigger Binding as well");
    }
    final BindPathSnooper delegate = new BindPathSnooper();
    try {
        // create our own local copy of the closure
        final Class closureClass = closure.getClass();
        // do in privileged block since we may be looking at private stuff
        Closure closureLocalCopy = java.security.AccessController.doPrivileged(new PrivilegedAction<Closure>() {

            public Closure run() {
                // assume closures have only 1 constructor, of the form (Object, Reference*)
                Constructor constructor = closureClass.getConstructors()[0];
                int paramCount = constructor.getParameterTypes().length;
                Object[] args = new Object[paramCount];
                args[0] = delegate;
                for (int i = 1; i < paramCount; i++) {
                    args[i] = new Reference(new BindPathSnooper());
                }
                try {
                    boolean acc = constructor.isAccessible();
                    constructor.setAccessible(true);
                    Closure localCopy = (Closure) constructor.newInstance(args);
                    if (!acc) {
                        constructor.setAccessible(false);
                    }
                    localCopy.setResolveStrategy(Closure.DELEGATE_ONLY);
                    for (Field f : closureClass.getDeclaredFields()) {
                        acc = f.isAccessible();
                        f.setAccessible(true);
                        if (f.getType() == Reference.class) {
                            delegate.fields.put(f.getName(), (BindPathSnooper) ((Reference) f.get(localCopy)).get());
                        }
                        if (!acc) {
                            f.setAccessible(false);
                        }
                    }
                    return localCopy;
                } catch (Exception e) {
                    throw new RuntimeException("Error snooping closure", e);
                }
            }
        });
        try {
            closureLocalCopy.call();
        } catch (DeadEndException e) {
            // we want this exception exposed.
            throw e;
        } catch (Exception e) {
        //LOGME
        // ignore it, likely failing because we are faking out properties
        // such as a call to Math.min(int, BindPathSnooper)
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new RuntimeException("A closure expression binding could not be created because of " + e.getClass().getName() + ":\n\t" + e.getMessage());
    }
    List<BindPath> rootPaths = new ArrayList<BindPath>();
    for (Map.Entry<String, BindPathSnooper> entry : delegate.fields.entrySet()) {
        BindPath bp = createBindPath(entry.getKey(), entry.getValue());
        bp.currentObject = closure;
        rootPaths.add(bp);
    }
    PropertyPathFullBinding fb = new PropertyPathFullBinding();
    fb.setSourceBinding(new ClosureSourceBinding(closure));
    fb.setTargetBinding(target);
    fb.bindPaths = rootPaths.toArray(new BindPath[rootPaths.size()]);
    return fb;
}
Also used : Closure(groovy.lang.Closure) Constructor(java.lang.reflect.Constructor) Reference(groovy.lang.Reference) ArrayList(java.util.ArrayList) Field(java.lang.reflect.Field) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 28 with Field

use of java.lang.reflect.Field in project flink by apache.

the class NettyConnectionManagerTest method testManualConfiguration.

/**
	 * Tests that the number of arenas and threads can be configured manually.
	 */
@Test
public void testManualConfiguration() throws Exception {
    // Expected numbers
    int numberOfArenas = 1;
    int numberOfClientThreads = 3;
    int numberOfServerThreads = 4;
    // Expected number of threads
    Configuration flinkConfig = new Configuration();
    flinkConfig.setInteger(NettyConfig.NUM_ARENAS, numberOfArenas);
    flinkConfig.setInteger(NettyConfig.NUM_THREADS_CLIENT, 3);
    flinkConfig.setInteger(NettyConfig.NUM_THREADS_SERVER, 4);
    NettyConfig config = new NettyConfig(InetAddress.getLocalHost(), NetUtils.getAvailablePort(), 1024, 1337, flinkConfig);
    NettyConnectionManager connectionManager = new NettyConnectionManager(config);
    connectionManager.start(mock(ResultPartitionProvider.class), mock(TaskEventDispatcher.class), mock(NetworkBufferPool.class));
    assertEquals(numberOfArenas, connectionManager.getBufferPool().getNumberOfArenas());
    {
        // Client event loop group
        Bootstrap boostrap = connectionManager.getClient().getBootstrap();
        EventLoopGroup group = boostrap.group();
        Field f = group.getClass().getSuperclass().getSuperclass().getDeclaredField("children");
        f.setAccessible(true);
        Object[] eventExecutors = (Object[]) f.get(group);
        assertEquals(numberOfClientThreads, eventExecutors.length);
    }
    {
        // Server event loop group
        ServerBootstrap bootstrap = connectionManager.getServer().getBootstrap();
        EventLoopGroup group = bootstrap.group();
        Field f = group.getClass().getSuperclass().getSuperclass().getDeclaredField("children");
        f.setAccessible(true);
        Object[] eventExecutors = (Object[]) f.get(group);
        assertEquals(numberOfServerThreads, eventExecutors.length);
    }
    {
        // Server child event loop group
        ServerBootstrap bootstrap = connectionManager.getServer().getBootstrap();
        EventLoopGroup group = bootstrap.childGroup();
        Field f = group.getClass().getSuperclass().getSuperclass().getDeclaredField("children");
        f.setAccessible(true);
        Object[] eventExecutors = (Object[]) f.get(group);
        assertEquals(numberOfServerThreads, eventExecutors.length);
    }
}
Also used : Field(java.lang.reflect.Field) EventLoopGroup(io.netty.channel.EventLoopGroup) Configuration(org.apache.flink.configuration.Configuration) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ResultPartitionProvider(org.apache.flink.runtime.io.network.partition.ResultPartitionProvider) TaskEventDispatcher(org.apache.flink.runtime.io.network.TaskEventDispatcher) NetworkBufferPool(org.apache.flink.runtime.io.network.buffer.NetworkBufferPool) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Test(org.junit.Test)

Example 29 with Field

use of java.lang.reflect.Field in project flink by apache.

the class NettyConnectionManagerTest method testMatchingNumberOfArenasAndThreadsAsDefault.

/**
	 * Tests that the number of arenas and number of threads of the client and
	 * server are set to the same number, that is the number of configured
	 * task slots.
	 */
@Test
public void testMatchingNumberOfArenasAndThreadsAsDefault() throws Exception {
    // Expected number of arenas and threads
    int numberOfSlots = 2;
    NettyConfig config = new NettyConfig(InetAddress.getLocalHost(), NetUtils.getAvailablePort(), 1024, numberOfSlots, new Configuration());
    NettyConnectionManager connectionManager = new NettyConnectionManager(config);
    connectionManager.start(mock(ResultPartitionProvider.class), mock(TaskEventDispatcher.class), mock(NetworkBufferPool.class));
    assertEquals(numberOfSlots, connectionManager.getBufferPool().getNumberOfArenas());
    {
        // Client event loop group
        Bootstrap boostrap = connectionManager.getClient().getBootstrap();
        EventLoopGroup group = boostrap.group();
        Field f = group.getClass().getSuperclass().getSuperclass().getDeclaredField("children");
        f.setAccessible(true);
        Object[] eventExecutors = (Object[]) f.get(group);
        assertEquals(numberOfSlots, eventExecutors.length);
    }
    {
        // Server event loop group
        ServerBootstrap bootstrap = connectionManager.getServer().getBootstrap();
        EventLoopGroup group = bootstrap.group();
        Field f = group.getClass().getSuperclass().getSuperclass().getDeclaredField("children");
        f.setAccessible(true);
        Object[] eventExecutors = (Object[]) f.get(group);
        assertEquals(numberOfSlots, eventExecutors.length);
    }
    {
        // Server child event loop group
        ServerBootstrap bootstrap = connectionManager.getServer().getBootstrap();
        EventLoopGroup group = bootstrap.childGroup();
        Field f = group.getClass().getSuperclass().getSuperclass().getDeclaredField("children");
        f.setAccessible(true);
        Object[] eventExecutors = (Object[]) f.get(group);
        assertEquals(numberOfSlots, eventExecutors.length);
    }
}
Also used : Field(java.lang.reflect.Field) EventLoopGroup(io.netty.channel.EventLoopGroup) Configuration(org.apache.flink.configuration.Configuration) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ResultPartitionProvider(org.apache.flink.runtime.io.network.partition.ResultPartitionProvider) TaskEventDispatcher(org.apache.flink.runtime.io.network.TaskEventDispatcher) NetworkBufferPool(org.apache.flink.runtime.io.network.buffer.NetworkBufferPool) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Test(org.junit.Test)

Example 30 with Field

use of java.lang.reflect.Field in project flink by apache.

the class TaskStopTest method doMocking.

public void doMocking(AbstractInvokable taskMock) throws Exception {
    TaskInfo taskInfoMock = mock(TaskInfo.class);
    when(taskInfoMock.getTaskNameWithSubtasks()).thenReturn("dummyName");
    TaskManagerRuntimeInfo tmRuntimeInfo = mock(TaskManagerRuntimeInfo.class);
    when(tmRuntimeInfo.getConfiguration()).thenReturn(new Configuration());
    task = new Task(mock(JobInformation.class), new TaskInformation(new JobVertexID(), "test task name", 1, 1, "foobar", new Configuration()), mock(ExecutionAttemptID.class), mock(AllocationID.class), 0, 0, Collections.<ResultPartitionDeploymentDescriptor>emptyList(), Collections.<InputGateDeploymentDescriptor>emptyList(), 0, mock(TaskStateHandles.class), mock(MemoryManager.class), mock(IOManager.class), mock(NetworkEnvironment.class), mock(BroadcastVariableManager.class), mock(TaskManagerActions.class), mock(InputSplitProvider.class), mock(CheckpointResponder.class), mock(LibraryCacheManager.class), mock(FileCache.class), tmRuntimeInfo, mock(TaskMetricGroup.class), mock(ResultPartitionConsumableNotifier.class), mock(PartitionProducerStateChecker.class), mock(Executor.class));
    Field f = task.getClass().getDeclaredField("invokable");
    f.setAccessible(true);
    f.set(task, taskMock);
    Field f2 = task.getClass().getDeclaredField("executionState");
    f2.setAccessible(true);
    f2.set(task, ExecutionState.RUNNING);
}
Also used : TaskInfo(org.apache.flink.api.common.TaskInfo) Field(java.lang.reflect.Field) StoppableTask(org.apache.flink.runtime.jobgraph.tasks.StoppableTask) TaskInformation(org.apache.flink.runtime.executiongraph.TaskInformation) ResultPartitionDeploymentDescriptor(org.apache.flink.runtime.deployment.ResultPartitionDeploymentDescriptor) Configuration(org.apache.flink.configuration.Configuration) JobVertexID(org.apache.flink.runtime.jobgraph.JobVertexID) InputGateDeploymentDescriptor(org.apache.flink.runtime.deployment.InputGateDeploymentDescriptor)

Aggregations

Field (java.lang.reflect.Field)4517 Method (java.lang.reflect.Method)500 Test (org.junit.Test)475 ArrayList (java.util.ArrayList)434 IOException (java.io.IOException)276 HashMap (java.util.HashMap)263 Map (java.util.Map)253 List (java.util.List)146 InvocationTargetException (java.lang.reflect.InvocationTargetException)136 Pattern (java.util.regex.Pattern)121 Matcher (java.util.regex.Matcher)115 File (java.io.File)93 HashSet (java.util.HashSet)91 Support_Field (tests.support.Support_Field)82 Annotation (java.lang.annotation.Annotation)77 Collection (java.util.Collection)70 SienaException (siena.SienaException)65 Test (org.testng.annotations.Test)64 Before (org.junit.Before)61 Type (java.lang.reflect.Type)57