Search in sources :

Example 66 with ObjectId

use of org.bson.types.ObjectId in project graylog2-server by Graylog2.

the class StreamResource method cloneStream.

@POST
@Path("/{streamId}/clone")
@Timed
@ApiOperation(value = "Clone a stream")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Stream not found."), @ApiResponse(code = 400, message = "Invalid or missing Stream id.") })
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@AuditEvent(type = AuditEventTypes.STREAM_CREATE)
public Response cloneStream(@ApiParam(name = "streamId", required = true) @PathParam("streamId") String streamId, @ApiParam(name = "JSON body", required = true) @Valid @NotNull CloneStreamRequest cr) throws ValidationException, NotFoundException {
    checkPermission(RestPermissions.STREAMS_CREATE);
    checkPermission(RestPermissions.STREAMS_READ, streamId);
    checkNotDefaultStream(streamId, "The default stream cannot be cloned.");
    final Stream sourceStream = streamService.load(streamId);
    final String creatorUser = getCurrentUser().getName();
    // Create stream.
    final Map<String, Object> streamData = Maps.newHashMap();
    streamData.put(StreamImpl.FIELD_TITLE, cr.title());
    streamData.put(StreamImpl.FIELD_DESCRIPTION, cr.description());
    streamData.put(StreamImpl.FIELD_CREATOR_USER_ID, creatorUser);
    streamData.put(StreamImpl.FIELD_CREATED_AT, Tools.nowUTC());
    streamData.put(StreamImpl.FIELD_MATCHING_TYPE, sourceStream.getMatchingType().toString());
    streamData.put(StreamImpl.FIELD_REMOVE_MATCHES_FROM_DEFAULT_STREAM, cr.removeMatchesFromDefaultStream());
    streamData.put(StreamImpl.FIELD_INDEX_SET_ID, cr.indexSetId());
    final Stream stream = streamService.create(streamData);
    streamService.pause(stream);
    final String id = streamService.save(stream);
    final List<StreamRule> sourceStreamRules = streamRuleService.loadForStream(sourceStream);
    for (StreamRule streamRule : sourceStreamRules) {
        final Map<String, Object> streamRuleData = Maps.newHashMapWithExpectedSize(6);
        streamRuleData.put(StreamRuleImpl.FIELD_TYPE, streamRule.getType().toInteger());
        streamRuleData.put(StreamRuleImpl.FIELD_FIELD, streamRule.getField());
        streamRuleData.put(StreamRuleImpl.FIELD_VALUE, streamRule.getValue());
        streamRuleData.put(StreamRuleImpl.FIELD_INVERTED, streamRule.getInverted());
        streamRuleData.put(StreamRuleImpl.FIELD_STREAM_ID, new ObjectId(id));
        streamRuleData.put(StreamRuleImpl.FIELD_DESCRIPTION, streamRule.getDescription());
        final StreamRule newStreamRule = streamRuleService.create(streamRuleData);
        streamRuleService.save(newStreamRule);
    }
    for (AlertCondition alertCondition : streamService.getAlertConditions(sourceStream)) {
        try {
            final AlertCondition clonedAlertCondition = alertService.fromRequest(CreateConditionRequest.create(alertCondition.getType(), alertCondition.getTitle(), alertCondition.getParameters()), stream, creatorUser);
            streamService.addAlertCondition(stream, clonedAlertCondition);
        } catch (ConfigurationException e) {
            LOG.warn("Unable to clone alert condition <" + alertCondition + "> - skipping: ", e);
        }
    }
    for (AlarmCallbackConfiguration alarmCallbackConfiguration : alarmCallbackConfigurationService.getForStream(sourceStream)) {
        final CreateAlarmCallbackRequest request = CreateAlarmCallbackRequest.create(alarmCallbackConfiguration);
        final AlarmCallbackConfiguration alarmCallback = alarmCallbackConfigurationService.create(stream.getId(), request, getCurrentUser().getName());
        alarmCallbackConfigurationService.save(alarmCallback);
    }
    for (Output output : sourceStream.getOutputs()) {
        streamService.addOutput(stream, output);
    }
    clusterEventBus.post(StreamsChangedEvent.create(stream.getId()));
    final Map<String, String> result = ImmutableMap.of("stream_id", id);
    final URI streamUri = getUriBuilderToSelf().path(StreamResource.class).path("{streamId}").build(id);
    return Response.created(streamUri).entity(result).build();
}
Also used : ObjectId(org.bson.types.ObjectId) StreamRule(org.graylog2.plugin.streams.StreamRule) URI(java.net.URI) CreateAlarmCallbackRequest(org.graylog2.rest.models.alarmcallbacks.requests.CreateAlarmCallbackRequest) ConfigurationException(org.graylog2.plugin.configuration.ConfigurationException) Output(org.graylog2.plugin.streams.Output) AlertCondition(org.graylog2.plugin.alarms.AlertCondition) Stream(org.graylog2.plugin.streams.Stream) AlarmCallbackConfiguration(org.graylog2.alarmcallbacks.AlarmCallbackConfiguration) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent) AuditEvent(org.graylog2.audit.jersey.AuditEvent) ApiResponses(io.swagger.annotations.ApiResponses)

