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.app.test.util.SearchResultUtilTest.java

@Test
public void testAddNewResultsWithPreviousSearchQueryResults() throws Exception {

    _addSearchResult("1234");

    List<SearchResult> searchResults = SearchResultUtil.getSearchQueryResults(_SEARCH_QUERY_ID);

    SearchResult searchResult = searchResults.get(0);

    for (int i = 0; i < PropertiesValues.TOTAL_NUMBER_OF_PREVIOUS_SEARCH_RESULT_IDS; i++) {
        SearchQueryPreviousResultUtil.addSearchQueryPreviousResult(searchResult.getSearchQueryId(),
                String.valueOf(i));
    }/*from  w  w  w. j  av a  2  s . c  om*/

    Assert.assertEquals(10, SearchQueryPreviousResultUtil.getSearchQueryPreviousResultsCount(_SEARCH_QUERY_ID));

    Method method = _clazz.getDeclaredMethod("_addNewResults", List.class);

    method.setAccessible(true);

    method.invoke(_classInstance, searchResults);

    searchResults = SearchResultUtil.getSearchQueryResults(_SEARCH_QUERY_ID);

    searchResult = searchResults.get(0);

    Assert.assertEquals(_SEARCH_QUERY_ID, searchResult.getSearchQueryId());
    Assert.assertEquals("1234", searchResult.getItemId());
    Assert.assertEquals("First Item", searchResult.getItemTitle());
    Assert.assertEquals("$10.00", searchResult.getAuctionPrice());
    Assert.assertEquals("$14.99", searchResult.getFixedPrice());
    Assert.assertEquals("http://www.ebay.com/itm/1234", searchResult.getItemURL());
    Assert.assertEquals("http://www.ebay.com/123.jpg", searchResult.getGalleryURL());

    Assert.assertEquals(10, SearchQueryPreviousResultUtil.getSearchQueryPreviousResultsCount(_SEARCH_QUERY_ID));

    List<String> searchQueryPreviousResults = SearchQueryPreviousResultUtil
            .getSearchQueryPreviousResults(_SEARCH_QUERY_ID);

    String latestSearchQueryPreviousResult = searchQueryPreviousResults.get(9);

    Assert.assertEquals("1234", latestSearchQueryPreviousResult);
}

From source file:gov.nih.nci.system.web.struts.action.CreateAction.java

