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.baidu.cc.spring.ConfigCenterPropertyExtractor.java

/**
 * To initialize properties import action from extractor to target configuration
 * center server. importer and extractor should not be null.
 * @throws Exception to throw out all exception to spring container.
 */// w w  w .j  a v a2  s  .  c o m
public void afterPropertiesSet() throws Exception {
    Assert.notNull(importer, "'importer property is null.'");
    Assert.notNull(extractor, "'extractor property is null.'");

    //get configuration items
    Method m = ReflectionUtils.findMethod(PropertyPlaceholderConfigurer.class, "mergeProperties");
    if (m != null) {
        m.setAccessible(true);
        Properties properties = (Properties) ReflectionUtils.invokeMethod(m, extractor);
        if (properties == null) {
            LOGGER.warn("Target extractor get a null property, import will ignore.");
            return;
        }

        Map copied = new HashMap(properties);
        importer.getConfigLoader().importConfigItems(ccVersion, copied);
    }
}

From source file:io.github.bonigarcia.wdm.test.CacheTest.java

@Test
public void testCache() throws Exception {
    BrowserManager browserManager = WebDriverManager.getInstance(driverClass);
    browserManager.architecture(architecture).version(driverVersion).setup();
    Downloader downloader = new Downloader(browserManager);

    Method method = BrowserManager.class.getDeclaredMethod("existsDriverInCache", String.class, String.class,
            Architecture.class);
    method.setAccessible(true);
    String driverInChachePath = (String) method.invoke(browserManager, downloader.getTargetPath(),
            driverVersion, architecture);

    assertThat(driverInChachePath, notNullValue());
}

From source file:hoot.services.nativeInterfaces.ProcessStreamInterfaceTest.java

@Test
@Category(UnitTest.class)
public void testcreateCmd() throws Exception {
    String jobIdStr = java.util.UUID.randomUUID().toString();
    JSONArray args = new JSONArray();
    JSONObject translation = new JSONObject();
    translation.put("translation", "/test/loc/translation.js");
    args.add(translation);//from   www.  ja v  a  2 s . c  o  m

    JSONObject output = new JSONObject();
    output.put("output", "/test/loc/out.osm");
    args.add(output);

    JSONObject input = new JSONObject();
    input.put("input", "/test/loc/input.shp");
    args.add(output);

    JSONObject command = new JSONObject();
    command.put("exectype", "hoot");
    command.put("exec", "ogr2osm");
    command.put("params", args);

    ProcessStreamInterface ps = new ProcessStreamInterface();

    Class[] cArg = new Class[1];
    cArg[0] = JSONObject.class;
    Method method = ProcessStreamInterface.class.getDeclaredMethod("createCmdArray", cArg);
    method.setAccessible(true);
    String[] ret = (String[]) method.invoke(ps, command);
    String commandStr = ArrayUtils.toString(ret);

    String expected = "{hoot,--ogr2osm,/test/loc/translation.js,/test/loc/out.osm,/test/loc/out.osm}";
    Assert.assertEquals(expected, commandStr);

}

From source file:com.brienwheeler.lib.concurrent.ExecutorsTest.java

@Test
public void testFinalize() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    NamedThreadFactory threadFactory = new NamedThreadFactory(THREAD_FACTORY_NAME);
    ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory);
    Assert.assertFalse(executor.isShutdown());
    Method finalize = executor.getClass().getDeclaredMethod("finalize");
    finalize.setAccessible(true);
    finalize.invoke(executor);//from  w  ww . ja v a2 s  .  c o m
    Assert.assertTrue(executor.isShutdown());
}

From source file:com.googlecode.dex2jar.tools.ApkSign.java

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length != 1) {
        usage();//from w  ww.j  a va2  s  .  c o  m
        return;
    }

    File apkIn = new File(remainingArgs[0]);
    if (!apkIn.exists()) {
        System.err.println(apkIn + " is not exists");
        usage();
        return;
    }

    if (output == null) {
        if (apkIn.isDirectory()) {
            output = new File(apkIn.getName() + "-signed.apk");
        } else {
            output = new File(FilenameUtils.getBaseName(apkIn.getName()) + "-signed.apk");
        }
    }

    if (output.exists() && !forceOverwrite) {
        System.err.println(output + " exists, use --force to overwrite");
        usage();
        return;
    }
    File realJar;
    if (apkIn.isDirectory()) {
        realJar = File.createTempFile("d2j", ".jar");
        realJar.deleteOnExit();
        System.out.println("zipping " + apkIn + " -> " + realJar);
        OutHandler out = FileOut.create(realJar, true);
        try {
            new FileWalker().withStreamHandler(new OutAdapter(out)).walk(apkIn);
        } finally {
            IOUtils.closeQuietly(out);
        }
    } else {
        realJar = apkIn;
    }

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) certificateFactory
            .generateCertificate(ApkSign.class.getResourceAsStream("ApkSign.cer"));
    KeyFactory rSAKeyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = rSAKeyFactory.generatePrivate(
            new PKCS8EncodedKeySpec(IOUtils.toByteArray(ApkSign.class.getResourceAsStream("ApkSign.private"))));

    Class<?> clz;
    try {
        clz = Class.forName("com.android.signapk.SignApk");
    } catch (ClassNotFoundException cnfe) {
        System.err.println("please run d2j-apk-sign in a sun compatible JRE (contains sun.security.*)");
        return;
    }
    Method m = clz.getMethod("sign", X509Certificate.class, PrivateKey.class, boolean.class, File.class,
            File.class);
    m.setAccessible(true);

    System.out.println("sign " + realJar + " -> " + output);
    m.invoke(null, cert, privateKey, this.signWhole, realJar, output);
}

