@Test
 public void removeConnection() throws Exception {
   ConnectionFactoryRegistry connectionFactoryLocator = new ConnectionFactoryRegistry();
   ConnectionFactory<TestApi2> connectionFactory =
       new StubOAuth2ConnectionFactory("clientId", "clientSecret", THROW_EXCEPTION);
   connectionFactoryLocator.addConnectionFactory(connectionFactory);
   StubConnectionRepository connectionRepository = new StubConnectionRepository();
   connectionRepository.addConnection(
       connectionFactory.createConnection(
           new ConnectionData(
               "oauth2Provider", "provider1User1", null, null, null, null, null, null, null)));
   connectionRepository.addConnection(
       connectionFactory.createConnection(
           new ConnectionData(
               "oauth2Provider", "provider1User2", null, null, null, null, null, null, null)));
   assertEquals(2, connectionRepository.findConnections("oauth2Provider").size());
   ConnectController connectController =
       new ConnectController(connectionFactoryLocator, connectionRepository);
   List<DisconnectInterceptor<?>> interceptors = getDisconnectInterceptor();
   connectController.setDisconnectInterceptors(interceptors);
   MockMvc mockMvc = standaloneSetup(connectController).build();
   mockMvc
       .perform(delete("/connect/oauth2Provider/provider1User1"))
       .andExpect(redirectedUrl("/connect/oauth2Provider"));
   assertEquals(1, connectionRepository.findConnections("oauth2Provider").size());
   assertFalse(((TestConnectInterceptor<?>) (interceptors.get(0))).preDisconnectInvoked);
   assertFalse(((TestConnectInterceptor<?>) (interceptors.get(0))).postDisconnectInvoked);
   assertNull(((TestConnectInterceptor<?>) (interceptors.get(0))).connectionFactory);
   assertTrue(((TestConnectInterceptor<?>) (interceptors.get(1))).preDisconnectInvoked);
   assertTrue(((TestConnectInterceptor<?>) (interceptors.get(1))).postDisconnectInvoked);
   assertSame(
       connectionFactory, ((TestConnectInterceptor<?>) (interceptors.get(1))).connectionFactory);
 }
  public void testFindById() throws Exception {
    loadDataSetXml("admin/commserver/seedLocationsAndServices.xml");
    Location[] locations = m_out.getLocations();

    Location firstLocation = locations[0];
    int locationId = firstLocation.getId();

    Location locationById = m_out.getLocation(locationId);
    assertNotNull(locationById);
    assertEquals(firstLocation.getName(), locationById.getName());

    Collection<LocationSpecificService> services = locationById.getServices();
    assertNotNull(services);
    assertEquals(3, services.size());
  }
 @Test
 public void oauth2Callback() throws Exception {
   ConnectionFactoryRegistry connectionFactoryLocator = new ConnectionFactoryRegistry();
   ConnectionFactory<TestApi2> connectionFactory =
       new StubOAuth2ConnectionFactory("clientId", "clientSecret");
   connectionFactoryLocator.addConnectionFactory(connectionFactory);
   StubConnectionRepository connectionRepository = new StubConnectionRepository();
   ConnectController connectController =
       new ConnectController(connectionFactoryLocator, connectionRepository);
   List<ConnectInterceptor<?>> interceptors = getConnectInterceptor();
   connectController.setConnectInterceptors(interceptors);
   connectController.afterPropertiesSet();
   MockMvc mockMvc = standaloneSetup(connectController).build();
   assertEquals(0, connectionRepository.findConnections("oauth2Provider").size());
   mockMvc
       .perform(get("/connect/oauth2Provider").param("code", "oauth2Code"))
       .andExpect(redirectedUrl("/connect/oauth2Provider"));
   List<Connection<?>> connections = connectionRepository.findConnections("oauth2Provider");
   assertEquals(1, connections.size());
   assertEquals("oauth2Provider", connections.get(0).getKey().getProviderId());
   // Check for postConnect() only. The preConnect() is only invoked during the initial portion of
   // the flow
   assertFalse(((TestConnectInterceptor<?>) (interceptors.get(0))).postConnectInvoked);
   TestConnectInterceptor<?> testInterceptor2 = (TestConnectInterceptor<?>) (interceptors.get(1));
   assertTrue(testInterceptor2.postConnectInvoked);
 }
 @Test
 public void sortByExample4() {
   List<Integer> example = asList(1, 3, 5, 2, 4, 6);
   final List<String> expected = asList("1", "3", "5", "2", "4", "6");
   assertEquals(
       expected,
       Algorithms.sortByExample(
           example,
           Strings.<Integer>string(),
           asList("6", "5", "4", "3", "2", "1"),
           Functions.<String>identity()));
   assertEquals(
       asList("3", "5", "4"),
       Algorithms.sortByExample(
           example,
           Strings.<Integer>string(),
           asList("5", "4", "3"),
           Functions.<String>identity()));
   assertEquals(
       expected,
       Algorithms.sortByExample(
           example,
           Strings.<Integer>string(),
           asList("1", "2", "3", "4", "5", "6", "7", "8", "9"),
           Functions.<String>identity()));
 }
 @Test
 public void sortByExample1() {
   List<Integer> example = asList(1, 3, 5, 2, 4, 6);
   assertEquals(example, Algorithms.sortByExample(example, asList(6, 5, 4, 3, 2, 1)));
   assertEquals(asList(3, 5, 4), Algorithms.sortByExample(example, asList(5, 4, 3)));
   assertEquals(example, Algorithms.sortByExample(example, asList(1, 2, 3, 4, 5, 6, 7, 8, 9)));
 }
 public void executeCommand_givenEnvironmentVariable_echoThatEnvVar() {
   env.put("SHELL_EXECUTOR", "foo");
   String[] command = new String[] {"sh", "-c", "echo ${SHELL_EXECUTOR}"};
   shellExecutor.executeCommand(env, asList(command));
   List<String> out = shellExecutor.getStdOut();
   assertEquals(1, out.size());
   assertEquals("foo", out.get(0));
 }
 @Test
 public void first() {
   final List<String> values = asList("a", "b", "a", "c", "a", "d", "e");
   assertEquals("c", Algorithms.first(values, Conditions.eq("c")));
   assertEquals("a", Algorithms.first(values, Conditions.eq("a")));
   assertEquals("e", Algorithms.first(values, Conditions.eq("e")));
   assertNull(Algorithms.first(values, Conditions.eq("f")));
 }
 @SuppressWarnings({"ImplicitNumericConversion"})
 @Test
 public void count() {
   final List<String> values = asList("a", "b", "a", "c", "a", "d", "e");
   assertEquals(3, Algorithms.count(values, Conditions.eq("a")));
   assertEquals(1, Algorithms.count(values, Conditions.eq("e")));
   assertEquals(0, Algorithms.count(values, Conditions.eq("f")));
 }
 @Test
 public void findMergedAnnotationWithAttributeAliasesInTargetAnnotation() {
   Class<?> element = AliasedTransactionalComponentClass.class;
   AliasedTransactional annotation = findMergedAnnotation(element, AliasedTransactional.class);
   assertNotNull("@AliasedTransactional on " + element, annotation);
   assertEquals("TX value via synthesized annotation.", "aliasForQualifier", annotation.value());
   assertEquals(
       "TX qualifier via synthesized annotation.", "aliasForQualifier", annotation.qualifier());
 }
 @Test
 public void javaxAnnotationTypeViaFindMergedAnnotation() throws Exception {
   assertEquals(
       ResourceHolder.class.getAnnotation(Resource.class),
       findMergedAnnotation(ResourceHolder.class, Resource.class));
   assertEquals(
       SpringAppConfigClass.class.getAnnotation(Resource.class),
       findMergedAnnotation(SpringAppConfigClass.class, Resource.class));
 }
  @Test
  @Ignore
  public void anOrderCanBeShipped() throws Exception {
    Order order = new Order("x", "y", "z");
    assertEquals(false, order.isShipped());

    order.ship();

    assertEquals("order should be shipped", true, order.isShipped());
  }
 @Test
 public void javaLangAnnotationTypeViaFindMergedAnnotation() throws Exception {
   Constructor<?> deprecatedCtor = Date.class.getConstructor(String.class);
   assertEquals(
       deprecatedCtor.getAnnotation(Deprecated.class),
       findMergedAnnotation(deprecatedCtor, Deprecated.class));
   assertEquals(
       Date.class.getAnnotation(Deprecated.class),
       findMergedAnnotation(Date.class, Deprecated.class));
 }
