Multiline.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package info.fetter.logstashforwarder;
  2. /*
  3. * Copyright 2015 Didier Fetter
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. import java.io.UnsupportedEncodingException;
  19. import java.util.Map;
  20. import java.util.regex.Pattern;
  21. import org.apache.commons.lang.builder.ToStringBuilder;
  22. public class Multiline {
  23. public enum WhatType { Previous, Next };
  24. public static byte JOINT = (byte) ' ';
  25. private Pattern pattern = null;
  26. private boolean negate = false;
  27. private WhatType what = WhatType.Previous;
  28. public Multiline() {
  29. }
  30. public Multiline(Multiline event) {
  31. if(event != null) {
  32. this.negate = event.negate;
  33. this.pattern = event.pattern;
  34. this.what = event.what;
  35. }
  36. }
  37. public Multiline(Map<String,String> fields) throws UnsupportedEncodingException {
  38. String strPattern = "";
  39. for(String key : fields.keySet()) {
  40. if ("pattern".equals(key))
  41. strPattern = fields.get(key);
  42. else if ("negate".equals(key))
  43. negate = Boolean.parseBoolean(fields.get(key));
  44. else if ("what".equals(key))
  45. what = WhatType.valueOf(fields.get(key));
  46. else
  47. throw new UnsupportedEncodingException(key + " not supported");
  48. }
  49. pattern = Pattern.compile(strPattern);
  50. }
  51. public Pattern getPattern() {
  52. return pattern;
  53. }
  54. public boolean isNegate() {
  55. return negate;
  56. }
  57. public WhatType getWhat() {
  58. return what;
  59. }
  60. public boolean isPrevious() {
  61. return what == WhatType.Previous;
  62. }
  63. public boolean isPatternFound (byte[] line) {
  64. boolean result = pattern.matcher(new String(line)).find();
  65. if (negate) return !result;
  66. return result;
  67. }
  68. @Override
  69. public String toString() {
  70. return new ToStringBuilder(this).
  71. append("pattern", pattern).
  72. append("negate", negate).
  73. append("what", what).
  74. toString();
  75. }
  76. }