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.jboss.instrument.classloading.JBossModulesLoadTimeWeaver.java

public void addTransformer(ClassFileTransformer transformer) {
    try {// w  w w .  ja  va2s .  c om
        Field transformers = ReflectionUtils.findField(classLoader.getClass(), "transformer");
        transformers.setAccessible(true);
        Object delegatingTransformer = transformers.get(classLoader);
        Method ADD_TRANSFORMER = ReflectionUtils.findMethod(delegatingTransformer.getClass(), "addTransformer",
                new Class<?>[] { ClassFileTransformer.class });
        ADD_TRANSFORMER.setAccessible(true);
        ADD_TRANSFORMER.invoke(delegatingTransformer, transformer);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:android.core.HttpHeaderTest.java

public void testCacheControlMultipleArguments() throws Exception {
    // get private method CacheManager.parseHeaders()
    Method m = CacheManager.class.getDeclaredMethod("parseHeaders",
            new Class[] { int.class, Headers.class, String.class });
    m.setAccessible(true);

    // create indata
    Headers h = new Headers();
    CharArrayBuffer buffer = new CharArrayBuffer(64);
    buffer.append(CACHE_CONTROL_COMPOUND);
    h.parseHeader(buffer);//w  w w.  ja v a 2 s.c  om

    CacheResult c = (CacheResult) m.invoke(null, 200, h, "text/html");

    // Check that expires is set to 0, to ensure that no-cache has overridden
    // the max-age argument
    assertEquals(0, c.getExpires());

    // check reverse order
    buffer.clear();
    buffer.append(CACHE_CONTROL_COMPOUND2);
    h.parseHeader(buffer);

    c = (CacheResult) m.invoke(null, 200, h, "text/html");
    assertEquals(0, c.getExpires());
}

From source file:com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractTypeAwareCheckTest.java

@Test
public void testClassAliasToString() throws Exception {
    Class<?> tokenType = Class.forName("com.puppycrawl.tools.checkstyle.checks.AbstractTypeAwareCheck$Token");

    Class<?> regularClassType = Class
            .forName("com.puppycrawl.tools.checkstyle.checks.AbstractTypeAwareCheck$RegularClass");
    Constructor<?> regularClassConstructor = regularClassType.getDeclaredConstructor(tokenType, String.class,
            AbstractTypeAwareCheck.class);
    regularClassConstructor.setAccessible(true);

    Constructor<?> tokenConstructor = tokenType.getDeclaredConstructor(String.class, int.class, int.class);
    Object token = tokenConstructor.newInstance("blablabla", 1, 1);

    Object regularClass = regularClassConstructor.newInstance(token, "sur", new JavadocMethodCheck());

    Class<?> classAliasType = Class
            .forName("com.puppycrawl.tools.checkstyle.checks.AbstractTypeAwareCheck$ClassAlias");
    Class<?> abstractTypeInfoType = Class
            .forName("com.puppycrawl.tools.checkstyle.checks.AbstractTypeAwareCheck$AbstractClassInfo");

    Constructor<?> classAliasConstructor = classAliasType.getDeclaredConstructor(tokenType,
            abstractTypeInfoType);// w w w  .  ja v a2 s . c  o m
    classAliasConstructor.setAccessible(true);

    Object classAlias = classAliasConstructor.newInstance(token, regularClass);
    Method toString = classAlias.getClass().getDeclaredMethod("toString");
    toString.setAccessible(true);
    String result = (String) toString.invoke(classAlias);
    assertEquals("ClassAlias[alias Token[blablabla(1x1)] for Token[blablabla(1x1)]]", result);
}

From source file:de.haber.xmind2latex.XMindToLatexExporterTest.java

@Test
public void testSave() {
    File in = new File("src/test/resources/content.xml");
    File out = new File("target/testout/result.tex");
    if (out.exists()) {
        out.delete();//from   w  ww .  j  a v  a2 s .c  om
    }
    String[] args = new String[] { "-i", in.getAbsolutePath(), "-o", out.getAbsolutePath() };

    XMindToLatexExporter exporter;
    try {
        exporter = CliParameters.build(args);

        Method save = exporter.getClass().getDeclaredMethod("save", String.class);
        assertNotNull(save);
        save.setAccessible(true);

        String txt = "   ?     ";
        save.invoke(exporter, txt);
        String content = FileUtils.readFileToString(out, "UTF-8");
        assertEquals(txt, content);

    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:pl.edu.pwr.iiar.zak.thermalKit.deserializers.HeaterUnitDeserializerTest.java

@Test
public void testDeserializeThermalInstances() throws Exception {
    Method method = HeaterUnitDeserializer.class.getDeclaredMethod("deserializeThermalInstances",
            ArrayNode.class);
    method.setAccessible(true);

    JsonNodeFactory factory = JsonNodeFactory.instance;
    ArrayNode instanceArrayNode = new ArrayNode(factory);
    ObjectNode instanceNode = new ObjectNode(factory);
    instanceArrayNode.add(instanceNode);

    instanceNode.put("name", "upper");
    instanceNode.put("primitiveType", "SLICEL");

    ArrayNode attributeArrayNode = new ArrayNode(factory);
    instanceNode.put("attributes", attributeArrayNode);
    ObjectNode attributeNode = new ObjectNode(factory);
    attributeArrayNode.add(attributeNode);
    attributeNode.put("physicalName", "phyName1");
    attributeNode.put("logicalName", "logName1");
    attributeNode.put("value", "value1");

    ArrayNode enablePinsNode = new ArrayNode(factory);
    instanceNode.put("enablePins", enablePinsNode);
    ObjectNode enablePinNode = new ObjectNode(factory);
    enablePinsNode.add(enablePinNode);//  w  w w .ja  va  2  s .c om
    enablePinNode.put("isOutputPin", false);
    enablePinNode.put("name", "D3");

    System.out.print(instanceArrayNode.toString());

    ArrayList<ThermalInstance> heaterInstances = (ArrayList<ThermalInstance>) method
            .invoke(new HeaterUnitDeserializer(), instanceArrayNode);

    ThermalInstance heaterInstance = heaterInstances.get(0);
    Assert.assertEquals(heaterInstance.getName(), "upper");
    Assert.assertEquals(heaterInstance.getType().toString(), "SLICEL");
}

From source file:com.app.test.util.CategoryUtilTest.java

@Test
public void testCreateGetCategoriesCall() throws Exception {
    Method method = _clazz.getDeclaredMethod("_createGetCategoriesCall");

    method.setAccessible(true);

    GetCategoriesCall getCategoriesCall = (GetCategoriesCall) method.invoke(_classInstance);

    ApiContext apiContext = getCategoriesCall.getApiContext();

    DetailLevelCodeType[] detailLevelCodeTypes = { DetailLevelCodeType.RETURN_ALL };

    Assert.assertNotNull(apiContext);//from w  w w.  j a v  a  2 s.  c  o m
    Assert.assertEquals(SiteCodeType.US, getCategoriesCall.getCategorySiteID());
    Assert.assertArrayEquals(detailLevelCodeTypes, getCategoriesCall.getDetailLevel());
    Assert.assertEquals(_SUB_CATEGORY_LEVEL_LIMIT, getCategoriesCall.getLevelLimit());
    Assert.assertTrue(getCategoriesCall.getViewAllNodes());
}

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

private Map<Parameter, String> getModuleArguments(boolean forImportModule, List<String> args) {
    try {/*from www . j av a  2 s .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);

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

        if (forImportModule) {
            return databaseModuleFactoriesArguments.getImportModuleArguments();
        } else {
            return databaseModuleFactoriesArguments.getExportModuleArguments();
        }
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:at.tugraz.ist.catroid.test.content.XMLValidatingTest.java

@SuppressWarnings("unchecked")
public void testSerializeProjectWithAllBricks() throws IllegalArgumentException, IllegalAccessException,
        InvocationTargetException, IOException, JSONException {

    File projectDirectory = new File(Consts.DEFAULT_ROOT + "/" + testProjectName);
    if (projectDirectory.exists()) {
        UtilFile.deleteDirectory(projectDirectory);
    }/*from   www . j a v  a 2 s  .  c  o  m*/

    Project project = new Project(getContext(), testProjectName);
    Sprite sprite = new Sprite("testSprite");
    Script startScript = new StartScript(sprite);
    Script whenScript = new WhenScript(sprite);
    Script broadcastScript = new BroadcastScript(sprite);
    sprite.addScript(startScript);
    sprite.addScript(whenScript);
    sprite.addScript(broadcastScript);
    project.addSprite(sprite);

    ProjectManager.getInstance().setProject(project);
    ProjectManager.getInstance().setCurrentSprite(sprite);
    ProjectManager.getInstance().setCurrentScript(startScript);

    Method[] methods = AddBrickDialog.class.getDeclaredMethods();
    HashMap<String, List<Brick>> brickMap = null;

    if (PluginManager.getInstance() == null) {
        PluginManager.createPluginManager(getContext());
    }

    for (Method method : methods) {
        if (method.getName().equalsIgnoreCase("setupBrickMap")) {
            method.setAccessible(true);
            brickMap = (HashMap<String, List<Brick>>) method.invoke(null, sprite, getContext());
            break;
        }
    }

    for (List<Brick> brickList : brickMap.values()) {
        for (Brick brick : brickList) {
            startScript.addBrick(brick);
        }
    }

    assertTrue("no bricks added to the start script", startScript.getBrickList().size() > 0);
    StorageHandler.getInstance().saveProject(project);

    //TODO adapt for Drone Bricks
    XMLValidationUtil.sendProjectXMLToServerForValidating(project);
}

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

@Test
@Category(UnitTest.class)
public void testcreateScriptCmd() throws Exception {
    //private String createScriptCmd(JSONObject cmd)
    hoot.services.controllers.wps.ETLProcessletTest etlTest = new hoot.services.controllers.wps.ETLProcessletTest();
    String sParam = etlTest.generateJobParam();
    JSONParser parser = new JSONParser();
    JSONObject command = (JSONObject) parser.parse(sParam);

    ProcessStreamInterface ps = new ProcessStreamInterface();

    Class[] cArg = new Class[1];
    cArg[0] = JSONObject.class;
    Method method = ProcessStreamInterface.class.getDeclaredMethod("createScriptCmdArray", cArg);
    method.setAccessible(true);
    command.put("jobId", "123-456-789");
    String[] ret = (String[]) method.invoke(ps, command);
    String commandStr = ArrayUtils.toString(ret);

    String expected = "";

    try {/*from   ww  w. j  a v  a2  s .co m*/
        String coreScriptPath = HootProperties.getProperty("coreScriptPath");

        String coreOutputPath = HootProperties.getProperty("coreScriptOutputPath");

        String ETLMakefile = HootProperties.getInstance().getProperty("ETLMakefile",
                HootProperties.getDefault("ETLMakefile"));
        String makePath = coreScriptPath + "/" + ETLMakefile;

        //[make, -f, /project/hoot/scripts/makeetl, translation=/test/file/test.js, INPUT_TYPE=OSM, INPUT=/test/file/INPUT.osm,  jobid=123-456-789]
        expected = "{make,-f," + makePath
                + ",translation=/test/file/test.js,INPUT_TYPE=OSM,INPUT=/test/file/INPUT.osm";
        expected += ",jobid=123-456-789";

        String dbname = HootProperties.getProperty("dbName");
        String userid = HootProperties.getProperty("dbUserId");
        String pwd = HootProperties.getProperty("dbPassword");
        String host = HootProperties.getProperty("dbHost");
        String dbUrl = "postgresql://" + userid + ":" + pwd + "@" + host + "/" + dbname;
        expected += ",DB_URL=" + dbUrl + "}";

    } catch (IOException e) {

    }

    Assert.assertEquals(expected, commandStr);

}

From source file:com.rackspacecloud.blueflood.cache.TtlCacheTest.java

private void forceMeterTick(String fieldName) {
    try {//w  w  w. j av  a 2 s  .  co m
        Field generalErrorMeterField = TtlCache.class.getDeclaredField(fieldName);
        generalErrorMeterField.setAccessible(true);
        Object generalErrorMeter = generalErrorMeterField.get(twoSecondCache);
        Method tick = generalErrorMeter.getClass().getDeclaredMethod("tick");
        tick.setAccessible(true);
        tick.invoke(generalErrorMeter);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}