From source file:com.adaptris.core.management.ManagementComponentFactory.java

private void invokeMethod(final Object o, final String methodName, final Class[] paramTypes,
        final Object[] params) {
    final Class<? extends Object> clas = o.getClass();
    List<String> types = paramTypes(paramTypes);
    try {//from w  w  w .  j av  a 2 s.  co  m
        log.trace("{}#{}({})", clas.getName(), methodName, (types.size() > 0 ? types : ""));
        final Method method = clas.getMethod(methodName, paramTypes);
        method.setAccessible(true);
        method.invoke(o, params);
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        log.trace("FAILED: {}#{}({})", clas, methodName, (types.size() > 0 ? types : ""), e);
    }
}

From source file:hoot.services.controllers.ingest.RasterToTilesResourceTest.java

@Test
@Category(UnitTest.class)
public void TestGetZoomInfo() throws Exception {
    RasterToTilesService rts = new RasterToTilesService();
    Method getZoomInfoMethod = RasterToTilesService.class.getDeclaredMethod("getZoomInfo", double.class);
    getZoomInfoMethod.setAccessible(true);

    JSONObject oActual = (JSONObject) getZoomInfoMethod.invoke(rts, 0.025);

    Assert.assertEquals("0-1 2-3 4-5 6-7 8-9 10-11 12-13 14-15 16-17", oActual.get("zoomlist").toString());
    Assert.assertEquals(500, oActual.get("rastersize"));
}

From source file:com.databasepreservation.testing.unit.cli.ModuleFactoryTestHelper.java

private Map<String, Parameter> getModuleParameters(List<String> args) {
    try {/*from w  w  w  .  ja  v a  2s  . c o m*/
        CLI cli = new CLI(args, module);

        Method getModuleFactories = CLI.class.getDeclaredMethod("getModuleFactories", List.class);
        getModuleFactories.setAccessible(true);
        CLI.DatabaseModuleFactoriesPair databaseModuleFactoriesPair = (CLI.DatabaseModuleFactoriesPair) getModuleFactories
                .invoke(cli, args);

        return databaseModuleFactoriesPair.getImportModuleFactory().getAllParameters();
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:InlineTestStringsProvider.java

@SuppressWarnings("unchecked")
@Override//from www  . jav a2 s  . c o m
void provideStrings() throws Exception {

    // Setup errors are set by the constructor - if any.
    if (!isBlank(getErrors()) || !isSetupValid())
        return;

    String testItemsGeneratorClassName = getClassName();
    String testItemsGeneratorMethod = getMethodName();

    // Invoke a method in an 'inline' items provide class
    // This code is here by design in order to keep the inline test item provider with no dependency on any of the main classes (such as TestItem)
    try {
        Class c = loadInlineClassIfNeeded(testItemsGeneratorClassName);
        try {
            Object o = c.newInstance();
            ArrayList<String[]> testData = new ArrayList<>();
            Method m = c.getDeclaredMethod(testItemsGeneratorMethod, testData.getClass());
            m.setAccessible(true);
            // Invoke the method on the instance with testData as a parameter to be created and returned
            m.invoke(o, testData);
            stringifyTestItems(testData);
        } catch (InvocationTargetException e) {
            throw (new Exception(
                    "InvocationTargetException generated by invoking Inline Items Generator Class: "
                            + sq(testItemsGeneratorClassName) + " / Method: " + sq(testItemsGeneratorMethod)));
        } catch (Exception e) {
            throw (new Exception("Exception generated by invoking Inline Items Generator Class: "
                    + sq(testItemsGeneratorClassName) + " / Method: " + sq(testItemsGeneratorMethod)));
        }
    } catch (Exception e) {
        System.out.println("failed to get class for class named: " + sq(testItemsGeneratorClassName));
    }
}

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

@Test
public void testLogIOExceptionFileNotFound() throws Exception {
    //I can't put wrong file here. Checkstyle fails before check started.
    //I saw some usage of file or handling of wrong file in Checker, or somewhere
    //in checks running part. So I had to do it with reflection to improve coverage.
    TranslationCheck check = new TranslationCheck();
    DefaultConfiguration checkConfig = createCheckConfig(TranslationCheck.class);
    check.configure(checkConfig);//  w  w w .ja va2  s.  c  om
    Checker checker = createChecker(checkConfig);
    check.setMessageDispatcher(checker);

    Method loadKeys = check.getClass().getDeclaredMethod("loadKeys", File.class);
    loadKeys.setAccessible(true);
    loadKeys.invoke(check, new File(""));

}