private void setParameterValue(Class klass, Object instance, String name, String value)
        throws NumberFormatException, Exception {
    if (value != null && value.trim().length() == 0)
        value = null;// w w  w.j  ava2s. c  o  m

    try {
        String paramName = name.substring(0, 1).toUpperCase() + name.substring(1);
        Method[] allMethods = klass.getMethods();
        for (Method m : allMethods) {
            String mname = m.getName();
            if (mname.equals("get" + paramName)) {
                Class type = m.getReturnType();
                Class[] argTypes = new Class[] { type };

                Method method = null;
                while (klass != Object.class) {
                    try {
                        Method setMethod = klass.getDeclaredMethod("set" + paramName, argTypes);
                        setMethod.setAccessible(true);
                        Object converted = convertValue(type, value);
                        if (converted != null)
                            setMethod.invoke(instance, converted);
                        break;
                    } catch (NumberFormatException e) {
                        throw e;
                    } catch (NoSuchMethodException ex) {
                        klass = klass.getSuperclass();
                    } catch (Exception e) {
                        throw e;
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:com.adobe.acs.commons.email.impl.EmailServiceImplTest.java

@Test
public final void testSendEmailAttachment() throws Exception {

    final String expectedMessage = "This is just a message";
    final String expectedSenderName = "John Smith";
    final String expectedSenderEmailAddress = "john@smith.com";
    final String attachment = "This is a attachment.";
    final String attachmentName = "attachment.txt";
    //Subject is provided inside the HtmlTemplate directly
    final String expectedSubject = "Greetings";

    final Map<String, String> params = new HashMap<String, String>();
    params.put("message", expectedMessage);
    params.put("senderName", expectedSenderName);
    params.put("senderEmailAddress", expectedSenderEmailAddress);

    final String recipient = "upasanac@acs.com";

    Map<String, DataSource> attachments = new HashMap();
    attachments.put(attachmentName, new ByteArrayDataSource(attachment, "text/plain"));

    ArgumentCaptor<HtmlEmail> captor = ArgumentCaptor.forClass(HtmlEmail.class);

    final List<String> failureList = emailService.sendEmail(emailTemplateAttachmentPath, params, attachments,
            recipient);/*from  www .j  a  v  a2s  .  c om*/

    verify(messageGatewayHtmlEmail, times(1)).send(captor.capture());

    assertEquals(expectedSenderEmailAddress, captor.getValue().getFromAddress().getAddress());
    assertEquals(expectedSenderName, captor.getValue().getFromAddress().getPersonal());
    assertEquals(expectedSubject, captor.getValue().getSubject());
    assertEquals(recipient, captor.getValue().getToAddresses().get(0).toString());
    Method getContainer = captor.getValue().getClass().getSuperclass().getDeclaredMethod("getContainer");
    getContainer.setAccessible(true);
    MimeMultipart mimeMultipart = (MimeMultipart) getContainer.invoke(captor.getValue());
    getContainer.setAccessible(false);
    assertEquals(attachment, mimeMultipart.getBodyPart(0).getContent().toString());

    //If email is sent to the recipient successfully, the response is an empty failureList
    assertTrue(failureList.isEmpty());
}

From source file:com.google.gdt.eclipse.designer.hosted.tdz.HostedModeSupport.java

public void dispose() {
    m_browserShell.dispose();/*from  w w  w .  j a  v  a  2  s.c  o m*/
    // dispose if initialized (may be not if Module loading failed)
    if (m_moduleSpaceHost != null) {
        m_moduleSpaceHost.getModuleSpace().dispose();
    }
    // dispose for project; if the same project used in another editor 
    // it would be added again by activating the project. 
    m_gwtSharedClassLoader.dispose(m_moduleDescription);
    m_logSupport.dispose();
    m_moduleSpaceHost = null;
    // clear static caches
    try {
        Class<?> clazz = m_gwtSharedClassLoader.loadClass("com.google.gwt.i18n.rebind.ClearStaticData");
        Method method = clazz.getDeclaredMethod("clear");
        method.setAccessible(true);
        method.invoke(null);
    } catch (Throwable e) {
    }
    try {
        Class<?> clazz = m_gwtSharedClassLoader
                .loadClass("com.google.gwt.uibinder.rebind.model.OwnerFieldClass");
        Field mapField = clazz.getDeclaredField("FIELD_CLASSES");
        mapField.setAccessible(true);
        Map<?, ?> map = (Map<?, ?>) mapField.get(null);
        map.clear();
    } catch (Throwable e) {
    }
}

From source file:com.github.ekumen.rosjava_actionlib.ActionClient.java

/**
 * Convenience method for retrieving the goal ID of a given action goal message.
 * @param goal The action goal message from where to obtain the goal ID.
 * @return Goal ID object containing the ID of the action message.
 * @see actionlib_msgs.GoalID/*www .j a v  a  2  s  .  co m*/
 */
public GoalID getGoalId(T_ACTION_GOAL goal) {
    GoalID gid = null;
    try {
        Method m = goal.getClass().getMethod("getGoalId");
        m.setAccessible(true); // workaround for known bug http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6924232
        gid = (GoalID) m.invoke(goal);
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
    return gid;
}

From source file:com.shazam.dataengineering.pipelinebuilder.DeploymentActionTest.java

@Test
public void writingReportShouldCreateJsonFile() throws Exception {
    DeploymentAction action = new DeploymentAction(getMockAbstractBuild(), new HashMap<S3Environment, String>(),
            new AnonymousAWSCredentials());

    Date date = new Date();

    Method method = action.getClass().getDeclaredMethod("writeReport", Date.class, String.class, Boolean.TYPE);
    method.setAccessible(true);

    method.invoke(action, date, "test-1234", true);

    File logFile = new File(testFolder.getRoot(), "deployment.log");
    assertTrue(logFile.exists());/*from  w  ww  . j  av a 2s .c o m*/

    List<String> jsonContent = Files.readAllLines(logFile.toPath(), Charset.defaultCharset());
    assertEquals(1, jsonContent.size());

    JSONParser jsonParser = new JSONParser();
    JSONObject log = (JSONObject) jsonParser.parse(jsonContent.get(0));
    JSONArray deployments = (JSONArray) log.get("deployments");
    JSONObject deployment = (JSONObject) deployments.get(0);

    assertEquals(String.valueOf(date.getTime()), deployment.get("date").toString());
    assertEquals("SYSTEM", deployment.get("username").toString());
    assertEquals("true", deployment.get("status").toString());
    assertEquals("test-1234", deployment.get("pipelineId"));
}

From source file:com.cloudera.impala.security.PersistedDelegationTokenSecretManager.java

@Override
public synchronized void startThreads() throws IOException {
    try {/*from w  w  w  .j  a va2  s. co  m*/
        // updateCurrentKey needs to be called to initialize the master key
        // (there should be a null check added in the future in rollMasterKey)
        // updateCurrentKey();
        Method m = AbstractDelegationTokenSecretManager.class.getDeclaredMethod("updateCurrentKey");
        m.setAccessible(true);
        m.invoke(this);
    } catch (Exception e) {
        throw new IOException("Failed to initialize master key", e);
    }
    running = true;
    tokenRemoverThread = new Daemon(new ExpiredTokenRemover());
    tokenRemoverThread.start();
}

From source file:com.shazam.dataengineering.pipelinebuilder.DeploymentActionTest.java

private String executeGetPipelineIdMethod(String pipelineFileName)
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    List<PipelineIdName> pipelineList = new ArrayList<PipelineIdName>();
    pipelineList.add(new PipelineIdName().withId("test1").withName("p1-this-is-a-test-pipeline-1"));
    pipelineList.add(new PipelineIdName().withId("test2").withName("d2-this-is-a-test-pipeline-1"));
    DeploymentAction action = new DeploymentAction(getMockAbstractBuild(), new HashMap<S3Environment, String>(),
            new AnonymousAWSCredentials());
    DataPipelineClient client = getMockDataPipelineClient(pipelineList);

    Method method = action.getClass().getDeclaredMethod("getPipelineId", String.class,
            DataPipelineClient.class);
    method.setAccessible(true);

    return (String) method.invoke(action, pipelineFileName, client);
}

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

@Test
public void testRemovePreviouslyNotifiedResults() throws Exception {
    SearchResult searchResult = new SearchResult(1, "1234", "First Item", "$10.00", "$14.99",
            "http://www.ebay.com/itm/1234", "http://www.ebay.com/123.jpg");

    List<SearchResult> searchResults = new ArrayList<>();

    searchResults.add(searchResult);//w w  w. j  ava2  s  .c  o m

    Method method = _clazz.getDeclaredMethod("_removePreviouslyNotifiedResults", int.class, List.class);

    method.setAccessible(true);

    method.invoke(_classInstance, 1, searchResults);

    Assert.assertEquals(1, searchResults.size());

    SearchQueryPreviousResultUtil.addSearchQueryPreviousResult(searchResult.getSearchQueryId(), "2345");

    method.invoke(_classInstance, 1, searchResults);

    Assert.assertEquals(1, searchResults.size());

    SearchQueryPreviousResultUtil.addSearchQueryPreviousResult(searchResult.getSearchQueryId(), "1234");

    method.invoke(_classInstance, 1, searchResults);

    Assert.assertEquals(0, searchResults.size());
}

From source file:gov.nih.nci.caarray.web.action.project.ProjectSamplesActionTest.java

private void setProjectForExperiment(Experiment e, Project p) throws SecurityException, NoSuchMethodException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    final Method m = e.getClass().getDeclaredMethod("setProject", Project.class);
    m.setAccessible(true);
    m.invoke(e, p);//  w ww  .j  a v a  2 s  .co m
}