Example 67 with ObjectId

use of org.bson.types.ObjectId in project graylog2-server by Graylog2.

the class V20161125161400_AlertReceiversMigrationTest method doMigrateMultipleQualifyingStreams.

@Test
public void doMigrateMultipleQualifyingStreams() throws Exception {
    final String matchingStreamId1 = new ObjectId().toHexString();
    final String matchingStreamId2 = new ObjectId().toHexString();
    final Stream stream1 = mock(Stream.class);
    when(stream1.getAlertReceivers()).thenReturn(Collections.emptyMap());
    final Stream stream2 = mock(Stream.class);
    when(stream2.getAlertReceivers()).thenReturn(ImmutableMap.of("users", ImmutableList.of("foouser"), "emails", ImmutableList.of("foo@bar.com")));
    when(stream2.getId()).thenReturn(matchingStreamId1);
    final Stream stream3 = mock(Stream.class);
    when(stream3.getAlertReceivers()).thenReturn(ImmutableMap.of("users", ImmutableList.of("foouser2")));
    when(stream3.getId()).thenReturn(matchingStreamId2);
    when(this.streamService.loadAll()).thenReturn(ImmutableList.of(stream1, stream2, stream3));
    final AlertCondition alertCondition1 = mock(AlertCondition.class);
    final AlertCondition alertCondition2 = mock(AlertCondition.class);
    when(this.streamService.getAlertConditions(eq(stream2))).thenReturn(ImmutableList.of(alertCondition1));
    when(this.streamService.getAlertConditions(eq(stream3))).thenReturn(ImmutableList.of(alertCondition2));
    final String alarmCallbackId1 = new ObjectId().toHexString();
    final AlarmCallbackConfiguration alarmCallback1 = AlarmCallbackConfigurationImpl.create(alarmCallbackId1, matchingStreamId1, EmailAlarmCallback.class.getCanonicalName(), "Email Alert Notification", new HashMap<>(), new Date(), "admin");
    final String alarmCallbackId2 = new ObjectId().toHexString();
    final AlarmCallbackConfiguration alarmCallback2 = AlarmCallbackConfigurationImpl.create(alarmCallbackId2, matchingStreamId2, EmailAlarmCallback.class.getCanonicalName(), "Email Alert Notification", new HashMap<>(), new Date(), "admin");
    final String alarmCallbackId3 = new ObjectId().toHexString();
    final AlarmCallbackConfiguration alarmCallback3 = AlarmCallbackConfigurationImpl.create(alarmCallbackId3, matchingStreamId2, EmailAlarmCallback.class.getCanonicalName(), "Email Alert Notification", new HashMap<>(), new Date(), "admin");
    final String alarmCallbackId4 = new ObjectId().toHexString();
    final AlarmCallbackConfiguration alarmCallback4 = AlarmCallbackConfigurationImpl.create(alarmCallbackId4, matchingStreamId2, HTTPAlarmCallback.class.getCanonicalName(), "Email Alert Notification", new HashMap<>(), new Date(), "admin");
    when(alarmCallbackConfigurationService.getForStream(eq(stream2))).thenReturn(ImmutableList.of(alarmCallback1));
    when(alarmCallbackConfigurationService.getForStream(eq(stream3))).thenReturn(ImmutableList.of(alarmCallback2, alarmCallback3, alarmCallback4));
    when(alarmCallbackConfigurationService.save(eq(alarmCallback1))).thenReturn(alarmCallbackId1);
    when(alarmCallbackConfigurationService.save(eq(alarmCallback2))).thenReturn(alarmCallbackId2);
    when(alarmCallbackConfigurationService.save(eq(alarmCallback3))).thenReturn(alarmCallbackId3);
    when(this.dbCollection.update(any(BasicDBObject.class), any(BasicDBObject.class))).thenReturn(new WriteResult(1, true, matchingStreamId1));
    when(this.dbCollection.update(any(BasicDBObject.class), any(BasicDBObject.class))).thenReturn(new WriteResult(1, true, matchingStreamId2));
    this.alertReceiversMigration.upgrade();
    final ArgumentCaptor<AlarmCallbackConfiguration> configurationArgumentCaptor = ArgumentCaptor.forClass(AlarmCallbackConfiguration.class);
    verify(this.alarmCallbackConfigurationService, times(3)).save(configurationArgumentCaptor.capture());
    final List<AlarmCallbackConfiguration> configurationValues = configurationArgumentCaptor.getAllValues();
    assertThat(configurationValues).isNotNull().isNotEmpty().hasSize(3).contains(alarmCallback1).contains(alarmCallback2).contains(alarmCallback3);
    for (AlarmCallbackConfiguration configurationValue : configurationValues) {
        if (configurationValue.getStreamId().equals(matchingStreamId1)) {
            assertThat(((List) configurationValue.getConfiguration().get(EmailAlarmCallback.CK_EMAIL_RECEIVERS)).size()).isEqualTo(1);
            assertThat(((List) configurationValue.getConfiguration().get(EmailAlarmCallback.CK_EMAIL_RECEIVERS)).get(0)).isEqualTo("foo@bar.com");
            assertThat(((List) configurationValue.getConfiguration().get(EmailAlarmCallback.CK_USER_RECEIVERS)).size()).isEqualTo(1);
            assertThat(((List) configurationValue.getConfiguration().get(EmailAlarmCallback.CK_USER_RECEIVERS)).get(0)).isEqualTo("foouser");
        }
        if (configurationValue.getStreamId().equals(matchingStreamId2)) {
            assertThat(configurationValue.getConfiguration().get(EmailAlarmCallback.CK_EMAIL_RECEIVERS)).isNull();
            assertThat(((List) configurationValue.getConfiguration().get(EmailAlarmCallback.CK_USER_RECEIVERS)).size()).isEqualTo(1);
            assertThat(((List) configurationValue.getConfiguration().get(EmailAlarmCallback.CK_USER_RECEIVERS)).get(0)).isEqualTo("foouser2");
        }
    }
    final ArgumentCaptor<BasicDBObject> queryCaptor = ArgumentCaptor.forClass(BasicDBObject.class);
    final ArgumentCaptor<BasicDBObject> updateCaptor = ArgumentCaptor.forClass(BasicDBObject.class);
    verify(this.dbCollection, times(2)).update(queryCaptor.capture(), updateCaptor.capture());
    final List<BasicDBObject> queries = queryCaptor.getAllValues();
    for (BasicDBObject query : queries) {
        final String streamId = (queries.indexOf(query) == 0 ? matchingStreamId1 : matchingStreamId2);
        assertThat(query.toJson()).isEqualTo("{ \"_id\" : { \"$oid\" : \"" + streamId + "\" } }");
    }
    updateCaptor.getAllValues().forEach(update -> assertThat(update.toJson()).isEqualTo("{ \"$unset\" : { \"" + StreamImpl.FIELD_ALERT_RECEIVERS + "\" : \"\" } }"));
    verifyMigrationCompletedWasPosted(ImmutableMap.of(matchingStreamId1, Optional.of(alarmCallbackId1), matchingStreamId2, Optional.of(alarmCallbackId2 + ", " + alarmCallbackId3)));
}
Also used : ObjectId(org.bson.types.ObjectId) Date(java.util.Date) BasicDBObject(com.mongodb.BasicDBObject) HTTPAlarmCallback(org.graylog2.alarmcallbacks.HTTPAlarmCallback) WriteResult(com.mongodb.WriteResult) AlertCondition(org.graylog2.plugin.alarms.AlertCondition) Stream(org.graylog2.plugin.streams.Stream) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) EmailAlarmCallback(org.graylog2.alarmcallbacks.EmailAlarmCallback) AlarmCallbackConfiguration(org.graylog2.alarmcallbacks.AlarmCallbackConfiguration) Test(org.junit.Test)

