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 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());
  }
  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;
  }
  @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));
  }
  private static EndPointAnalysis assertEndpointAnalysis(
      Trace trace, Frame grailsFrame, Frame httpFrame) {
    EndPointAnalysis ep = endPointAnalyzer.locateEndPoint(trace);
    assertNotNull("No analysis", ep);

    Operation operation = grailsFrame.getOperation();
    String resourceKey =
        GrailsControllerMethodEndPointAnalyzer.makeResourceKey(operation.getSourceCodeLocation());
    EndPointName epName = EndPointName.valueOf(resourceKey);
    assertEquals("Mismatched endpoint name", epName, ep.getEndPointName());

    assertEquals("Mismatched label", operation.getLabel(), ep.getResourceLabel());
    assertEquals(
        "Mismatched score",
        EndPointAnalysis.depth2score(FrameUtil.getDepth(grailsFrame)),
        ep.getScore());

    if (httpFrame == null) {
      assertEquals("Mismatched grails example", operation.getLabel(), ep.getExample());
    } else {
      String expected = EndPointAnalysis.createHttpExampleRequest(httpFrame);
      assertEquals("Mismatched http example", expected, ep.getExample());
    }

    return ep;
  }
  @Test
  public void testLocateExternalResourceNameWhenEnabledWithSqlAndDisabledApp() {
    assertInitialState();

    // enable query external resources creation
    registry.set(CollectionSettingNames.CS_QUERY_EXRTERNAL_RESOURCE_NAME, Boolean.TRUE);

    Operation op = createJdbcOperation("jdbc:foobar://huh:8080");
    op.type(JdbcOperationExternalResourceAnalyzer.TYPE);

    Frame frame = createJdbcFrame(op);
    Trace trace = createJdbcTrace(frame);

    registry.set(
        CollectionSettingNames.createApplicationCollectionSettingName(trace.getAppName()),
        Boolean.FALSE);

    Collection<ExternalResourceDescriptor> resources = locateExternalResourceName(trace);

    // make sure that no query external resources were created
    assertNotNull("external resource descriptors list", resources);
    assertEquals("total external resource descriptors", 1, resources.size());

    ExternalResourceDescriptor firstDescriptor = ListUtil.getFirstMember(resources);
    ExternalResourceType type = ExternalResourceType.valueOf(firstDescriptor.getType());
    assertSame("first descriptor type", ExternalResourceType.DATABASE, type);
    assertFalse("first descriptor is a parent", firstDescriptor.isParent());

    assertTrue(
        trace.getAppName() + "is known", generator.isApplicationNameKnown(trace.getAppName()));
  }
  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 testAddDestinationDetailsToMapIfNeeded() throws JMSException {
    Queue queue = mock(Queue.class);
    when(queue.getQueueName()).thenReturn("mock-queue");

    Operation op = new Operation();
    OperationMap map = op.createMap("test-map");

    addDestinationDetailsToMapIfNeeded(queue, map, "test");

    String type = map.get("test" + TYPE, String.class);
    String name = map.get("test" + NAME, String.class);

    assertNotNull(type);
    assertNotNull(name);

    assertEquals(type, DestinationType.Queue.name());
    assertEquals(name, "mock-queue");

    queue = null;
    op = new Operation();
    map = op.createMap("test-map");

    addDestinationDetailsToMapIfNeeded(queue, map, "test");
    type = map.get("test" + TYPE, String.class);
    name = map.get("test" + NAME, String.class);

    assertNull(type);
    assertNull(name);
  }
  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;
  }
 // execution(* DBCursor.toArray());
 @Test
 public void toArray() throws Exception {
   testCursor().toArray();
   Operation op = getLastEntered();
   assertNotNull(op);
   assertEquals("MongoDB: DBCursor.toArray()", op.getLabel());
   standardAsserts(op);
 }
  @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"));
  }
 // 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 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 modelAttributeMethodWithSimpleReturnTypeMonitored() {
    ExampleController testController = new ExampleController();
    testController.namedString_specialString();

    Operation operation = getLastEntered();
    assertEquals("testString", operation.get("value"));
    assertEquals("specialString", operation.get("modelAttributeName"));
  }
 @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 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));
  }
  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;
  }
  @Test
  public void testLocateExternalResourceNameWhenEnabledAndWithSql() {
    assertInitialState();

    // enable query external resources creation
    registry.set(CollectionSettingNames.CS_QUERY_EXRTERNAL_RESOURCE_NAME, Boolean.TRUE);

    Operation op = createJdbcOperation("jdbc:foobar://huh:8080");
    op.type(JdbcOperationExternalResourceAnalyzer.TYPE);
    op.put("sql", "selct * from all");

    Frame frame = createJdbcFrame(op);
    Trace trace = createJdbcTrace(frame);

    assertQueryExternalResources(trace);
  }
  @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 testLocateExternalResourceNameWhenEnabledWithoutSqlAndWithDriverOperationType() {
    assertInitialState();

    analyzer = new TestJDBCURIAnalyzer(JdbcDriverExternalResourceAnalyzer.TYPE);

    // enable query external resources creation
    registry.set(CollectionSettingNames.CS_QUERY_EXRTERNAL_RESOURCE_NAME, Boolean.TRUE);

    Operation op = createJdbcOperation("jdbc:foobar://huh:8080");
    op.label("test-label");
    op.type(JdbcDriverExternalResourceAnalyzer.TYPE);

    Frame frame = createJdbcFrame(op);
    Trace trace = createJdbcTrace(frame);

    assertQueryExternalResources(trace, 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"));
  }
  @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"));
  }
  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));
  }
  @Test
  public void testLocateExternalResourceNameWhenDisabled() {
    assertInitialState();

    Operation op = createJdbcOperation("jdbc:foobar://huh:8080");
    op.type(JdbcOperationExternalResourceAnalyzer.TYPE);

    Frame frame = createJdbcFrame(op);
    Trace trace = createJdbcTrace(frame);

    Collection<ExternalResourceDescriptor> resources = locateExternalResourceName(trace);

    // make sure that no query external resources were created
    assertNotNull("external resource descriptors list", resources);
    assertEquals("total external resource descriptors", 1, resources.size());

    ExternalResourceDescriptor firstDescriptor = ListUtil.getFirstMember(resources);
    ExternalResourceType type = ExternalResourceType.valueOf(firstDescriptor.getType());
    assertSame("first descriptor type", ExternalResourceType.DATABASE, type);
    assertFalse("first descriptor is a parent", firstDescriptor.isParent());

    assertTrue(
        trace.getAppName() + " is known", generator.isApplicationNameKnown(trace.getAppName()));
  }
 @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"));
 }