Example #13
0
  @Test
  public void afterAdvice() {
    OnExitTracingAspect aspect = new OnExitTracingAspect();

    ServiceB b = new ServiceB("test");

    assertEquals(3, b.computeX(1, 2));
    assertEquals(5, b.computeX(2, 3));
    assertEquals(-10, b.computeX(0, -10));
    assertEquals(asList(3, 5, -10), aspect.values);
  }
Example #14
0
    @Mock(invocations = 1)
    public int computeX(int a, int b) {
      // Asserts that the received arguments meets the expected values.
      // Equivalent jMock2 expectations: one(mockOfServiceB).computeX(2, 5);
      assertEquals(2, a);
      assertEquals(5, b);

      // Returns the expected result.
      // Equivalent jMock2 expectation: will(returnValue(7));
      return 7;
    }
  public void testGetLocations() throws Exception {
    loadDataSetXml("admin/commserver/clearLocations.xml");
    Location[] emptyLocations = m_out.getLocations();
    assertEquals(0, emptyLocations.length);

    loadDataSetXml("admin/commserver/seedLocationsAndServices.xml");
    Location[] locations = m_out.getLocations();
    assertEquals(2, locations.length);
    assertEquals("https://localhost:8092/RPC2", locations[0].getProcessMonitorUrl());
    assertEquals("https://remotehost.example.org:8092/RPC2", locations[1].getProcessMonitorUrl());
  }
