Search in sources :

Example 36 with ValidationException

use of org.graylog2.plugin.database.ValidationException in project graylog2-server by Graylog2.

the class EsNodeProviderTest method setupConfig.

private ElasticsearchConfiguration setupConfig(Map<String, String> settings) {
    // required params we don't care about in this test, so we set them to dummy values for all test cases
    settings.put("retention_strategy", "delete");
    ElasticsearchConfiguration configuration = new ElasticsearchConfiguration();
    try {
        new JadConfig(new InMemoryRepository(settings), configuration).process();
    } catch (ValidationException | RepositoryException e) {
        fail(e.getMessage());
    }
    return configuration;
}
Also used : JadConfig(com.github.joschi.jadconfig.JadConfig) InMemoryRepository(com.github.joschi.jadconfig.repositories.InMemoryRepository) ValidationException(com.github.joschi.jadconfig.ValidationException) ElasticsearchConfiguration(org.graylog2.configuration.ElasticsearchConfiguration) RepositoryException(com.github.joschi.jadconfig.RepositoryException)

Example 37 with ValidationException

use of org.graylog2.plugin.database.ValidationException in project graylog2-server by Graylog2.

the class ConfigurationMapConverter method convertValues.

/**
     * Converts the values in the map to the requested types. This has been copied from the Graylog web interface
     * and should be removed once we have better configuration objects.
     */
public static Map<String, Object> convertValues(final Map<String, Object> data, final ConfigurationRequest configurationRequest) throws ValidationException {
    final Map<String, Object> configuration = Maps.newHashMapWithExpectedSize(data.size());
    final Map<String, Map<String, Object>> configurationFields = configurationRequest.asList();
    for (final Map.Entry<String, Object> entry : data.entrySet()) {
        final String field = entry.getKey();
        final Map<String, Object> fieldDescription = configurationFields.get(field);
        if (fieldDescription == null || fieldDescription.isEmpty()) {
            throw new ValidationException(field, "Unknown configuration field description for field \"" + field + "\"");
        }
        final String type = (String) fieldDescription.get("type");
        // Decide what to cast to. (string, bool, number)
        Object value;
        switch(type) {
            case "text":
            case "dropdown":
                value = entry.getValue() == null ? "" : String.valueOf(entry.getValue());
                break;
            case "number":
                try {
                    value = Integer.parseInt(String.valueOf(entry.getValue()));
                } catch (NumberFormatException e) {
                    // If a numeric field is optional and not provided, use null as value
                    if ("true".equals(String.valueOf(fieldDescription.get("is_optional")))) {
                        value = null;
                    } else {
                        throw new ValidationException(field, e.getMessage());
                    }
                }
                break;
            case "boolean":
                value = "true".equalsIgnoreCase(String.valueOf(entry.getValue()));
                break;
            case "list":
                final List<?> valueList = entry.getValue() == null ? Collections.emptyList() : (List<?>) entry.getValue();
                value = valueList.stream().filter(o -> o != null && o instanceof String).map(String::valueOf).collect(Collectors.toList());
                break;
            default:
                throw new ValidationException(field, "Unknown configuration field type \"" + type + "\"");
        }
        configuration.put(field, value);
    }
    return configuration;
}
Also used : ConfigurationRequest(org.graylog2.plugin.configuration.ConfigurationRequest) List(java.util.List) ValidationException(org.graylog2.plugin.database.ValidationException) Map(java.util.Map) Maps(com.google.common.collect.Maps) Collections(java.util.Collections) Collectors(java.util.stream.Collectors) ValidationException(org.graylog2.plugin.database.ValidationException) Map(java.util.Map)

Example 38 with ValidationException

use of org.graylog2.plugin.database.ValidationException in project graylog2-server by Graylog2.

the class PersistedServiceImpl method embed.

protected <T extends Persisted> void embed(T model, String key, EmbeddedPersistable o) throws ValidationException {
    Map<String, List<ValidationResult>> errors = validate(model.getEmbeddedValidations(key), o.getPersistedFields());
    if (!errors.isEmpty()) {
        throw new ValidationException(errors);
    }
    Map<String, Object> fields = Maps.newHashMap(o.getPersistedFields());
    fieldTransformations(fields);
    BasicDBObject dbo = new BasicDBObject(fields);
    collection(model).update(new BasicDBObject("_id", new ObjectId(model.getId())), new BasicDBObject("$push", new BasicDBObject(key, dbo)));
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) ValidationException(org.graylog2.plugin.database.ValidationException) ObjectId(org.bson.types.ObjectId) ArrayList(java.util.ArrayList) List(java.util.List) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject)

Example 39 with ValidationException

use of org.graylog2.plugin.database.ValidationException in project graylog2-server by Graylog2.

the class PersistedServiceImpl method save.

