List of usage examples for java.lang.reflect Method setAccessible
@Override @CallerSensitive public void setAccessible(boolean flag)
From source file:com.all.testing.MockInyectRunner.java
private Object createStub(Field field, Object instance) { try {/*from w w w.j a v a 2s. c om*/ Stub stubAnnotation = field.getAnnotation(Stub.class); if (StubPolicyCreation.NEW_PER_TEST_METHOD == stubAnnotation.value()) { String factoryMethodName = !stubAnnotation.factoryMethod().isEmpty() ? stubAnnotation.factoryMethod() : field.getName(); Method factoryMethod = instance.getClass().getDeclaredMethod(factoryMethodName); factoryMethod.setAccessible(true); Object stubInstance = factoryMethod.invoke(instance); setValue(field, instance, stubInstance); return stubInstance; } } catch (IllegalArgumentException e) { log.error(e, e); } catch (IllegalAccessException e) { log.error(e, e); } catch (SecurityException e) { log.error(e, e); } catch (NoSuchMethodException e) { log.error(e, e); } catch (InvocationTargetException e) { log.error(e, e); } return getFieldValue(instance, field); }
From source file:com.shazam.dataengineering.pipelinebuilder.DeploymentActionTest.java
@Test(expected = InvocationTargetException.class) // Caused by a DeploymentException @WithoutJenkins//from w ww . j a v a 2 s. co m public void validateNewPipelineShouldThrowExceptionWhenValidationFails() 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); ValidatePipelineDefinitionRequest validationRequest = new ValidatePipelineDefinitionRequest() .withPipelineId(pipelineId).withPipelineObjects(pipelineList); ValidatePipelineDefinitionResult validationResponse = new ValidatePipelineDefinitionResult() .withValidationWarnings(new ValidationWarning().withWarnings("1", "2", "3")) .withValidationErrors(new ValidationError().withErrors("4", "5"), new ValidationError().withErrors("6")) .withErrored(true); DataPipelineClient dataPipelineClient = mock(DataPipelineClient.class); when(dataPipelineClient.validatePipelineDefinition(validationRequest)).thenReturn(validationResponse); 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("validateNewPipeline", String.class, DataPipelineClient.class); method.setAccessible(true); method.invoke(action, pipelineId, dataPipelineClient); }
From source file:com.shazam.dataengineering.pipelinebuilder.DeploymentActionTest.java
@Test @WithoutJenkins/* ww w .j a v a 2s . co m*/ public void validateNewPipelineShouldSaveWarningAndErrorMessages() throws Exception { String pipelineId = "test1234"; String json = new FilePath(new File("src/test/resources/pipeline3.json")).readToString(); PipelineObject pipeline = new PipelineObject(json); ValidatePipelineDefinitionRequest validationRequest = new ValidatePipelineDefinitionRequest() .withPipelineId(pipelineId).withPipelineObjects(pipeline.getAWSObjects()); ValidatePipelineDefinitionResult validationResponse = new ValidatePipelineDefinitionResult() .withValidationWarnings(new ValidationWarning().withWarnings("1", "2", "3")) .withValidationErrors(new ValidationError().withErrors("4", "5"), new ValidationError().withErrors("6")) .withErrored(false); DataPipelineClient dataPipelineClient = mock(DataPipelineClient.class); when(dataPipelineClient.validatePipelineDefinition(validationRequest)).thenReturn(validationResponse); 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("validateNewPipeline", String.class, DataPipelineClient.class); method.setAccessible(true); method.invoke(action, pipelineId, dataPipelineClient); assertEquals(7, action.getClientMessages().size()); assertTrue(action.getClientMessages().get(0).contains("[ERROR]")); assertTrue(action.getClientMessages().get(1).contains("[ERROR]")); assertTrue(action.getClientMessages().get(2).contains("[ERROR]")); assertTrue(action.getClientMessages().get(3).contains("[WARN]")); assertTrue(action.getClientMessages().get(4).contains("[WARN]")); assertTrue(action.getClientMessages().get(5).contains("[WARN]")); }
From source file:com.legstar.config.commons.LegStarConfigCommons.java
/** * For a given configuration key and value locate a corresponding * setter method and use it./*from w w w .ja v a2 s . c o m*/ * * @param o the bean to set * @param key the configuration key * @param value the configuration value * @throws LegStarConfigurationException if setting value on bean fails */ protected void setValue(final Object o, final String key, final String value) throws LegStarConfigurationException { String setterName = getSetterName(key); if (_log.isDebugEnabled()) { _log.debug("Using setter method: " + setterName + ", for value: " + value); } try { Method[] allMethods = o.getClass().getMethods(); for (Method method : allMethods) { if (method.getName().equals(setterName)) { method.setAccessible(true); Class<?> parm = (Class<?>) method.getGenericParameterTypes()[0]; if (parm.isAssignableFrom(String.class)) { method.invoke(o, value); break; } if (parm.isAssignableFrom(boolean.class)) { method.invoke(o, Boolean.parseBoolean(value)); break; } if (parm.isAssignableFrom(int.class)) { method.invoke(o, Integer.parseInt(value)); break; } if (parm.isAssignableFrom(long.class)) { method.invoke(o, Long.parseLong(value)); break; } if (parm.isAssignableFrom(HostEndpoint.AccessStrategy.class)) { method.invoke(o, AccessStrategy.valueOf(value)); break; } _log.warn("Setter method: " + setterName + ", parameter type: " + parm + ", not compatible with value: " + value); } } } catch (SecurityException e) { throw new LegStarConfigurationException(e); } catch (IllegalArgumentException e) { throw new LegStarConfigurationException(e); } catch (IllegalAccessException e) { throw new LegStarConfigurationException(e); } catch (InvocationTargetException e) { throw new LegStarConfigurationException(e); } }
From source file:ota.otaupdates.MainActivity.java
/** * @return null if unconfirmed/*w w w. ja v a 2 s .co m*/ */ public Boolean isMobileDataEnabled() { Object connectivityService = getSystemService(CONNECTIVITY_SERVICE); ConnectivityManager cm = (ConnectivityManager) connectivityService; try { Class<?> c = Class.forName(cm.getClass().getName()); Method m = c.getDeclaredMethod("getMobileDataEnabled"); m.setAccessible(true); return (Boolean) m.invoke(cm); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:com.yahoo.pulsar.broker.namespace.NamespaceServiceTest.java
@Test public void testSplitMapWithRefreshedStatMap() throws Exception { OwnershipCache MockOwnershipCache = spy(pulsar.getNamespaceService().getOwnershipCache()); ManagedLedger ledger = mock(ManagedLedger.class); when(ledger.getCursors()).thenReturn(Lists.newArrayList()); doNothing().when(MockOwnershipCache).disableOwnership(any(NamespaceBundle.class)); Field ownership = NamespaceService.class.getDeclaredField("ownershipCache"); ownership.setAccessible(true);/*from w ww . ja va 2s . com*/ ownership.set(pulsar.getNamespaceService(), MockOwnershipCache); NamespaceService namespaceService = pulsar.getNamespaceService(); NamespaceName nsname = new NamespaceName("pulsar/global/ns1"); DestinationName dn = DestinationName.get("persistent://pulsar/global/ns1/topic-1"); NamespaceBundles bundles = namespaceService.getNamespaceBundleFactory().getBundles(nsname); NamespaceBundle originalBundle = bundles.findBundle(dn); PersistentTopic topic = new PersistentTopic(dn.toString(), ledger, pulsar.getBrokerService()); Method method = pulsar.getBrokerService().getClass().getDeclaredMethod("addTopicToStatsMaps", DestinationName.class, PersistentTopic.class); method.setAccessible(true); method.invoke(pulsar.getBrokerService(), dn, topic); String nspace = originalBundle.getNamespaceObject().toString(); List<PersistentTopic> list = this.pulsar.getBrokerService().getAllTopicsFromNamespaceBundle(nspace, originalBundle.toString()); assertNotNull(list); // Split bundle and take ownership of split bundles CompletableFuture<Void> result = namespaceService.splitAndOwnBundle(originalBundle); try { result.get(); } catch (Exception e) { // make sure: no failure fail("split bundle faild", e); } try { // old bundle should be removed from status-map list = this.pulsar.getBrokerService().getAllTopicsFromNamespaceBundle(nspace, originalBundle.toString()); fail(); } catch (NullPointerException ne) { // OK } // status-map should be updated with new split bundles NamespaceBundle splitBundle = pulsar.getNamespaceService().getBundle(dn); assertTrue(!CollectionUtils.isEmpty( this.pulsar.getBrokerService().getAllTopicsFromNamespaceBundle(nspace, splitBundle.toString()))); }
From source file:com.limegroup.gnutella.gui.themes.setters.SubstanceThemeSetter.java
private void fixWindowsOSFont() { try {/* w ww .jav a 2s . c om*/ Toolkit toolkit = Toolkit.getDefaultToolkit(); Method method = Toolkit.class.getDeclaredMethod("setDesktopProperty", String.class, Object.class); method.setAccessible(true); String fontName = null; String language = ApplicationSettings.getLanguage(); if (language != null) { if (language.startsWith("ja")) { //Meiryo for Japanese fontName = "Meiryo"; } else if (language.startsWith("ko")) { //Malgun Gothic for Korean fontName = "Malgun Gothic"; } else if (language.startsWith("zh")) { //Microsoft JhengHei for Chinese (Traditional) //Microsoft YaHei for Chinese (Simplified) fontName = "Microsoft JhengHei"; } else if (language.startsWith("he")) { //Gisha for Hebrew fontName = "Gisha"; } else if (language.startsWith("th")) { //Leelawadee for Thai fontName = "Leelawadee"; } } if (fontName != null) { Font font = new Font(fontName, Font.PLAIN, 12); method.invoke(toolkit, "win.icon.font", font); SubstanceLookAndFeel.setFontPolicy(SubstanceFontUtilities.getDefaultFontPolicy()); } } catch (Throwable e) { LOG.error("Error fixing font", e); } }
From source file:com.limegroup.gnutella.gui.themes.setters.SubstanceThemeSetter.java
private void fixLinuxOSFont() { try {/*from w ww.ja v a 2 s .co m*/ Toolkit toolkit = Toolkit.getDefaultToolkit(); Method method = Toolkit.class.getDeclaredMethod("setDesktopProperty", String.class, Object.class); method.setAccessible(true); String fontName = null; String language = ApplicationSettings.getLanguage(); if (language != null) { if (language.startsWith("ja")) { //Meiryo for Japanese fontName = "Meiryo"; } else if (language.startsWith("ko")) { //Malgun Gothic for Korean fontName = "Malgun Gothic"; } else if (language.startsWith("zh")) { //Microsoft JhengHei for Chinese (Traditional) //Microsoft YaHei for Chinese (Simplified) fontName = "Microsoft JhengHei"; } else if (language.startsWith("he")) { //Gisha for Hebrew fontName = "Gisha"; } else if (language.startsWith("th")) { //Leelawadee for Thai fontName = "Leelawadee"; } } if (fontName != null) { // linux is hardcoded to Dialog fontName = "Dialog"; method.invoke(toolkit, "gnome.Gtk/FontName", fontName); SubstanceLookAndFeel.setFontPolicy(SubstanceFontUtilities.getDefaultFontPolicy()); } } catch (Throwable e) { LOG.error("Error fixing font", e); } }