Example #16
0
 /** Validate that the client can intentionally disconnect and reconnect */
 @Test
 public void testClientDisconnect() throws Exception {
   String connectionId = blockingSSLConnect();
   selector.disconnect(connectionId);
   selector.poll(10, asList(SelectorTest.createSend(connectionId, "hello1")));
   assertEquals("Request should not have succeeded", 0, selector.completedSends().size());
   assertEquals("There should be a disconnect", 1, selector.disconnected().size());
   assertTrue(
       "The disconnect should be from our node", selector.disconnected().contains(connectionId));
   connectionId = blockingSSLConnect();
   assertEquals("hello2", blockingRequest(connectionId, "hello2"));
 }
Example #17
0
  @Test
  public void aroundAdvice() {
    TracingAspect aspect = new TracingAspect();

    ServiceB b = new ServiceB("test");

    assertEquals(3, b.computeX(1, 2));
    assertEquals(5, b.computeX(2, 3));
    assertEquals(-10, b.computeX(0, -10));
    assertEquals(asList(1, 2, 2, 3, 0, -10), aspect.inputValues);
    assertEquals(asList(3, 5, -10), aspect.outputValues);
  }
  public void testDeleteWithServices() throws Exception {
    loadDataSetXml("admin/commserver/seedLocationsAndServices.xml");
    Location[] locationsBeforeDelete = m_out.getLocations();
    assertEquals(2, locationsBeforeDelete.length);

    Location locationToDelete = m_out.getLocation(101);

    m_out.deleteLocation(locationToDelete);

    Location[] locationsAfterDelete = m_out.getLocations();
    assertEquals(1, locationsAfterDelete.length);
    assertEquals("remotehost.example.org", locationsAfterDelete[0].getFqdn());
  }
  @Test
  public void receiveAnOrder() throws Exception {
    when(request.getMethod()).thenReturn("POST");
    when(request.getRequestURI()).thenReturn("/orders");
    when(request.getParameter("order_code")).thenReturn("1234");
    when(request.getParameter("article_code")).thenReturn("ABCD");
    when(request.getParameter("address")).thenReturn("Some Place");

    ordersController.service();

    assertEquals(1, orders.size());
    assertEquals(new Order("1234", "ABCD", "Some Place"), orders.get(0));
  }
Example #20
0
 @Test
 public void zip1() {
   // Should result in a JoinResult that looks like: [(0,1,7), (1,2,8), (2,3,9)]
   final List<JoinResult<Integer, Integer, Integer>> results =
       Algorithms.zip(asList(1, 2, 3), asList(7, 8, 9));
   final Iterator<JoinResult<Integer, Integer, Integer>> r = results.iterator();
   for (int i = 0; i < 3; i++) {
     final JoinResult<Integer, Integer, Integer> result = r.next();
     assertEquals(Integer.valueOf(i), result.getKey());
     assertEquals(Integer.valueOf(i + 1), result.getX());
     assertEquals(Integer.valueOf(i + 7), result.getY());
   }
 }