@Override
public <T extends Persisted> String save(T model) throws ValidationException {
    Map<String, List<ValidationResult>> errors = validate(model, model.getFields());
    if (!errors.isEmpty()) {
        throw new ValidationException(errors);
    }
    BasicDBObject doc = new BasicDBObject(model.getFields());
    // ID was created in constructor or taken from original doc already.
    doc.put("_id", new ObjectId(model.getId()));
    // Do field transformations
    fieldTransformations(doc);
    /*
         * We are running an upsert. This means that the existing
		 * document will be updated if the ID already exists and
		 * a new document will be created if it doesn't.
		 */
    BasicDBObject q = new BasicDBObject("_id", new ObjectId(model.getId()));
    collection(model).update(q, doc, true, false);
    return model.getId();
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) ValidationException(org.graylog2.plugin.database.ValidationException) ObjectId(org.bson.types.ObjectId) ArrayList(java.util.ArrayList) List(java.util.List)

Example 40 with ValidationException

use of org.graylog2.plugin.database.ValidationException in project graylog2-server by Graylog2.

the class DashboardWidgetsResource method addWidget.

@POST
@Timed
@ApiOperation(value = "Add a widget to a dashboard")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = 404, message = "Dashboard not found."), @ApiResponse(code = 400, message = "Validation error."), @ApiResponse(code = 400, message = "No such widget type.") })
@AuditEvent(type = AuditEventTypes.DASHBOARD_WIDGET_CREATE)
public Response addWidget(@ApiParam(name = "dashboardId", required = true) @PathParam("dashboardId") String dashboardId, @ApiParam(name = "JSON body", required = true) AddWidgetRequest awr) throws ValidationException, NotFoundException {
    checkPermission(RestPermissions.DASHBOARDS_EDIT, dashboardId);
    // Bind to streams for reader users and check stream permission.
    if (awr.config().containsKey("stream_id")) {
        checkPermission(RestPermissions.STREAMS_READ, (String) awr.config().get("stream_id"));
    } else {
        checkPermission(RestPermissions.SEARCHES_ABSOLUTE);
        checkPermission(RestPermissions.SEARCHES_RELATIVE);
        checkPermission(RestPermissions.SEARCHES_KEYWORD);
    }
    final DashboardWidget widget;
    try {
        widget = dashboardWidgetCreator.fromRequest(awr, getCurrentUser().getName());
        final Dashboard dashboard = dashboardService.load(dashboardId);
        dashboardService.addWidget(dashboard, widget);
    } catch (DashboardWidget.NoSuchWidgetTypeException e2) {
        LOG.debug("No such widget type.", e2);
        throw new BadRequestException("No such widget type.", e2);
    } catch (InvalidRangeParametersException e3) {
        LOG.debug("Invalid timerange parameters provided.", e3);
        throw new BadRequestException("Invalid timerange parameters provided.", e3);
    } catch (InvalidWidgetConfigurationException e4) {
        LOG.debug("Invalid widget configuration.", e4);
        throw new BadRequestException("Invalid widget configuration.", e4);
    }
    final Map<String, String> result = ImmutableMap.of("widget_id", widget.getId());
    final URI widgetUri = getUriBuilderToSelf().path(DashboardWidgetsResource.class, "getWidget").build(dashboardId, widget.getId());
    return Response.created(widgetUri).entity(result).build();
}
Also used : InvalidRangeParametersException(org.graylog2.plugin.indexer.searches.timeranges.InvalidRangeParametersException) DashboardWidget(org.graylog2.dashboards.widgets.DashboardWidget) Dashboard(org.graylog2.dashboards.Dashboard) BadRequestException(javax.ws.rs.BadRequestException) InvalidWidgetConfigurationException(org.graylog2.dashboards.widgets.InvalidWidgetConfigurationException) URI(java.net.URI) 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) AuditEvent(org.graylog2.audit.jersey.AuditEvent) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

ApiOperation (io.swagger.annotations.ApiOperation)47 AuditEvent (org.graylog2.audit.jersey.AuditEvent)47 Timed (com.codahale.metrics.annotation.Timed)36 ValidationException (org.graylog2.plugin.database.ValidationException)32 ApiResponses (io.swagger.annotations.ApiResponses)29 Path (javax.ws.rs.Path)29 BadRequestException (javax.ws.rs.BadRequestException)25 PUT (javax.ws.rs.PUT)24 Produces (javax.ws.rs.Produces)23 Consumes (javax.ws.rs.Consumes)22 POST (javax.ws.rs.POST)21 URI (java.net.URI)18 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)13 Stream (org.graylog2.plugin.streams.Stream)12 User (org.graylog2.plugin.database.users.User)11 MessageInput (org.graylog2.plugin.inputs.MessageInput)11 NotFoundException (org.graylog2.database.NotFoundException)10 List (java.util.List)7 NoAuditEvent (org.graylog2.audit.jersey.NoAuditEvent)7 Dashboard (org.graylog2.dashboards.Dashboard)7