Example 68 with ObjectId

use of org.bson.types.ObjectId in project graylog2-server by Graylog2.

the class V20161125161400_AlertReceiversMigrationTest method doMigrateSingleQualifyingStream.

@Test
public void doMigrateSingleQualifyingStream() throws Exception {
    final String matchingStreamId = new ObjectId().toHexString();
    final Stream stream1 = mock(Stream.class);
    when(stream1.getAlertReceivers()).thenReturn(Collections.emptyMap());
    final Stream stream2 = mock(Stream.class);
    when(stream2.getAlertReceivers()).thenReturn(ImmutableMap.of("users", ImmutableList.of("foouser"), "emails", ImmutableList.of("foo@bar.com")));
    when(stream2.getId()).thenReturn(matchingStreamId);
    when(this.streamService.loadAll()).thenReturn(ImmutableList.of(stream1, stream2));
    final AlertCondition alertCondition = mock(AlertCondition.class);
    when(this.streamService.getAlertConditions(eq(stream2))).thenReturn(ImmutableList.of(alertCondition));
    final String alarmCallbackId = new ObjectId().toHexString();
    final AlarmCallbackConfiguration alarmCallback = AlarmCallbackConfigurationImpl.create(alarmCallbackId, matchingStreamId, EmailAlarmCallback.class.getCanonicalName(), "Email Alert Notification", new HashMap<>(), new Date(), "admin");
    when(alarmCallbackConfigurationService.getForStream(eq(stream2))).thenReturn(ImmutableList.of(alarmCallback));
    when(alarmCallbackConfigurationService.save(eq(alarmCallback))).thenReturn(alarmCallbackId);
    when(this.dbCollection.update(any(BasicDBObject.class), any(BasicDBObject.class))).thenReturn(new WriteResult(1, true, matchingStreamId));
    this.alertReceiversMigration.upgrade();
    final ArgumentCaptor<AlarmCallbackConfiguration> configurationArgumentCaptor = ArgumentCaptor.forClass(AlarmCallbackConfiguration.class);
    verify(this.alarmCallbackConfigurationService, times(1)).save(configurationArgumentCaptor.capture());
    final AlarmCallbackConfiguration updatedConfiguration = configurationArgumentCaptor.getValue();
    assertThat(updatedConfiguration).isEqualTo(alarmCallback);
    assertThat(updatedConfiguration.getType()).isEqualTo(EmailAlarmCallback.class.getCanonicalName());
    assertThat(((List) updatedConfiguration.getConfiguration().get(EmailAlarmCallback.CK_EMAIL_RECEIVERS)).size()).isEqualTo(1);
    assertThat(((List) updatedConfiguration.getConfiguration().get(EmailAlarmCallback.CK_EMAIL_RECEIVERS)).get(0)).isEqualTo("foo@bar.com");
    assertThat(((List) updatedConfiguration.getConfiguration().get(EmailAlarmCallback.CK_USER_RECEIVERS)).size()).isEqualTo(1);
    assertThat(((List) updatedConfiguration.getConfiguration().get(EmailAlarmCallback.CK_USER_RECEIVERS)).get(0)).isEqualTo("foouser");
    final ArgumentCaptor<BasicDBObject> queryCaptor = ArgumentCaptor.forClass(BasicDBObject.class);
    final ArgumentCaptor<BasicDBObject> updateCaptor = ArgumentCaptor.forClass(BasicDBObject.class);
    verify(this.dbCollection, times(1)).update(queryCaptor.capture(), updateCaptor.capture());
    assertThat(queryCaptor.getValue().toJson()).isEqualTo("{ \"_id\" : { \"$oid\" : \"" + matchingStreamId + "\" } }");
    assertThat(updateCaptor.getValue().toJson()).isEqualTo("{ \"$unset\" : { \"" + StreamImpl.FIELD_ALERT_RECEIVERS + "\" : \"\" } }");
    verifyMigrationCompletedWasPosted(ImmutableMap.of(matchingStreamId, Optional.of(alarmCallbackId)));
}
Also used : ObjectId(org.bson.types.ObjectId) Date(java.util.Date) BasicDBObject(com.mongodb.BasicDBObject) WriteResult(com.mongodb.WriteResult) AlertCondition(org.graylog2.plugin.alarms.AlertCondition) Stream(org.graylog2.plugin.streams.Stream) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) EmailAlarmCallback(org.graylog2.alarmcallbacks.EmailAlarmCallback) AlarmCallbackConfiguration(org.graylog2.alarmcallbacks.AlarmCallbackConfiguration) Test(org.junit.Test)

