public List<ExternalResourceDescriptor> locateExternalResourceName(Trace trace) {
    Collection<Frame> dbFrames = trace.getLastFramesOfType(TYPE);
    if ((dbFrames == null) || dbFrames.isEmpty()) {
      return Collections.emptyList();
    }

    List<ExternalResourceDescriptor> dbDescriptors =
        new ArrayList<ExternalResourceDescriptor>(dbFrames.size());

    for (Frame dbFrame : dbFrames) {
      Operation op = dbFrame.getOperation();
      String host = op.get("host", String.class);
      Integer portProperty = op.get("port", Integer.class);
      int port = portProperty == null ? -1 : portProperty.intValue();

      String dbName = op.get("dbName", String.class);

      String redisHash = MD5NameGenerator.getName(dbName + host + port);

      dbDescriptors.add(
          new ExternalResourceDescriptor(
              dbFrame,
              "redis:" + redisHash,
              dbName,
              ExternalResourceType.DATABASE.name(),
              "Redis",
              host,
              port));
    }

    return dbDescriptors;
  }
  private Operation assertDataBinderOperation(DataBinder dataBinder) {
    Operation op = getLastEntered();
    assertNotNull("No operation", op);
    assertEquals("Mismatched type", InitBinderOperationCollectionAspect.TYPE, op.getType());
    assertEquals(
        "Mismatched object name",
        dataBinder.getObjectName(),
        op.get(InitBinderOperationFinalizer.OBJECT_NAME, String.class));

    Object target = dataBinder.getTarget();
    String expected =
        (target == null)
            ? InitBinderOperationFinalizer.UNKNOWN_TARGET_TYPE
            : target.getClass().getName();
    assertEquals(
        "Mismatched target type",
        expected,
        op.get(InitBinderOperationFinalizer.TARGET_TYPE, String.class));
    assertDataBinderFields(
        op, InitBinderOperationFinalizer.ALLOWED_FIELDS_LIST, dataBinder.getAllowedFields());
    assertDataBinderFields(
        op, InitBinderOperationFinalizer.DISALLOWED_FIELDS_LIST, dataBinder.getDisallowedFields());
    assertDataBinderFields(
        op, InitBinderOperationFinalizer.REQUIRED_FIELDS_LIST, dataBinder.getRequiredFields());

    return op;
  }
  @Test
  public void testBuiltStatementOptionValues() {

    MockSession session = new MockSession();
    Insert insert = QueryBuilder.insertInto("myTable");
    insert.values(new String[] {"arg"}, new Object[] {"stringvalue"});

    Insert.Options using = insert.using(timestamp(100));
    using.values(new String[] {"another"}, new Object[] {"value"});

    Operation operation = CassandraOperationFinalizer.get(insert);
    assertNotNull(operation);

    session.execute(insert);

    assertNotNull(operation.getLabel());
    assertEquals("OperationType", CassandraExternalResourceAnalyzer.TYPE, operation.getType());
    String cql = operation.get("cql", String.class);
    assertEquals("cql", insert.getQueryString(), cql);
    OperationMap params =
        operation.get(CassandraOperationFinalizer.PARAMS_VALUES, OperationMap.class);
    assertNotNull(params);
    assertEquals("params", params.size(), 2);
    assertNull(CassandraOperationFinalizer.remove(insert));
  }
  public Collection<ExternalResourceDescriptor> locateExternalResourceName(
      Trace trace, Collection<Frame> dbFrames) {
    if (ListUtil.size(dbFrames) <= 0) {
      return Collections.emptyList();
    }

    List<ExternalResourceDescriptor> dbDescriptors =
        new ArrayList<ExternalResourceDescriptor>(dbFrames.size());
    for (Frame dbFrame : dbFrames) {
      Operation op = dbFrame.getOperation();
      String host = op.get("host", String.class);
      int port = op.getInt("port", (-1));
      String dbName = op.get("dbName", String.class);

      String mongoHash = MD5NameGenerator.getName(dbName + host + port);
      String color = colorManager.getColor(op);
      dbDescriptors.add(
          new ExternalResourceDescriptor(
              dbFrame,
              "mongo:" + mongoHash,
              dbName,
              ExternalResourceType.DATABASE.name(),
              MONGODB_VENDOR,
              host,
              port,
              color,
              false));
    }

    return dbDescriptors;
  }
  @Test
  public void modelAttributeMethodWithComplexReturnTypeMonitored() {
    ExampleController testController = new ExampleController();
    testController.namedAccount_specialAccount();

    Operation operation = getLastEntered();
    assertEquals(Account.class.getName(), operation.get("value"));
    assertEquals("specialAccount", operation.get("modelAttributeName"));
  }
  @Test
  public void modelAttributeMethodWithSimpleReturnTypeMonitored() {
    ExampleController testController = new ExampleController();
    testController.namedString_specialString();

    Operation operation = getLastEntered();
    assertEquals("testString", operation.get("value"));
    assertEquals("specialString", operation.get("modelAttributeName"));
  }
  @Test
  public void modelAttributeMethodUnnamedScalarAttributeMonitored() {
    ExampleController testController = new ExampleController();
    testController.unnamedAttributeAccount();

    Operation operation = getLastEntered();
    assertEquals(Account.class.getName(), operation.get("value"));
    assertEquals("account", operation.get("modelAttributeName"));
  }
  @Test
  public void modelAttributeMethodWithUnnamedListAttributeMonitored() {
    ExampleController testController = new ExampleController();
    testController.unnamedAttributeListAccount();

    Operation operation = getLastEntered();
    assertEquals("java.util.ArrayList", operation.get("value"));
    assertEquals("accountList", operation.get("modelAttributeName"));
  }
  @Test
  public void testExtractStreamMessageTypeAttributes() throws JMSException {
    StreamMessage objectMessage = mock(StreamMessage.class);

    Operation op = new Operation();

    extractMessageTypeAttributes(op, objectMessage);

    String type = op.get(MESSAGE_TYPE, String.class);

    assertEquals(MessageType.StreamMessage.name(), type);
    assertNull(op.get(MESSAGE_CONTENT));
    assertNull(op.get(MESSAGE_CONTENT_MAP));
  }
  @Test
  public void testMethodsIntercepted() {
    ClassPathXmlApplicationContext ctx =
        new ClassPathXmlApplicationContext("test-class-path-scan-operation.xml", getClass());
    assertNotNull("Cannot find " + Fubar.class.getSimpleName(), ctx.getBean(Fubar.class));

    ArgumentCaptor<Operation> opCaptor = ArgumentCaptor.forClass(Operation.class);
    Mockito.verify(spiedOperationCollector, Mockito.atLeastOnce()).enter(opCaptor.capture());

    final Package pkg = getClass().getPackage();
    Map<String, String> locationsMap =
        new TreeMap<String, String>() {
          private static final long serialVersionUID = 1L;

          {
            put("findCandidateComponents", pkg.getName());
            put(
                "findPathMatchingResources",
                "classpath*:" + pkg.getName().replace('.', '/') + "/**/*.class");
          }
        };
    for (Operation captured : opCaptor.getAllValues()) {
      Operation op = assertScanOperation(captured);
      SourceCodeLocation scl = op.getSourceCodeLocation();
      String methodName = scl.getMethodName();
      String expectedLocation = locationsMap.remove(methodName);
      assertNotNull("Unnown method: " + methodName, expectedLocation);

      String actualLocation =
          op.get(SpringLifecycleMethodOperationCollectionAspect.EVENT_ATTR, String.class);
      assertEquals(methodName + ": Mismatched location", expectedLocation, actualLocation);
    }

    assertTrue("Aspect did not intercept call to " + locationsMap.keySet(), locationsMap.isEmpty());
  }
  private void assertQueryDescriptor(ExternalResourceDescriptor desc, String oSql) {
    ExternalResourceDescriptor parent = desc.getParentDescriptor();
    assertNotNull("QUERY ExternalResourceDescriptor parent", parent);

    ExternalResourceType type = ExternalResourceType.valueOf(parent.getType());
    assertSame("QUERY ExternalResourceDescriptor parent type", ExternalResourceType.DATABASE, type);

    List<ExternalResourceDescriptor> children = parent.getChildren();
    assertNotNull("QUERY ExternalResourceDescriptor parent children", children);
    assertEquals("QUERY ExternalResourceDescriptor parent children size", 1, children.size());

    ExternalResourceDescriptor firstChild = children.get(0);
    assertNotNull("QUERY ExternalResourceDescriptor parent first child", firstChild);
    assertSame("QUERY ExternalResourceDescriptor parent first child", desc, firstChild);

    Frame frame = desc.getFrame();
    assertNotNull("QUERY ExternalResourceDescriptor frame", frame);

    Operation op = frame.getOperation();
    assertNotNull("QUERY ExternalResourceDescriptor frame operation", frame);

    String sql = oSql != null ? oSql : op.get("sql", String.class);
    assertEquals("QUERY ExternalResourceDescriptor label", sql, desc.getLabel());

    assertEquals("QUERY ExternalResourceDescriptor vendor", parent.getVendor(), desc.getVendor());
    assertEquals("QUERY ExternalResourceDescriptor host", parent.getHost(), desc.getHost());
    assertEquals("QUERY ExternalResourceDescriptor port", parent.getPort(), desc.getPort());
    assertEquals(
        "QUERY ExternalResourceDescriptor incoming", parent.isIncoming(), desc.isIncoming());
  }
 @Test
 public void testSetWithDbName() {
   DummyJedisCommands client = new DummyJedisCommands("localhost");
   client.set("mykey", "myvalue");
   Operation op = getLastEntered();
   assertNotNull("No operation extracted", op);
   assertEquals("Mismatched method name", "set", op.get("methodName"));
   assertEquals("Mismatched label", "Redis: mykey.set", op.getLabel());
   assertEquals(
       "Mismatched argument value",
       "mykey",
       op.get(OperationFields.ARGUMENTS, OperationList.class).get(0));
   assertEquals("Mismatched host", "localhost", op.get("host"));
   assertEquals("Mismatched port", 6379, op.getInt("port", (-1)));
   assertEquals("Mismatched DB name", "0", op.get("dbName"));
 }
  @Test
  public void testExtractTextMessageTypeAttributes() throws JMSException {
    TextMessage txtMessage = mock(TextMessage.class);
    when(txtMessage.getText()).thenReturn("test-text");

    Operation op = new Operation();

    extractMessageTypeAttributes(op, txtMessage);

    String type = op.get(MESSAGE_TYPE, String.class);
    String content = op.get(MESSAGE_CONTENT, String.class);

    assertEquals(MessageType.TextMessage.name(), type);
    assertEquals("test-text", content);
    assertNull(op.get(MESSAGE_CONTENT_MAP));
  }
  @Test
  public void testExtractMapMessageTypeAttributes() throws JMSException {
    MapMessage mapMessage = mock(MapMessage.class);

    final Map<String, String> mockMap = new HashMap<String, String>();
    mockMap.put("test-key", "test-value");

    when(mapMessage.getMapNames())
        .thenReturn(
            new Enumeration<String>() {
              Iterator<String> iter = mockMap.keySet().iterator();

              public boolean hasMoreElements() {
                return iter.hasNext();
              }

              public String nextElement() {
                return iter.next();
              }
            });

    when(mapMessage.getObject(
            argThat(
                new BaseMatcher<String>() {
                  public boolean matches(Object val) {
                    return "test-key".equals(val);
                  }

                  public void describeTo(Description desc) {
                    // do nothing
                  }
                })))
        .thenReturn(mockMap.get("test-key"));

    Operation op = new Operation();

    extractMessageTypeAttributes(op, mapMessage);

    String type = op.get(MESSAGE_TYPE, String.class);
    OperationMap contentMap = op.get(MESSAGE_CONTENT_MAP, OperationMap.class);

    assertNotNull(contentMap);
    assertEquals(mockMap.size(), contentMap.size());
    assertEquals(mockMap.get("test-key"), contentMap.get("test-key"));
    assertEquals(MessageType.MapMessage.name(), type);
    assertNull(op.get(MESSAGE_CONTENT));
  }
  @Test
  public void testCached() throws Exception {
    DummyFilter dFilter = new DummyFilter();
    dFilter.init(new DummyFilterConfig());
    dFilter.doFilter(null, null, null);
    Operation first = getLastEntered();
    assertNotNull(first);
    reset(spiedOperationCollector);
    dFilter.doFilter(null, null, null);
    Operation second = getLastEntered();

    // We cache the entire Operation, but return different references
    assertTrue(first.equals(second));
    assertEquals(first.getLabel(), second.getLabel());
    assertEquals(first.get("filterClass"), second.get("filterClass"));
    assertEquals(first.get("filterName"), second.get("filterName"));
  }
 // execution(* DBCursor.sort(DBSort));
 @Test
 public void sort() throws Exception {
   testCursor().sort(new BasicDBObject("sort", "this"));
   Operation op = getLastEntered();
   assertNotNull(op);
   assertEquals("MongoDB: DBCursor.sort()", op.getLabel());
   assertEquals("{ \"sort\" : \"this\"}", ((OperationList) op.get("args")).get(0));
   standardAsserts(op);
 }
 // execution(* DBCursor.limit(int));
 @Test
 public void limit() throws Exception {
   testCursor().limit(35);
   Operation op = getLastEntered();
   assertNotNull(op);
   assertEquals("MongoDB: DBCursor.limit()", op.getLabel());
   assertEquals("35", ((OperationList) op.get("args")).get(0));
   standardAsserts(op);
 }
 @Test
 public void toArrayInt() throws Exception {
   testCursor().toArray(43);
   Operation op = getLastEntered();
   assertNotNull(op);
   assertEquals("MongoDB: DBCursor.toArray()", op.getLabel());
   assertEquals("43", ((OperationList) op.get("args")).get(0));
   standardAsserts(op);
 }
 @Test
 public void testPing() {
   DummyJedisCommands client = new DummyJedisCommands(null);
   client.ping();
   Operation op = getLastEntered();
   assertNotNull("No operation extracted", op);
   assertEquals("Mismatched method name", "ping", op.get("methodName"));
   assertEquals("Mismatched label", "Redis: ping", op.getLabel());
 }
  @Test
  public void testRun2() throws Exception {
    // Step 1: Execute test
    tests.test_Traverse2();

    // Step 2:  Get the Operation that was just created by our aspect
    Operation op = getLastEntered();
    assertNotNull("No Neo4J.Traverse operation data is intercepted", op);

    // Step 3:  Validate
    assertEquals(
        "Invalid operation type", OperationCollectionTypes.TRAVERSE_TYPE.type, op.getType());

    assertEquals("Invalid Label", OperationCollectionTypes.TRAVERSE_TYPE.label, op.getLabel());

    assertNotNull("Parameter 'start' does not exists", op.get("start"));
    assertNotNull(
        "Parameter 'traversalDescription' does not exists", op.get("traversalDescription"));
  }
  static void assertAttributes(final Map<String, Object> mockMap, Operation op) {
    Object map = op.get(MESSAGE_PROPERTIES);

    assertNotNull(map);
    assertTrue(map instanceof OperationMap);

    OperationMap opMap = (OperationMap) map;

    for (String key : mockMap.keySet()) {
      assertEquals(mockMap.get(key), opMap.get(key));
    }
  }
  @Test
  public void testBuiltStatementValue() {

    MockSession session = new MockSession();
    Insert insert = QueryBuilder.insertInto("myTable");
    insert.value("arg", "stringvalue");

    Operation operation = CassandraOperationFinalizer.get(insert);
    assertNotNull(operation);

    session.execute(insert);

    assertNotNull(operation.getLabel());
    assertEquals("OperationType", CassandraExternalResourceAnalyzer.TYPE, operation.getType());
    String cql = operation.get("cql", String.class);
    assertEquals("cql", insert.getQueryString(), cql);
    OperationMap params =
        operation.get(CassandraOperationFinalizer.PARAMS_VALUES, OperationMap.class);
    assertNotNull(params);
    assertEquals("params", params.size(), 1);
    assertNull(CassandraOperationFinalizer.remove(insert));
  }
  protected Operation assertScanOperation(Operation op) {
    assertNotNull("No operation", op);
    assertEquals(
        "Mismatched operation type",
        SpringLifecycleMethodEndPointAnalyzer.CLASSPATH_SCAN_TYPE,
        op.getType());

    String compType =
        op.get(
            StereotypedSpringBeanMethodOperationCollectionAspectSupport.COMP_TYPE_ATTR,
            String.class);
    // make sure not intercepted by one of the stereotyped beans aspects
    assertNull("Unexpected stereotyped bean method collection: " + compType, compType);
    return op;
  }
  static void assertHeaders(Message message, Operation op) throws JMSException {
    Object map = op.get(MESSAGE_HEADERS);

    assertNotNull(map);
    assertTrue(map instanceof OperationMap);

    OperationMap opMap = (OperationMap) map;

    assertEquals(CORRELATION_ID, message.getJMSCorrelationID(), opMap.get(CORRELATION_ID));
    assertEquals(
        DELIVERY_MODE,
        getDeliveryMode(message.getJMSDeliveryMode()).getLabel(),
        opMap.get(DELIVERY_MODE));
    assertEquals(EXPIRATION, Long.valueOf(message.getJMSExpiration()), opMap.get(EXPIRATION));
    assertEquals(MESSAGE_ID, message.getJMSMessageID(), opMap.get(MESSAGE_ID));
    assertEquals(PRIORITY, Integer.valueOf(message.getJMSPriority()), opMap.get(PRIORITY));
    assertEquals(REDELIVERED, Boolean.valueOf(message.getJMSRedelivered()), opMap.get(REDELIVERED));
  }
 public void standardAsserts(Operation op) {
   assertEquals(MongoCursorOperationCollectionAspect.TYPE, op.getType());
   assertEquals("{ \"key\" : \"value\"}", op.get("keysWanted"));
   assertEquals("{ \"query\" : \"value\"}", op.get("query"));
 }
 /**
  * @param conn The created {@link Connection}
  * @param op The {@link Operation} containing the URL in its {@link
  *     OperationFields#CONNECTION_URL} attribute
  * @return The previous assigned URL to the connection - <code>null</code> if none
  */
 String startTracking(Connection conn, Operation op) {
   return startTracking(conn, op.get(OperationFields.CONNECTION_URL, String.class));
 }
  private void runLiveSearchControlsActions(DirContextCreator creator)
      throws NamingException, URISyntaxException {
    final String DN_PROPNAME = "objectclass", DN_PROPVAL = "person", BASE_DN = "ou=people";
    final String ARGS_FILTER = "(&(" + DN_PROPNAME + "=" + DN_PROPVAL + ")(uid={0})(sn={1}))";
    final Format userSearchFilter = new MessageFormat(ARGS_FILTER);

    for (Map<String, Set<String>> ldifEntry : LDIF_ENTRIES) {
      Set<String> classValues = ldifEntry.get(DN_PROPNAME);
      if (!classValues.contains(DN_PROPVAL)) {
        continue;
      }
      Set<String> values = ldifEntry.get("cn");
      assertNotNull("No CN for " + ldifEntry, values);
      assertEquals("Multiple CB(s) for " + ldifEntry, 1, values.size());

      /*
       * The LDIF is set up in such a way that for person(s), the
       * 'uid' value is same as the 1st name in lowercase, and the
       * 'sn' value is same as the 2nd name
       */
      String cnValue = values.iterator().next().trim();
      int spacePos = cnValue.indexOf(' ');
      String uidValue = cnValue.substring(0, spacePos).toLowerCase();
      String snValue = cnValue.substring(spacePos + 1);
      Object[] filterArgs = {uidValue, snValue};
      String noArgsFilter = userSearchFilter.format(filterArgs);
      for (SearchControlsActions action : SearchControlsActions.values()) {
        final String TEST_NAME = cnValue + "[" + action + "]";
        final String TEST_FILTER = action.isRequiredFilterArgs() ? ARGS_FILTER : noArgsFilter;
        final Object[] SEARCH_ARGS = action.isRequiredFilterArgs() ? filterArgs : null;
        logger.info("Running test: " + TEST_NAME);
        DirContext context = creator.createDirContext();
        Hashtable<?, ?> environment;
        try {
          // save a copy just in case it changes on context close
          environment = new Hashtable<Object, Object>(context.getEnvironment());

          NamingEnumeration<SearchResult> result =
              action.search(context, BASE_DN, TEST_FILTER, SEARCH_ARGS);
          assertNotNull(TEST_NAME + ": No result", result);
          try {
            if (!checkMatchingSearchResult(result, "cn", cnValue)) {
              fail(TEST_NAME + ": No match found");
            }
          } finally {
            result.close();
          }
        } catch (NamingException e) {
          logger.warn(
              "search("
                  + TEST_NAME
                  + ")"
                  + " "
                  + e.getClass().getSimpleName()
                  + ": "
                  + e.getMessage(),
              e);
          throw e;
        } finally {
          context.close();
        }

        Operation op = assertContextOperation(TEST_NAME, BASE_DN, environment);
        assertEquals(
            TEST_NAME + ": Mismatched filter",
            TEST_FILTER,
            op.get(LdapDefinitions.LOOKUP_FILTER_ATTR, String.class));
        assertExternalResourceAnalysis(
            TEST_NAME, op, (String) environment.get(Context.PROVIDER_URL));
        Mockito.reset(spiedOperationCollector); // prepare for next iteration
      }
    }
  }
 private static OperationList assertDataBinderFields(Operation op, String key, String... names) {
   return assertDataBinderFields(op.get(key, OperationList.class), key, names);
 }