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:io.neba.core.logviewer.LogfileViewerConsolePluginTest.java

private void invokeInit(Servlet servlet, ServletConfig config)
        throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
    Method method = servlet.getClass().getMethod("init", ServletConfig.class);
    method.setAccessible(true);
    method.invoke(servlet, config);//  w w  w . j ava  2  s.  co  m
}

From source file:de.matzefratze123.heavyspleef.core.flag.FlagRegistry.java

public void flushAndExecuteInitMethods() {
    while (!queuedInitMethods.isEmpty()) {
        Method method = queuedInitMethods.poll();

        boolean accessible = method.isAccessible();
        if (!accessible) {
            method.setAccessible(true);
        }/*from   w w  w  . j a  v a 2  s  .c  o m*/

        Class<?>[] parameters = method.getParameterTypes();
        Object[] args = new Object[parameters.length];

        for (int i = 0; i < parameters.length; i++) {
            Class<?> parameter = parameters[i];
            if (parameter == HeavySpleef.class) {
                args[i] = heavySpleef;
            }
        }

        try {
            method.invoke(null, args);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new IllegalArgumentException("Could not invoke flag initialization method " + method.getName()
                    + " of type " + method.getDeclaringClass().getCanonicalName() + ": ", e);
        } finally {
            method.setAccessible(accessible);
        }
    }
}

From source file:com.github.ekumen.rosjava_actionlib.ActionClient.java

/**
 * Convenience method for setting the goal ID of an action goal message.
 * @param goal The action goal message to set the goal ID for.
 * @param gid The goal ID object.//w w w .  ja v a 2  s .co  m
 * @see actionlib_msgs.GoalID
 */
public void setGoalId(T_ACTION_GOAL goal, GoalID gid) {
    try {
        Method m = goal.getClass().getMethod("setGoalId", GoalID.class);
        m.setAccessible(true); // workaround for known bug http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6924232
        m.invoke(goal, gid);
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}

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

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

    JsonNode nodesRoot = mock(JsonNode.class);
    JsonNode nodes = mock(JsonNode.class);
    JsonNode node = mock(JsonNode.class);
    JsonNode node_temp = mock(JsonNode.class);
    JsonNode port_temp = mock(JsonNode.class);
    JsonNode attribute_temp = mock(JsonNode.class);
    JsonNode attribute_temp_son = mock(JsonNode.class);
    JsonNode ports = mock(JsonNode.class);
    JsonNode attributes = mock(JsonNode.class);
    JsonNode portAttributes = mock(JsonNode.class);
    JsonNode portAttribute = mock(JsonNode.class);
    JsonNode attributes_son = mock(JsonNode.class);
    JsonNode port = mock(JsonNode.class);
    List<PhysicalNode> result;

    when(nodesRoot.path(any(String.class))).thenReturn(nodes);
    when(nodes.size()).thenReturn(1);// w ww  .j a v a  2 s .  c  om
    when(nodes.get(any(Integer.class))).thenReturn(node);
    //get into method "buildnode"
    when(node.get(any(String.class))).thenReturn(node_temp);
    when(node_temp.asText()).thenReturn(new String(""))//branch null
            .thenReturn(new String("test")) //node_id
            .thenReturn(new String("switch")); //NODE_TYPE

    result = (List<PhysicalNode>) method.invoke(phyConfigLoader, nodesRoot); //return empty list
    Assert.assertTrue(result.size() == 0);
    verify(node_temp).asText();

    when(node.path(any(String.class))).thenReturn(ports)//PORTS
            .thenReturn(attributes);//ATTRIBUTES
    ////get into method "buildports"
    when(ports.size()).thenReturn(1);
    when(ports.get(any(Integer.class))).thenReturn(port);
    ///////get into method "buildport"
    when(port.get(any(String.class))).thenReturn(port_temp);
    when(port_temp.asText()).thenReturn(new String("test"))//PORT_ID
            .thenReturn(new String("switch"));//PORT_TYPE
    when(port.path(any(String.class))).thenReturn(portAttributes);
    ////////get into method "buildportattributes"
    when(portAttributes.size()).thenReturn(1);
    when(portAttributes.get(any(Integer.class))).thenReturn(attributes_son);
    //////////get into method "buildPortAttribute"
    when(attributes_son.path(any(String.class))).thenReturn(attribute_temp_son);
    when(attribute_temp_son.asText()).thenReturn(new String("zm")).thenReturn(new String("zm"));
    ////return to method "buildnode" and get into method "..............buildNodeAttributes"
    when(attributes.size()).thenReturn(1);
    when(attributes.get(any(Integer.class))).thenReturn(portAttribute);
    //////get into method "..............buildNodeAttribute"
    when(portAttribute.path(any(String.class))).thenReturn(attribute_temp);
    when(attribute_temp.asText()).thenReturn(new String("test"))//ATTRIBUTE_NAME
            .thenReturn(new String("test"));//ATTRIBUTE_VALUE

    result = (List<PhysicalNode>) method.invoke(phyConfigLoader, nodesRoot); //return empty list
    Assert.assertTrue(result.size() == 1);

}

From source file:com.amazonaws.services.kinesis.io.ObjectExtractor.java

/**
 * Create an Object Extractor using indicated serialisation for the class.
 * /*from w ww . j av a2 s.c  o m*/
 * @param aggregateLabelMethod The method to be used as the label for
 *        aggregation.
 * @param clazz The base class used for deserialisation and accessed using
 *        configured accessor methods.
 * @param serialiser Instance of an ITransformer which converts between the
 *        binary Kinesis format and the required Object format indicated by
 *        the base class.
 */