Example 69 with ObjectId

use of org.bson.types.ObjectId in project graylog2-server by Graylog2.

the class StreamRuleServiceImpl method streamRuleCountByStream.

@Override
public Map<String, Long> streamRuleCountByStream() {
    final DBCursor streamIds = collection(StreamImpl.class).find(new BasicDBObject(), new BasicDBObject("_id", 1));
    final Map<String, Long> streamRules = new HashMap<>(streamIds.size());
    for (DBObject keys : streamIds) {
        final ObjectId streamId = (ObjectId) keys.get("_id");
        streamRules.put(streamId.toHexString(), streamRuleCount(streamId));
    }
    return streamRules;
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) DBCursor(com.mongodb.DBCursor) HashMap(java.util.HashMap) ObjectId(org.bson.types.ObjectId) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject)

Example 70 with ObjectId

use of org.bson.types.ObjectId in project graylog2-server by Graylog2.

the class StreamRuleServiceImpl method loadForStreamId.

@Override
public List<StreamRule> loadForStreamId(String streamId) throws NotFoundException {
    ObjectId id = new ObjectId(streamId);
    final List<StreamRule> streamRules = new ArrayList<>();
    final List<DBObject> respStreamRules = query(StreamRuleImpl.class, new BasicDBObject(StreamRuleImpl.FIELD_STREAM_ID, id));
    for (DBObject streamRule : respStreamRules) {
        streamRules.add(toStreamRule(streamRule));
    }
    return streamRules;
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) ObjectId(org.bson.types.ObjectId) StreamRule(org.graylog2.plugin.streams.StreamRule) ArrayList(java.util.ArrayList) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject)

Aggregations

ObjectId (org.bson.types.ObjectId)249 Test (org.junit.Test)157 BasicDBObject (com.mongodb.BasicDBObject)54 Document (org.bson.Document)38 DBObject (com.mongodb.DBObject)35 ArrayList (java.util.ArrayList)28 BsonObjectId (org.bson.BsonObjectId)27 Date (java.util.Date)24 DBRef (com.mongodb.DBRef)15 List (java.util.List)15 StreamRuleMock (org.graylog2.streams.matchers.StreamRuleMock)14 Message (org.graylog2.plugin.Message)13 BasicBSONObject (org.bson.BasicBSONObject)12 Query (org.springframework.data.mongodb.core.query.Query)11 GridFSFile (com.mongodb.client.gridfs.model.GridFSFile)10 Map (java.util.Map)10 Binary (org.bson.types.Binary)10 GridFSFindIterable (com.mongodb.client.gridfs.GridFSFindIterable)8 UsingDataSet (com.lordofthejars.nosqlunit.annotation.UsingDataSet)7 Code (org.bson.types.Code)7