Example usage for java.lang.reflect Method setAccessible

List of usage examples for java.lang.reflect Method setAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Method setAccessible.

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Usage

From source file:com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolderTest.java

@Test
public void testGetAllAnnotationValuesWrongArg() throws ReflectiveOperationException {
    SuppressWarningsHolder holder = new SuppressWarningsHolder();
    Method getAllAnnotationValues = holder.getClass().getDeclaredMethod("getAllAnnotationValues",
            DetailAST.class);
    getAllAnnotationValues.setAccessible(true);

    DetailAST methodDef = new DetailAST();
    methodDef.setType(TokenTypes.METHOD_DEF);
    methodDef.setText("Method Def");
    methodDef.setLineNo(0);/*from   ww  w.j av  a 2 s .c o m*/
    methodDef.setColumnNo(0);

    DetailAST lparen = new DetailAST();
    lparen.setType(TokenTypes.LPAREN);

    DetailAST parent = new DetailAST();
    parent.addChild(lparen);
    parent.addChild(methodDef);

    try {
        getAllAnnotationValues.invoke(holder, parent);
        fail("Exception expected");
    } catch (InvocationTargetException ex) {
        assertTrue(ex.getCause() instanceof IllegalArgumentException);
        assertEquals("Unexpected AST: Method Def[0x0]", ex.getCause().getMessage());
    }
}

From source file:com.shazam.dataengineering.pipelinebuilder.DeploymentActionTest.java

@Test
@WithoutJenkins//from ww  w  .j a v  a 2s . com
public void removeOldPipelineShouldGenerateInfoMessagesForSuccess() throws Exception {
    DataPipelineClient dataPipelineClient = mock(DataPipelineClient.class);
    DeploymentAction action = new DeploymentAction(getMockAbstractBuild(), new HashMap<S3Environment, String>(),
            new AnonymousAWSCredentials());
    DeletePipelineRequest request = new DeletePipelineRequest().withPipelineId("test");

    Field pipelineIdField = action.getClass().getDeclaredField("pipelineToRemoveId");
    pipelineIdField.setAccessible(true);
    pipelineIdField.set(action, "test");
    Method method = action.getClass().getDeclaredMethod("removeOldPipeline", DataPipelineClient.class);
    method.setAccessible(true);

    method.invoke(action, dataPipelineClient);
    verify(dataPipelineClient).deletePipeline(request);
    assertTrue(action.getClientMessages().get(0).contains("[INFO]"));
    assertFalse(action.getClientMessages().get(0).contains("[WARN]"));
}

From source file:com.shazam.dataengineering.pipelinebuilder.DeploymentActionTest.java

@Test
@WithoutJenkins//from   w w w. jav a  2 s  .c  o m
public void createNewPipelineShouldReturnPipelineId() throws Exception {
    DataPipelineClient dataPipelineClient = mock(DataPipelineClient.class);
    DeploymentAction action = new DeploymentAction(getMockAbstractBuild(), new HashMap<S3Environment, String>(),
            new AnonymousAWSCredentials());
    CreatePipelineResult createPipelineResult = new CreatePipelineResult().withPipelineId("test12345");
    when(dataPipelineClient.createPipeline(any(CreatePipelineRequest.class))).thenReturn(createPipelineResult);

    Field pipelineFileField = action.getClass().getDeclaredField("pipelineFile");
    pipelineFileField.setAccessible(true);
    pipelineFileField.set(action, "p1-test-pipeline-name-34.json");
    Method method = action.getClass().getDeclaredMethod("createNewPipeline", DataPipelineClient.class);
    method.setAccessible(true);

    String result = (String) method.invoke(action, dataPipelineClient);

    assertEquals("test12345", result);
}

From source file:org.carewebframework.ui.test.MockEnvironment.java

/**
 * Makes ZK believe the current thread is an event thread.
 * //from  ww w .j  ava 2 s .c o m
 * @param value If true, the current thread becomes an event thread. If false, it is not an
 *            event thread.
 * @throws Exception Unspecified exception.
 */
