List of usage examples for java.lang.reflect Method setAccessible
@Override @CallerSensitive public void setAccessible(boolean flag)
From source file:com.hybris.oms.rest.resources.TmallJSCMQ2TestEnvResource.java
@SuppressWarnings("unchecked") @POST/*w w w . j a v a2 s . c om*/ @Path("/sendmq2testenv") @Secured({ "ROLE_admin" }) public String sendMQ2TestEnv(final String oid) { final List<Message> messageList = sendTmallMessageRelatedConfig.getTmallMessageList(); // Mock Message Map<String, Object> rawMap = null; Map<String, String> contentMap = null; Message message = null; Class c; try { c = Class.forName("com.taobao.api.internal.tmc.Message"); final Method methodSetRaw = c.getDeclaredMethod("setRaw", Map.class); methodSetRaw.setAccessible(true); final Object tmallMessageObj = c.newInstance(); rawMap = new HashMap<String, Object>(); contentMap = new HashMap<String, String>(); contentMap.put("buyer_nick", "sandbox_cilai_c"); contentMap.put("payment", "44.00"); contentMap.put("tid", oid); contentMap.put("oid", oid); contentMap.put("seller_nick", "sandbox_c_1"); contentMap.put("type", "guarantee_trade"); rawMap.put("content", contentMap); rawMap.put("topic", "taobao_trade_TradeBuyerPay"); rawMap.put("time", Calendar.getInstance().getTime()); rawMap.put("id", "2130700002172846269"); rawMap.put("nick", "sandbox_c_1"); rawMap.put("userid", "2074082786"); rawMap.put("dataid", "192559684481084"); rawMap.put("publisher", "4272"); rawMap.put("outtime", Calendar.getInstance().getTime()); methodSetRaw.invoke(tmallMessageObj, rawMap); message = (Message) tmallMessageObj; message.setId(4160600490938325004L); message.setTopic("taobao_trade_TradeBuyerPay"); message.setPubTime(Calendar.getInstance().getTime()); message.setOutgoingTime(Calendar.getInstance().getTime()); message.setUserId(911757567L); message.setContentMap(contentMap); messageList.add(message); } catch (final Exception e1) { logger.error("message reflec error ", e1); } try { // messageNum = messageList.size(); // ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); // String json = ""; // json = ow.writeValueAsString(messageList.get(0).getRaw()); final JSONSerializer jsonSerializer = new JSONSerializer(); final String rawJson = jsonSerializer.deepSerialize(messageList.get(0).getRaw()); // ClientResponse response = sendTmallMessageRelatedConfig.getPostmq2testenvWR().header("X-tenantid", "single") // .post(ClientResponse.class, rawJson); final ClientResponse response = sendTmallMessageRelatedConfig.getReceivemqWR() .type(MediaType.APPLICATION_JSON).header("X-tenantid", "single") .post(ClientResponse.class, rawJson); if (response.getStatus() != 200) { logger.debug("Failed : HTTP error code : " + response.getStatus()); } else { messageList.clear(); } logger.info("Output from test env .... \n"); final String output = response.getEntity(String.class); logger.info("Receive " + output + " messages."); } catch (final Exception e) { logger.error("Fail to send to test env ", e); } // return messageNum + " messages are sent to test env."; return "1 messages are sent to test env."; }
From source file:com.puppycrawl.tools.checkstyle.checks.TranslationCheckTest.java
@Test public void testLogIOException() 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);/*from w ww .j a v a2 s . c om*/ check.setMessageDispatcher(createChecker(checkConfig)); Method logIOException = check.getClass().getDeclaredMethod("logIOException", IOException.class, File.class); logIOException.setAccessible(true); logIOException.invoke(check, new IOException("test exception"), new File("")); }
From source file:com.puppycrawl.tools.checkstyle.checks.header.HeaderCheckTest.java
@Test public void testIoExceptionWhenLoadingHeaderFile() throws Exception { HeaderCheck check = PowerMockito.spy(new HeaderCheck()); PowerMockito.doThrow(new IOException("expected exception")).when(check, "loadHeader", anyObject()); check.setHeaderFile(getPath("InputRegexpHeader1.java")); Method loadHeaderFile = AbstractHeaderCheck.class.getDeclaredMethod("loadHeaderFile"); loadHeaderFile.setAccessible(true); try {//from www . j a va 2 s .com loadHeaderFile.invoke(check); fail("Exception expected"); } catch (InvocationTargetException ex) { assertTrue(ex.getCause() instanceof CheckstyleException); assertEquals("unable to load header file " + getPath("InputRegexpHeader1.java"), ex.getCause().getMessage()); } }
From source file:hoot.services.utils.MultipartSerializerTest.java
@Test @Category(UnitTest.class) public void TestValidatePath() throws Exception { Method m = MultipartSerializer.class.getDeclaredMethod("validatePath", String.class, String.class); m.setAccessible(true); boolean isValid = (Boolean) m.invoke(null, //use null if the method is static "/projects/hoot/upload/123456", "/projects/hoot/upload/123456/DcGisRoads.gdb"); Assert.assertTrue(isValid);/*from w ww .ja va 2 s . c om*/ isValid = (Boolean) m.invoke(null, //use null if the method is static "/projects/hoot/upload/123456", "/projects/hoot/upload/123456/../DcGisRoads.gdb"); Assert.assertFalse(isValid); isValid = (Boolean) m.invoke(null, //use null if the method is static "/projects/hoot/upload/123456", "\0//DcGisRoads.gdb"); Assert.assertFalse(isValid); }
From source file:ProxyAdapter.java
@SuppressWarnings("unchecked") public ProxyAdapter(Class... interfaces) { proxy = (T) Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Method m; try { //Determine if the method has been defined in a subclass m = ProxyAdapter.this.getClass().getMethod(method.getName(), method.getParameterTypes()); m.setAccessible(true); } catch (Exception e) { //if not found throw new UnsupportedOperationException(method.toString(), e); }//from w ww . j a v a 2s .c o m //Invoke the method found and return the result try { return m.invoke(ProxyAdapter.this, args); } catch (InvocationTargetException e) { throw e.getCause(); } } }); }
From source file:com.epam.gepard.examples.gherkin.jbehave.FeatureFileFromJiraTicket.java
@Override protected String getStoryPath() { Environment e = getTestClassExecutionData().getEnvironment(); HtmlRunReporter htmlRunReporter = getTestClassExecutionData().getHtmlRunReporter(); String fieldValue;// w ww. j a va 2 s. com String featureFilename; try { //get feature info fieldValue = jiraSiteHandler.getTicketFieldValue(this, jiraTicket, "description"); int startPos = fieldValue.indexOf("Feature:"); int endPos = fieldValue.lastIndexOf("{noformat}"); if (startPos < 0 || endPos <= 0) { throw new SimpleGepardException("Cannot identify feature part in ticket: " + jiraTicket); } fieldValue = fieldValue.substring(startPos, endPos); //save it to file String featureFullFilename = htmlRunReporter.formatPathName(new java.io.File(".").getCanonicalPath()) + "/" + e.getProperty(Environment.GEPARD_HTML_RESULT_PATH) + "/" + getTestClassExecutionData().getHtmlRunReporter().getTestURL() + "." + jiraTicket + ".feature"; featureFilename = featureFullFilename.substring(featureFullFilename.lastIndexOf("/") + 1); String featurePath = featureFullFilename.substring(0, featureFullFilename.lastIndexOf("/")); File file = new File(featureFullFilename); File path = new File(featurePath); fileUtil.writeToFile(fieldValue, file); Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class }); method.setAccessible(true); method.invoke(ClassLoader.getSystemClassLoader(), new Object[] { path.toURI().toURL() }); } catch (JSONException | IOException ex) { throw new SimpleGepardException("Connect to JIRA failed.", ex); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) { throw new SimpleGepardException("Transferring Feature info to JBehave failed.", ex); } return featureFilename; }
From source file:com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractTypeAwareCheckTest.java
@Test public void testIsSubclassWithNulls() throws Exception { JavadocMethodCheck check = new JavadocMethodCheck(); Method isSubclass = check.getClass().getSuperclass().getDeclaredMethod("isSubclass", Class.class, Class.class); isSubclass.setAccessible(true); assertFalse((boolean) isSubclass.invoke(check, null, null)); }
From source file:de.thkwalter.et.ortskurve.OrtskurveControllerTest.java
/** * Test fr die Methode {@link OrtskurveController#messpunkteValidieren(Vector2D[])}. * /*from w ww .java 2 s .co m*/ * @throws Throwable */ @Test public void testMesspunkteValidieren2() throws Throwable { // Die in diesem Test verwendeten Messpunkte werden erzeugt. Vector2D[] testMesspunkte = new Vector2D[] { new Vector2D(1.0, 0.0), new Vector2D(3.0, 0.0), new Vector2D(2, 1) }; // Die zu testende Methode wird aufgerufen. Method methode = OrtskurveController.class.getDeclaredMethod("messpunkteValidieren", Vector2D[].class); methode.setAccessible(true); methode.invoke(this.ortskurveController, (Object) testMesspunkte); }
From source file:com.achep.acdisplay.notifications.OpenNotification.java
/** * Note, that method is not equals with {@link #equals(Object)} method. * * @param n notification to compare with. * @return {@code true} if notifications are from the same source and will * be handled by system as same notifications, {@code false} otherwise. *//*from w w w . j av a 2 s . c om*/ @SuppressLint("NewApi") @SuppressWarnings("ConstantConditions") public boolean hasIdenticalIds(@Nullable OpenNotification n) { if (n == null) return false; StatusBarNotification sbn = getStatusBarNotification(); StatusBarNotification sbn2 = n.getStatusBarNotification(); if (Device.hasLemonCakeApi()) { // FIXME: Android L reflections. // service.cancelNotification(notification.getKey()); try { Method method = sbn.getClass().getMethod("getKey"); method.setAccessible(true); String key = (String) method.invoke(sbn); String key2 = (String) method.invoke(sbn2); return new EqualsBuilder().append(key, key2).isEquals(); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { /* sad, but true */ } } return new EqualsBuilder().append(sbn.getId(), sbn2.getId()).append(getPackageName(), n.getPackageName()) .append(sbn.getTag(), sbn2.getTag()).isEquals(); }
From source file:com.glaf.core.util.ReflectUtils.java
public static Object invoke(Object object, String methodName) { try {//from w w w . j a v a2 s. c o m Method method = ReflectionUtils.findMethod(object.getClass(), methodName); if (!Modifier.isPublic(method.getModifiers())) { method.setAccessible(true); } return ReflectionUtils.invokeMethod(method, object); } catch (Exception ex) { throw new RuntimeException(ex); } }