public ObjectExtractor(List<String> aggregateLabelMethodNames, Class clazz,
        IKinesisSerializer<Object, byte[]> serialiser) throws Exception {
    this.clazz = clazz;

    if (serialiser == null) {
        this.serialiser = new JsonSerializer(clazz);
    } else {
        this.serialiser = serialiser;
    }

    if (aggregateLabelMethodNames == null || aggregateLabelMethodNames.size() == 0) {
        throw new InvalidConfigurationException("Cannot Aggregate an Object without a Label Method");
    } else {
        this.aggregateLabelMethods = aggregateLabelMethodNames;

        for (String s : aggregateLabelMethodNames) {
            Method m = clazz.getDeclaredMethod(s);
            m.setAccessible(true);

            this.aggregateLabelMethodMap.put(s, m);
        }
    }

    LabelSet labels = LabelSet.fromStringKeys(this.aggregateLabelMethods);
    this.aggregateLabelColumn = labels.getName();
}

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

@Test
@WithoutJenkins//from  www .ja  va2s  .co m
public void activateNewPipelineShouldCallActivatePipeline() throws Exception {
    String pipelineId = "test1234";
    ActivatePipelineRequest activateRequest = new ActivatePipelineRequest().withPipelineId(pipelineId);
    ActivatePipelineResult activateResult = new ActivatePipelineResult();
    DataPipelineClient dataPipelineClient = mock(DataPipelineClient.class);
    when(dataPipelineClient.activatePipeline(activateRequest)).thenReturn(activateResult);

    DeploymentAction action = new DeploymentAction(getMockAbstractBuild(), new HashMap<S3Environment, String>(),
            new AnonymousAWSCredentials());

    Method method = action.getClass().getDeclaredMethod("activateNewPipeline", String.class,
            DataPipelineClient.class);
    method.setAccessible(true);

    method.invoke(action, pipelineId, dataPipelineClient);

    verify(dataPipelineClient).activatePipeline(any(ActivatePipelineRequest.class));
}

From source file:com.asakusafw.runtime.stage.output.StageOutputDriver.java

private void setOutputFilePrefix(JobContext localContext, String name) throws IOException {
    assert localContext != null;
    assert name != null;
    try {//from   w w w.ja v  a 2 s  .co  m
        Method method = FileOutputFormat.class.getDeclaredMethod(METHOD_SET_OUTPUT_NAME, JobContext.class,
                String.class);
        method.setAccessible(true);
        method.invoke(null, localContext, name);
    } catch (Exception e) {
        throw new IOException(MessageFormat.format(
                "Failed to configure output name of \"{0}\" ([MAPREDUCE-370] may be not applied)", name), e);
    }
}

From source file:com.amazonaws.services.kinesis.io.ObjectExtractor.java

/**
 * {@inheritDoc}//from  w w  w  .j  a  v a2  s. c  o m
 */
@Override
public void validate() throws Exception {
    if (!validated) {
        // validate sum config
        if ((this.aggregatorType.equals(AggregatorType.SUM)) && this.sumValueMap == null) {
            throw new Exception("Summary Aggregators require both a Label Field and a Value Field Set");
        }

        if (this.aggregatorType.equals(AggregatorType.SUM)) {
            for (String s : this.sumValueMap.keySet()) {
                try {
                    Method m = clazz.getDeclaredMethod(s);
                    m.setAccessible(true);
                    this.sumValueMap.put(s, m);
                } catch (NoSuchMethodException e) {
                    LOG.error(e);
                    throw e;
                }
            }
        }

        LOG.info(String.format("Object Extractor Configuration\n" + "Class: %s\n" + "Date Method: %s\n",
                this.clazz.getSimpleName(), this.dateMethodName));

        validated = true;
    }
}

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

@Test
@WithoutJenkins//ww  w .  j a  v  a2  s .co m
public void uploadNewPipelineShouldCallPutPipeline() throws Exception {
    String pipelineId = "test1234";
    ArrayList<com.amazonaws.services.datapipeline.model.PipelineObject> pipelineList = new ArrayList<com.amazonaws.services.datapipeline.model.PipelineObject>();
    PipelineObject pipeline = mock(PipelineObject.class);
    when(pipeline.getAWSObjects()).thenReturn(pipelineList);

    PutPipelineDefinitionRequest putRequest = new PutPipelineDefinitionRequest().withPipelineId(pipelineId)
            .withPipelineObjects(pipelineList);
    PutPipelineDefinitionResult putResult = new PutPipelineDefinitionResult().withErrored(false);
    DataPipelineClient dataPipelineClient = mock(DataPipelineClient.class);
    when(dataPipelineClient.putPipelineDefinition(putRequest)).thenReturn(putResult);

    DeploymentAction action = new DeploymentAction(getMockAbstractBuild(), new HashMap<S3Environment, String>(),
            new AnonymousAWSCredentials());

    Field pipelineFileField = action.getClass().getDeclaredField("pipelineObject");
    pipelineFileField.setAccessible(true);
    pipelineFileField.set(action, pipeline);
    Method method = action.getClass().getDeclaredMethod("uploadNewPipeline", String.class,
            DataPipelineClient.class);
    method.setAccessible(true);

    method.invoke(action, pipelineId, dataPipelineClient);

    verify(pipeline).getAWSObjects();
    verify(dataPipelineClient).putPipelineDefinition(any(PutPipelineDefinitionRequest.class));
}