Example #21
0
  /**
   * Send multiple requests to several connections in parallel. Validate that responses are received
   * in the order that requests were sent.
   */
  @Test
  public void testNormalOperation() throws Exception {
    int conns = 5;

    // create connections
    ArrayList<String> connectionIds = new ArrayList<String>();
    for (int i = 0; i < conns; i++) {
      connectionIds.add(blockingSSLConnect());
    }

    // send echo requests and receive responses
    int responseCount = 0;
    List<NetworkSend> sends = new ArrayList<NetworkSend>();
    for (int i = 0; i < conns; i++) {
      String connectionId = connectionIds.get(i);
      sends.add(SelectorTest.createSend(connectionId, connectionId + "&" + 0));
    }

    // loop until we complete all requests
    while (responseCount < conns) {
      // do the i/o
      selector.poll(0L, sends);

      assertEquals("No disconnects should have occurred.", 0, selector.disconnected().size());

      // handle any responses we may have gotten
      for (NetworkReceive receive : selector.completedReceives()) {
        String[] pieces = SelectorTest.asString(receive).split("&");
        assertEquals("Should be in the form 'conn-counter'", 2, pieces.length);
        assertEquals("Check the source", receive.getConnectionId(), pieces[0]);
        assertEquals(
            "Check that the receive has kindly been rewound",
            0,
            receive.getReceivedBytes().getPayload().position());
        assertTrue(
            "Received connectionId is as expected ",
            connectionIds.contains(receive.getConnectionId()));
        assertEquals("Check the request counter", 0, Integer.parseInt(pieces[1]));
        responseCount++;
      }

      // prepare new sends for the next round
      sends.clear();
      for (NetworkSend send : selector.completedSends()) {
        String dest = send.getConnectionId();
        sends.add(SelectorTest.createSend(dest, dest + "&" + 0));
      }
    }
  }
  public void testStore() throws Exception {
    loadDataSetXml("admin/commserver/clearLocations.xml");
    Location location = new Location();
    location.setName("test location");
    location.setAddress("192.168.1.2");
    location.setFqdn("localhost");

    m_out.storeLocation(location);

    Location[] dbLocations = m_out.getLocations();
    assertEquals(1, dbLocations.length);
    assertEquals("test location", dbLocations[0].getName());
    assertEquals("192.168.1.2", dbLocations[0].getAddress());
    assertEquals("localhost", dbLocations[0].getFqdn());
  }
Example #23
0
  @Test
  public void partition1() {
    final List<Integer> values = asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    Map<Boolean, Collection<Integer>> partitioned =
        Algorithms.partition(
            values,
            new Condition<Integer>() {
              public boolean eval(Integer integer) {
                return integer % 2 == 0;
              }
            });

    assertEquals(asList(1, 3, 5, 7, 9), partitioned.get(false));
    assertEquals(asList(2, 4, 6, 8, 10), partitioned.get(true));
  }
  @Test
  public void supportsOptionSynonyms() {
    OptionParser parser = new OptionParser();
    List<String> synonyms = asList("message", "blurb", "greeting");
    parser.acceptsAll(synonyms).withRequiredArg();
    String expectedMessage = "Hello";

    OptionSet options = parser.parse("--message", expectedMessage);

    for (String each : synonyms) {
      assertTrue(each, options.has(each));
      assertTrue(each, options.hasArgument(each));
      assertEquals(each, expectedMessage, options.valueOf(each));
      assertEquals(each, asList(expectedMessage), options.valuesOf(each));
    }
  }
