/graylog2-server/src/main/java/org/graylog/plugins/views/search/validation/QueryValidationServiceImpl.java

https://github.com/Graylog2/graylog2-server · Java · 70 lines · 42 code · 12 blank · 16 comment · 1 complexity · fb7913ffc36b2c02afb3eb58fec2d614 MD5 · raw file

  1. /*
  2. * Copyright (C) 2020 Graylog, Inc.
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the Server Side Public License, version 1,
  6. * as published by MongoDB, Inc.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * Server Side Public License for more details.
  12. *
  13. * You should have received a copy of the Server Side Public License
  14. * along with this program. If not, see
  15. * <http://www.mongodb.com/licensing/server-side-public-license>.
  16. */
  17. package org.graylog.plugins.views.search.validation;
  18. import org.graylog.plugins.views.search.validation.validators.ValidationErrors;
  19. import org.graylog2.indexer.fieldtypes.MappedFieldTypesService;
  20. import javax.inject.Inject;
  21. import javax.inject.Singleton;
  22. import java.util.List;
  23. import java.util.Set;
  24. import java.util.stream.Collectors;
  25. @Singleton
  26. public class QueryValidationServiceImpl implements QueryValidationService {
  27. private final LuceneQueryParser luceneQueryParser;
  28. private final MappedFieldTypesService fields;
  29. private final Set<QueryValidator> validators;
  30. @Inject
  31. public QueryValidationServiceImpl(LuceneQueryParser luceneQueryParser,
  32. MappedFieldTypesService fields,
  33. Set<QueryValidator> validators) {
  34. this.luceneQueryParser = luceneQueryParser;
  35. this.fields = fields;
  36. this.validators = validators;
  37. }
  38. @Override
  39. public ValidationResponse validate(ValidationRequest req) {
  40. if (req.isEmptyQuery()) {
  41. return ValidationResponse.ok();
  42. }
  43. try {
  44. final ParsedQuery parsedQuery = luceneQueryParser.parse(req.rawQuery());
  45. final ValidationContext context = ValidationContext.builder()
  46. .request(req)
  47. .query(parsedQuery)
  48. .availableFields(fields.fieldTypesByStreamIds(req.streams(), req.timerange()))
  49. .build();
  50. final List<ValidationMessage> explanations = validators.stream()
  51. .flatMap(val -> val.validate(context).stream())
  52. .collect(Collectors.toList());
  53. return ValidationResponse.withDetectedStatus(explanations);
  54. } catch (Exception e) {
  55. return ValidationResponse.error(ValidationErrors.create(e));
  56. }
  57. }
  58. }