public void inEventListener(boolean value) throws Exception {
    Method inEventListener = BeanUtils.findMethod(EventProcessor.class, "inEventListener", boolean.class);
    inEventListener.setAccessible(true);
    inEventListener.invoke(null, value);
}

From source file:org.opendaylight.nemo.renderer.openflow.physicalnetwork.PhyConfigLoaderTest.java

public void testBuildPortAttributes() throws Exception {
    Class<PhyConfigLoader> class1 = PhyConfigLoader.class;
    Method method = class1.getDeclaredMethod("buildPortAttributes", new Class[] { JsonNode.class });
    method.setAccessible(true);

    List<Attribute> attributeList;
    JsonNode attributes = mock(JsonNode.class);
    JsonNode portAttribute = mock(JsonNode.class);
    JsonNode jsonNode_temp = mock(JsonNode.class);

    when(attributes.size()).thenReturn(1);
    when(attributes.get(any(Integer.class))).thenReturn(portAttribute);
    //get into method "buildPortAttribute"
    when(portAttribute.path(any(String.class))).thenReturn(jsonNode_temp);
    when(jsonNode_temp.asText()).thenReturn(new String(""))//branch null
            .thenReturn(new String("zm"));
    attributeList = (List<Attribute>) method.invoke(phyConfigLoader, attributes);
    Assert.assertTrue(attributeList.size() == 0);
    //new AttributeName("zm");
    attributeList = (List<Attribute>) method.invoke(phyConfigLoader, attributes);
    Assert.assertTrue(attributeList.size() == 1);
    verify(portAttribute, times(3)).path(any(String.class));
    verify(jsonNode_temp, times(3)).asText();
}

From source file:org.opendaylight.nemo.renderer.openflow.physicalnetwork.PhyConfigLoaderTest.java

@Test
public void testBuildExternals() throws Exception {
    JsonNode externalRoot = mock(JsonNode.class);
    JsonNode exNetworkNodes = mock(JsonNode.class);
    JsonNode exNetworkNode = mock(JsonNode.class);
    JsonNode jsonNode = mock(JsonNode.class);
    String nodeId = new String("1");
    String portId = new String("2");
    String peerMac = new String("00:11:22:33:44:55");

    Class<PhyConfigLoader> class1 = PhyConfigLoader.class;
    Method method = class1.getDeclaredMethod("buildExternals", new Class[] { JsonNode.class });
    method.setAccessible(true);

    when(externalRoot.path(any(String.class))).thenReturn(exNetworkNodes);
    when(exNetworkNodes.size()).thenReturn(1);
    when(exNetworkNodes.get(any(Integer.class))).thenReturn(exNetworkNode);

    //get into method "buildExNetwork"
    when(exNetworkNode.get(any(String.class))).thenReturn(jsonNode);
    when(jsonNode.asText()).thenReturn(nodeId).thenReturn(portId).thenReturn(peerMac);

    method.invoke(phyConfigLoader, externalRoot);

    verify(externalRoot).path(any(String.class));
    verify(exNetworkNodes, times(2)).size();
    verify(exNetworkNodes).get(any(Integer.class));
    verify(exNetworkNode, times(3)).get(any(String.class));
    verify(jsonNode, times(3)).asText();
}

From source file:org.opendaylight.nemo.renderer.openflow.physicalnetwork.PhyConfigLoaderTest.java