Example #25
0
  /**
   * Validate that when the server disconnects, a client send ends up with that node in the
   * disconnected list.
   */
  @Test
  public void testServerDisconnect() throws Exception {
    // connect and do a simple request
    String connectionId = blockingSSLConnect();
    assertEquals("hello", blockingRequest(connectionId, "hello"));

    // disconnect
    server.closeConnections();
    while (!selector.disconnected().contains(connectionId)) {
      selector.poll(1000L);
    }

    // reconnect and do another request
    connectionId = blockingSSLConnect();
    assertEquals("hello", blockingRequest(connectionId, "hello"));
  }
 @Test
 public void getMetaAnnotationTypesOnClassWithMetaDepth2() {
   Set<String> names =
       getMetaAnnotationTypes(
           ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class);
   assertEquals(names(TransactionalComponent.class, Transactional.class, Component.class), names);
 }
 @Test
 public void oauth2ErrorCallback() throws Exception {
   ConnectionFactoryRegistry connectionFactoryLocator = new ConnectionFactoryRegistry();
   ConnectionFactory<TestApi2> connectionFactory =
       new StubOAuth2ConnectionFactory("clientId", "clientSecret", THROW_EXCEPTION);
   connectionFactoryLocator.addConnectionFactory(connectionFactory);
   StubConnectionRepository connectionRepository = new StubConnectionRepository();
   MockMvc mockMvc =
       standaloneSetup(new ConnectController(connectionFactoryLocator, connectionRepository))
           .build();
   assertEquals(0, connectionRepository.findConnections("oauth2Provider").size());
   HashMap<String, String> expectedError = new HashMap<String, String>();
   expectedError.put("error", "access_denied");
   expectedError.put("errorDescription", "The user said no.");
   expectedError.put("errorUri", "http://provider.com/user/said/no");
   mockMvc
       .perform(
           get("/connect/oauth2Provider")
               .param("error", "access_denied")
               .param("error_description", "The user said no.")
               .param("error_uri", "http://provider.com/user/said/no"))
       .andExpect(redirectedUrl("/connect/oauth2Provider"))
       .andExpect(request().sessionAttribute("social_authorization_error", notNullValue()))
       .andExpect(request().sessionAttribute("social_authorization_error", expectedError));
 }
 @Test
 public void connect_OAuth1Provider() throws Exception {
   ConnectionFactoryRegistry connectionFactoryLocator = new ConnectionFactoryRegistry();
   ConnectionFactory<TestApi1> connectionFactory =
       new StubOAuth1ConnectionFactory("clientId", "clientSecret");
   connectionFactoryLocator.addConnectionFactory(connectionFactory);
   ConnectController connectController = new ConnectController(connectionFactoryLocator, null);
   List<ConnectInterceptor<?>> interceptors = getConnectInterceptor();
   connectController.setConnectInterceptors(interceptors);
   connectController.afterPropertiesSet();
   MockMvc mockMvc = standaloneSetup(connectController).build();
   mockMvc
       .perform(post("/connect/oauth1Provider"))
       .andExpect(
           redirectedUrl("https://someprovider.com/oauth/authorize?oauth_token=requestToken"))
       .andExpect(
           request()
               .sessionAttribute(
                   "oauthToken",
                   samePropertyValuesAs(new OAuthToken("requestToken", "requestTokenSecret"))));
   // Check for preConnect() only. The postConnect() won't be invoked until after callback
   TestConnectInterceptor<?> textInterceptor1 = (TestConnectInterceptor<?>) (interceptors.get(0));
   assertTrue(textInterceptor1.preConnectInvoked);
   assertEquals("oauth1Provider", textInterceptor1.connectionFactory.getProviderId());
   assertFalse(((TestConnectInterceptor<?>) (interceptors.get(1))).preConnectInvoked);
 }
Example #29
0
 @Test
 public void select2() {
   final List<String> values = asList("a", "b", "a", "c", "a", "d", "e");
   assertEquals(
       asList("a", "a", "a"),
       Algorithms.select(values, new ArrayList<String>(10), Conditions.eq("a")));
 }
  /**
   * Tests the single parameter case.
   *
   * @throws IOException Never
   * @throws ServletException Never
   */
  @Test
  public void testSingleIDParameters() throws IOException, ServletException {
    RESTEdit action = new RESTEdit();
    ActionInvocationStore store = EasyMock.createStrictMock(ActionInvocationStore.class);
    EasyMock.expect(store.getCurrent())
        .andReturn(
            new DefaultActionInvocation(
                action,
                "/admin/user/rest-edit/12",
                null,
                asList("12"),
                new DefaultActionConfiguration(RESTEdit.class, "/admin/user/rest-edit"),
                true,
                true,
                null));
    EasyMock.replay(store);

    WorkflowChain chain = EasyMock.createStrictMock(WorkflowChain.class);
    chain.continueWorkflow();
    EasyMock.replay(chain);

    DefaultURIParameterWorkflow workflow =
        new DefaultURIParameterWorkflow(expressionEvaluator, store);
    workflow.perform(chain);

    assertEquals(12, action.id);

    EasyMock.verify(store, chain);
  }