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:org.opendaylight.nemo.renderer.cli.physicalnetwork.PhysicalResourceLoaderTest.java

@Test
public void testBuildLinks() throws Exception {
    List<PhysicalLink> list;
    Class<PhysicalResourceLoader> class1 = PhysicalResourceLoader.class;
    Method method = class1.getDeclaredMethod("buildLinks", new Class[] { JsonNode.class });
    method.setAccessible(true);

    JsonNode linksRoot = mock(JsonNode.class);
    JsonNode links = mock(JsonNode.class);
    JsonNode link = mock(JsonNode.class);
    JsonNode link_temp_buildlink = mock(JsonNode.class);

    when(linksRoot.path(any(String.class))).thenReturn(links);
    when(links.size()).thenReturn(1);/*from   ww w  .  j a  va  2  s .co m*/
    when(links.get(any(Integer.class))).thenReturn(link);
    //get into method "build link" args(link)
    when(link.get(any(String.class))).thenReturn(link_temp_buildlink);
    when(link_temp_buildlink.asText()).thenReturn(new String("1"))//new PhysicalLinkId(strLinkId)
            .thenReturn(new String("2"))//new PhysicalNodeId
            .thenReturn(new String("3"))//new PhysicalPortId
            .thenReturn(new String("4"))//new PhysicalNodeId
            .thenReturn(new String("5"))//new PhysicalPortId
            .thenReturn(new String(""));//linkNode.get("link-bandwidth").asText().equals("")
    when(link_temp_buildlink.asLong()).thenReturn((long) 1);

    list = (List<PhysicalLink>) method.invoke(physicalResourceLoader, linksRoot);
    Assert.assertTrue(list.size() == 1);
    verify(link_temp_buildlink, times(6)).asText();
}

From source file:co.cask.cdap.filetailer.FileTailerIT.java