@Test
public void testBuildHosts() throws Exception {
    Class<PhyConfigLoader> class1 = PhyConfigLoader.class;
    Method method = class1.getDeclaredMethod("buildHosts", new Class[] { JsonNode.class });
    method.setAccessible(true);

    JsonNode hostsNode = mock(JsonNode.class);
    JsonNode hosts = mock(JsonNode.class);
    JsonNode host = mock(JsonNode.class);
    JsonNode host_temp = mock(JsonNode.class);
    JsonNode host_temp1 = mock(JsonNode.class);
    JsonNode ipaddrs = mock(JsonNode.class);
    JsonNode ipaddr = mock(JsonNode.class);
    List<PhysicalHost> list;

    when(hostsNode.path(any(String.class))).thenReturn(hosts);
    when(hosts.size()).thenReturn(1);//from   w ww.j  a va  2 s.c o  m
    when(hosts.get(any(Integer.class))).thenReturn(host);
    //get into method "buildhost"
    when(host.get(any(String.class))).thenReturn(host_temp);
    when(host_temp.asText()).thenReturn(new String("00001111-0000-0000-0000-000011112222")) //HOST_ID
            .thenReturn(new String("hostName")) //HOST_NAME
            .thenReturn(new String("00:11:22:33:44:55")) //MAC_ADDRESS
            .thenReturn(new String("nodeId")) //NODE_ID
            .thenReturn(new String("connetionId"));//PhysicalPortId
    when(host.path(any(String.class))).thenReturn(ipaddrs);
    when(ipaddrs.size()).thenReturn(1);
    when(ipaddrs.get(any(Integer.class))).thenReturn(ipaddr);
    when(ipaddr.get(any(String.class))).thenReturn(host_temp1);
    when(host_temp1.asText()).thenReturn(new String("192.168.1.1"));//ipv4_address

    list = (List<PhysicalHost>) method.invoke(phyConfigLoader, hostsNode);
    Assert.assertTrue(list.size() == 1);
}

From source file:au.org.ala.delta.editor.directives.ExportControllerTest.java

public DeltaEditorTestHelper createTestHelper() throws Exception {

    DeltaEditorTestHelper helper = new DeltaEditorTestHelper();
    ApplicationContext context = helper.getContext();
    context.setApplicationClass(DeltaEditor.class);
    Method method = ApplicationContext.class.getDeclaredMethod("setApplication", Application.class);
    method.setAccessible(true);
    method.invoke(context, helper);/*from w w w .  ja v  a 2  s .  co m*/

    return helper;
}

From source file:it.geosolutions.geobatch.annotations.GenericActionService.java

/**
 * The canCreateAction method lookup for a checkConfiguration annotated method and invoke it, the result of that method will be returned to the caller.
 * If no annotated method will be found the result returned will be forced to TRUE (but log a message under WARN level)
 * If an exception occurrs during the method invocation the result will be forced to FALSE
 * Please note that it executes (or try to executes) just the first method found. So annotate more than one method per class does not make sense. 
 * @param actionConfig/*  w ww  .j a  v  a  2  s .  c o m*/
 * @return
 */
public boolean checkConfiguration(ActionConfiguration actionConfig) {
    Boolean isConfigurationOk = true;
    Method el = null;
    for (Method method : actionType.getDeclaredMethods()) {
        if (method.isAnnotationPresent(CheckConfiguration.class)) {
            el = method;
            break;
        }
    }
    if (el != null) {
        el.setAccessible(true);
        StringBuilder sb = new StringBuilder();
        sb.append("Found a @CheckConfiguration annotated method called: ").append(el.getName());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(sb.toString());
        }
        try {
            isConfigurationOk = (Boolean) el.invoke(
                    actionType.getDeclaredConstructor(actionConfig.getClass()).newInstance(actionConfig));
        } catch (Exception e) {
            if (LOGGER.isWarnEnabled()) {
                StringBuilder sb2 = new StringBuilder();
                sb2.append("An exception has occurred while invoking the CheckConfiguration").append(
                        ". The result will be forced to false, please check and fix this abnormal situation. ");
                if (e.getMessage() != null)
                    sb2.append(e.getMessage());
                LOGGER.warn(sb2.toString(), e);
            }
            isConfigurationOk = false;
        }
    }
    return isConfigurationOk;
}

From source file:io.neba.core.logviewer.LogfileViewerConsolePluginTest.java

private void invokeDestroy(Servlet servlet)
        throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
    Method method = servlet.getClass().getMethod("destroy");
    method.setAccessible(true);
    method.invoke(servlet);//from   w  w w .j a v  a 2  s .  c o  m
}