private void mockMetricsProcessor(PipeManager manager) throws IOException, NoSuchMethodException,
        InvocationTargetException, IllegalAccessException, NoSuchFieldException {
    List<Pipe> pipeList = new ArrayList<Pipe>();
    StreamClient client = null;//from   w w  w .j  a v a2s.  com
    StreamWriter writer = null;
    try {
        Method method1 = manager.getClass().getDeclaredMethod("getPipeConfigs");
        method1.setAccessible(true);
        List<PipeConfiguration> pipeConfList = (List<PipeConfiguration>) method1.invoke(manager);
        for (PipeConfiguration pipeConf : pipeConfList) {
            FileTailerQueue queue = new FileTailerQueue(pipeConf.getQueueSize());
            client = pipeConf.getSinkConfiguration().getStreamClient();
            String streamName = pipeConf.getSinkConfiguration().getStreamName();
            Method method2 = manager.getClass().getDeclaredMethod("getStreamWriterForPipe", StreamClient.class,
                    String.class);
            method2.setAccessible(true);
            writer = (StreamWriter) method2.invoke(manager, client, streamName);
            FileTailerStateProcessor stateProcessor = new FileTailerStateProcessorImpl(pipeConf.getDaemonDir(),
                    pipeConf.getStateFile());
            FileTailerMetricsProcessor metricsProcessor = new FileTailerMetricsProcessor(
                    pipeConf.getDaemonDir(), pipeConf.getStatisticsFile(),
                    pipeConf.getStatisticsSleepInterval(), pipeConf.getPipeName(),
                    pipeConf.getSourceConfiguration().getFileName()) {

                @Override
                public void onReadEventMetric(int eventSize) {
                    super.onReadEventMetric(eventSize);
                    read.incrementAndGet();
                }

                @Override
                public void onIngestEventMetric(int latency) {
                    super.onIngestEventMetric(latency);
                    ingest.incrementAndGet();
                }
            };
            pipeList.add(new Pipe(new LogTailer(pipeConf, queue, stateProcessor, metricsProcessor, null),
                    new FileTailerSink(queue, writer, SinkStrategy.LOADBALANCE, stateProcessor,
                            metricsProcessor, null, pipeConf.getSinkConfiguration().getPackSize()),
                    metricsProcessor));
            client = null;
            writer = null;
        }
        Field field = manager.getClass().getDeclaredField("serviceManager");
        field.setAccessible(true);

        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

        field.set(manager, new ServiceManager(pipeList));
    } finally {
        if (client != null) {
            client.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:com.hp.mqm.clt.CliParserTest.java

@Test
public void testArgs_tagFormat()
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ParseException {
    CliParser cliParser = new CliParser();
    Method argsValidation = cliParser.getClass().getDeclaredMethod("areCmdArgsValid", CommandLine.class);
    argsValidation.setAccessible(true);
    CommandLineParser parser = new DefaultParser();

    CommandLine cmdArgs = parser.parse(options, new String[] { "-t", "OS:Linux", "test.xml" });
    Boolean result = (Boolean) argsValidation.invoke(cliParser, cmdArgs);
    Assert.assertTrue(result);//from  www  . j  a  va  2 s  .  c  om

    cmdArgs = parser.parse(options, new String[] { "-t", "OS:", "test.xml" });
    result = (Boolean) argsValidation.invoke(cliParser, cmdArgs);
    Assert.assertFalse(result);

    cmdArgs = parser.parse(options, new String[] { "-f", "OS::Linux", "test.xml" });
    result = (Boolean) argsValidation.invoke(cliParser, cmdArgs);
    Assert.assertFalse(result);

    cmdArgs = parser.parse(options, new String[] { "-f", ":", "test.xml" });
    result = (Boolean) argsValidation.invoke(cliParser, cmdArgs);
    Assert.assertFalse(result);
}

From source file:org.opendaylight.nemo.renderer.cli.physicalnetwork.PhysicalResourceLoaderTest.java

@Test
public void testBuildHosts() throws Exception {
    Class<PhysicalResourceLoader> class1 = PhysicalResourceLoader.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);//www. j  av  a  2  s .  co  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(physicalResourceLoader, hostsNode);
    Assert.assertTrue(list.size() == 1);
}

From source file:org.opendaylight.nemo.renderer.cli.physicalnetwork.PhysicalResourceLoaderTest.java

@Test
public void testBuildPortAttributes() throws Exception {
    Class<PhysicalResourceLoader> class1 = PhysicalResourceLoader.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(physicalResourceLoader, attributes);
    Assert.assertTrue(attributeList.size() == 0);
    //new AttributeName("zm");
    attributeList = (List<Attribute>) method.invoke(physicalResourceLoader, attributes);
    Assert.assertTrue(attributeList.size() == 1);
    verify(portAttribute, times(3)).path(any(String.class));
    verify(jsonNode_temp, times(3)).asText();
}

From source file:com.hp.mqm.clt.CliParserTest.java

@Test
public void testArgs_settingsValidation()
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ParseException {
    CliParser cliParser = new CliParser();
    Method settingsValidation = cliParser.getClass().getDeclaredMethod("areSettingsValid", Settings.class);
    settingsValidation.setAccessible(true);
    Settings settings = new Settings();

    Boolean result = (Boolean) settingsValidation.invoke(cliParser, settings);
    Assert.assertFalse(result);/*from  w  w w  .  j  a  v a2s . c  om*/

    settings.setServer("http://test.hp.com:8080");
    result = (Boolean) settingsValidation.invoke(cliParser, settings);
    Assert.assertFalse(result);

    settings.setSharedspace(1001);
    result = (Boolean) settingsValidation.invoke(cliParser, settings);
    Assert.assertFalse(result);

    settings.setWorkspace(1002);
    result = (Boolean) settingsValidation.invoke(cliParser, settings);
    Assert.assertTrue(result);
}

From source file:com.netflix.hystrix.contrib.javanica.command.AbstractHystrixCommandFactory.java

CommandAction createFallbackAction(MetaHolder metaHolder,
        Collection<HystrixCollapser.CollapsedRequest<Object, Object>> collapsedRequests) {
    String fallbackMethodName = metaHolder.getHystrixCommand().fallbackMethod();
    CommandAction fallbackAction = null;
    if (StringUtils.isNotEmpty(fallbackMethodName)) {
        try {/* w w  w. j a v  a2s .c  o  m*/
            Method fallbackMethod = metaHolder.getObj().getClass().getDeclaredMethod(fallbackMethodName,
                    metaHolder.getParameterTypes());
            if (fallbackMethod.isAnnotationPresent(HystrixCommand.class)) {
                fallbackMethod.setAccessible(true);
                MetaHolder fmMetaHolder = MetaHolder.builder().obj(metaHolder.getObj()).method(fallbackMethod)
                        .args(metaHolder.getArgs()).defaultCollapserKey(metaHolder.getDefaultCollapserKey())
                        .defaultCommandKey(fallbackMethod.getName())
                        .defaultGroupKey(metaHolder.getDefaultGroupKey())
                        .hystrixCollapser(metaHolder.getHystrixCollapser())
                        .hystrixCommand(fallbackMethod.getAnnotation(HystrixCommand.class)).build();
                fallbackAction = new LazyCommandExecutionAction(GenericHystrixCommandFactory.getInstance(),
                        fmMetaHolder, collapsedRequests);
            } else {
                fallbackAction = new MethodExecutionAction(metaHolder.getObj(), fallbackMethod,
                        metaHolder.getArgs());
            }
        } catch (NoSuchMethodException e) {
            throw Throwables.propagate(e);
        }
    }
    return fallbackAction;
}

From source file:net.jselby.pc.bukkit.BukkitLoader.java

@SuppressWarnings("unchecked")
public void loadPlugin(File file)
        throws ZipException, IOException, InvalidPluginException, InvalidDescriptionException {
    if (file.getName().endsWith(".jar")) {
        JarFile jarFile = new JarFile(file);

        URL[] urls = { new URL("jar:file:" + file + "!/") };
        URLClassLoader cl = URLClassLoader.newInstance(urls);

        ZipEntry bukkit = jarFile.getEntry("plugin.yml");
        String bukkitClass = "";
        PluginDescriptionFile reader = null;
        if (bukkit != null) {
            reader = new PluginDescriptionFile(new InputStreamReader(jarFile.getInputStream(bukkit)));
            bukkitClass = reader.getMain();
            System.out.println("Loading plugin " + reader.getName() + "...");
        }//w w  w  .  j  a va  2 s . c  o  m

        jarFile.close();

        try {
            //addToClasspath(file);
            JavaPluginLoader pluginLoader = new JavaPluginLoader(PoweredCube.getInstance().getBukkitServer());
            Plugin plugin = pluginLoader.loadPlugin(file);
            Class<JavaPlugin> pluginClass = (Class<JavaPlugin>) plugin.getClass().getSuperclass();
            for (Method method : pluginClass.getDeclaredMethods()) {
                if (method.getName().equalsIgnoreCase("init")
                        || method.getName().equalsIgnoreCase("initialize")) {
                    method.setAccessible(true);
                    method.invoke(plugin, null, PoweredCube.getInstance().getBukkitServer(), reader,
                            new File("plugins" + File.separator + reader.getName()), file, cl);
                }
            }

            // Load the plugin, using its default methods
            BukkitPluginManager mgr = (BukkitPluginManager) Bukkit.getPluginManager();
            mgr.registerPlugin((JavaPlugin) plugin);
            plugin.onLoad();
            plugin.onEnable();
        } catch (Exception e1) {
            e1.printStackTrace();
        } catch (Error e1) {
            e1.printStackTrace();
        }

        jarFile.close();
    }
}

From source file:net.groupbuy.service.impl.BaseServiceImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void copyProperties(Object source, Object target, String[] ignoreProperties) throws BeansException {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(target.getClass());
    List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null
                && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
            PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(),
                    targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }//from  w  ww  . j  a  va 2s  .  co m
                    Object sourceValue = readMethod.invoke(source);
                    Object targetValue = readMethod.invoke(target);
                    if (sourceValue != null && targetValue != null && targetValue instanceof Collection) {
                        Collection collection = (Collection) targetValue;
                        collection.clear();
                        collection.addAll((Collection) sourceValue);
                    } else {
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, sourceValue);
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}

From source file:com.app.test.mail.DefaultMailSenderTest.java

@Before
public void setUp() throws Exception {
    setUpProperties();//from ww  w  . j a  v  a 2  s .  c  o  m

    _clazz = Class.forName(DefaultMailSender.class.getName());

    _classInstance = _clazz.newInstance();

    Method _authenticateOutboundEmailAddressMethod = _clazz
            .getDeclaredMethod("_authenticateOutboundEmailAddress");

    _authenticateOutboundEmailAddressMethod.setAccessible(true);

    _session = (Session) _authenticateOutboundEmailAddressMethod.invoke(_classInstance);
}