http://git-wip-us.apache.org/repos/asf/metron/blob/a5b13777/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/ComparisonOperatorsEvaluatorTest.java ---------------------------------------------------------------------- diff --git a/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/ComparisonOperatorsEvaluatorTest.java b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/ComparisonOperatorsEvaluatorTest.java new file mode 100644 index 0000000..8afc234 --- /dev/null +++ b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/ComparisonOperatorsEvaluatorTest.java @@ -0,0 +1,446 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.metron.stellar.common.evaluators; + +import org.antlr.v4.runtime.tree.TerminalNode; +import org.apache.metron.stellar.dsl.ParseException; +import org.apache.metron.stellar.dsl.Token; +import org.apache.metron.stellar.common.generated.StellarParser; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.io.Serializable; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@SuppressWarnings("ALL") +public class ComparisonOperatorsEvaluatorTest { + @Rule + public final ExpectedException exception = ExpectedException.none(); + + ComparisonExpressionEvaluator evaluator; + + @Before + public void setUp() throws Exception { + evaluator = new ComparisonOperatorsEvaluator(); + } + + @Test + public void nonSupportedOperatorThrowsExceptionNonNumbericComparable() throws Exception { + Token<String> left = mock(Token.class); + when(left.getValue()).thenReturn("b"); + + Token<String> right = mock(Token.class); + when(right.getValue()).thenReturn("a"); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + + exception.expect(ParseException.class); + exception.expectMessage("Unsupported operator: " + op); + + evaluator.evaluate(left, right, op); + } + + @Test + public void nonSupportedOperatorThrowsExceptionNumbericComparison() throws Exception { + Token<Long> left = mock(Token.class); + when(left.getValue()).thenReturn(1L); + + Token<Long> right = mock(Token.class); + when(right.getValue()).thenReturn(0L); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + + exception.expect(ParseException.class); + exception.expectMessage("Unsupported operator: " + op); + + evaluator.evaluate(left, right, op); + } + + @Test + public void leftIsNullThenThrowException() throws Exception { + Token<Long> left = mock(Token.class); + Token<Long> right = mock(Token.class); + when(right.getValue()).thenReturn(1L); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LT()).thenReturn(mock(TerminalNode.class)); + + assertFalse(evaluator.evaluate(left, right, op)); + } + + @Test + public void rightIsNullThenReturnFalse() throws Exception { + Token<Long> left = mock(Token.class); + when(left.getValue()).thenReturn(1L); + Token<Long> right = mock(Token.class); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LT()).thenReturn(mock(TerminalNode.class)); + + assertFalse(evaluator.evaluate(left, right, op)); + } + + @Test + public void rightAndLeftIsNullThenReturnFalse() throws Exception { + Token<Long> left = mock(Token.class); + Token<Long> right = mock(Token.class); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LT()).thenReturn(mock(TerminalNode.class)); + + assertFalse(evaluator.evaluate(left, right, op)); + } + + @Test + public void throwParseExceptionWhenTryingToCompareNonComparable() throws Exception { + exception.expect(ParseException.class); + exception.expectMessage("Unsupported operations. The following expression is invalid: "); + + Token<Serializable> left = mock(Token.class); + when(left.getValue()).thenReturn(mock(Serializable.class)); + + Token<Serializable> right = mock(Token.class); + when(right.getValue()).thenReturn(mock(Serializable.class)); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LT()).thenReturn(mock(TerminalNode.class)); + + evaluator.evaluate(left, right, op); + } + + @Test + public void makeSureAllOperatorsProperlyWorkForLongs() throws Exception { + Token<Long> left = mock(Token.class); + when(left.getValue()).thenReturn(0L); + + Token<Long> right = mock(Token.class); + when(right.getValue()).thenReturn(1L); + + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LT()).thenReturn(mock(TerminalNode.class)); + assertTrue(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LTE()).thenReturn(mock(TerminalNode.class)); + assertTrue(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GT()).thenReturn(mock(TerminalNode.class)); + assertFalse(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GTE()).thenReturn(mock(TerminalNode.class)); + assertFalse(evaluator.evaluate(left, right, op)); + } + } + + @Test + public void makeSureAllOperatorsProperlyWorkForDoubles() throws Exception { + Token<Double> left = mock(Token.class); + when(left.getValue()).thenReturn(0D); + + Token<Double> right = mock(Token.class); + when(right.getValue()).thenReturn(1D); + + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LT()).thenReturn(mock(TerminalNode.class)); + assertTrue(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LTE()).thenReturn(mock(TerminalNode.class)); + assertTrue(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GT()).thenReturn(mock(TerminalNode.class)); + assertFalse(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GTE()).thenReturn(mock(TerminalNode.class)); + assertFalse(evaluator.evaluate(left, right, op)); + } + } + + @Test + public void makeSureAllOperatorsProperlyWorkForFloats() throws Exception { + Token<Float> left = mock(Token.class); + when(left.getValue()).thenReturn(0F); + + Token<Float> right = mock(Token.class); + when(right.getValue()).thenReturn(1F); + + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LT()).thenReturn(mock(TerminalNode.class)); + assertTrue(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LTE()).thenReturn(mock(TerminalNode.class)); + assertTrue(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GT()).thenReturn(mock(TerminalNode.class)); + assertFalse(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GTE()).thenReturn(mock(TerminalNode.class)); + assertFalse(evaluator.evaluate(left, right, op)); + } + } + + @Test + public void makeSureAllOperatorsProperlyWorkForInts() throws Exception { + Token<Integer> left = mock(Token.class); + when(left.getValue()).thenReturn(0); + + Token<Integer> right = mock(Token.class); + when(right.getValue()).thenReturn(1); + + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LT()).thenReturn(mock(TerminalNode.class)); + assertTrue(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LTE()).thenReturn(mock(TerminalNode.class)); + assertTrue(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GT()).thenReturn(mock(TerminalNode.class)); + assertFalse(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GTE()).thenReturn(mock(TerminalNode.class)); + assertFalse(evaluator.evaluate(left, right, op)); + } + } + + @Test + public void makeSureAllOperatorsWorkForMixedTypesDoublesLong() throws Exception { + Token<Long> left = mock(Token.class); + when(left.getValue()).thenReturn(1L); + + Token<Double> right = mock(Token.class); + when(right.getValue()).thenReturn(1.0000001D); + + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LT()).thenReturn(mock(TerminalNode.class)); + assertTrue(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LTE()).thenReturn(mock(TerminalNode.class)); + assertTrue(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GT()).thenReturn(mock(TerminalNode.class)); + assertFalse(evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GTE()).thenReturn(mock(TerminalNode.class)); + assertFalse(evaluator.evaluate(left, right, op)); + } + } + + @Test + public void makeSureAllOperatorsWorkForMixedTypesDoublesFloat() throws Exception { + final double leftValue = 1.0000001D; + final float rightValue = 1.0000001F; + + Token<Double> left = mock(Token.class); + when(left.getValue()).thenReturn(leftValue); + + Token<Float> right = mock(Token.class); + when(right.getValue()).thenReturn(rightValue); + + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LT()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue < rightValue, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LTE()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue <= rightValue, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GT()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue > rightValue, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GTE()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue >= rightValue, evaluator.evaluate(left, right, op)); + } + } + + @Test + public void makeSureAllOperatorsWorkForMixedTypesFloatIntegers() throws Exception { + final int leftValue = 1; + final float rightValue = 1.0000001F; + + Token<Integer> left = mock(Token.class); + when(left.getValue()).thenReturn(leftValue); + + Token<Float> right = mock(Token.class); + when(right.getValue()).thenReturn(rightValue); + + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LT()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue < rightValue, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LTE()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue <= rightValue, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GT()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue > rightValue, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GTE()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue >= rightValue, evaluator.evaluate(left, right, op)); + } + } + + @Test + public void makeSureAllOperatorsWorkForMixedTypesFloatIntegers2() throws Exception { + final int leftValue = 1; + final float rightValue = 1.00000001F; + + Token<Integer> left = mock(Token.class); + when(left.getValue()).thenReturn(leftValue); + + Token<Float> right = mock(Token.class); + when(right.getValue()).thenReturn(rightValue); + + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LT()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue < rightValue, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LTE()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue <= rightValue, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GT()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue > rightValue, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GTE()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue >= rightValue, evaluator.evaluate(left, right, op)); + } + } + + @Test + public void makeSureAllOperatorsWorkForMixedTypesLongIntegers() throws Exception { + final int leftValue = 1; + final long rightValue = 3L; + + Token<Integer> left = mock(Token.class); + when(left.getValue()).thenReturn(leftValue); + + Token<Long> right = mock(Token.class); + when(right.getValue()).thenReturn(rightValue); + + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LT()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue < rightValue, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LTE()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue <= rightValue, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GT()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue > rightValue, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GTE()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue >= rightValue, evaluator.evaluate(left, right, op)); + } + } + + @Test + public void makeSureAllOperatorsWorkForNonIntegerComparableTypes() throws Exception { + final String leftValue = "a"; + final String rightValue = "b"; + + Token<String> left = mock(Token.class); + when(left.getValue()).thenReturn(leftValue); + + Token<String> right = mock(Token.class); + when(right.getValue()).thenReturn(rightValue); + + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LT()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue.compareTo(rightValue) < 0, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.LTE()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue.compareTo(rightValue) <= 0, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GT()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue.compareTo(rightValue) > 0, evaluator.evaluate(left, right, op)); + } + { + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.GTE()).thenReturn(mock(TerminalNode.class)); + assertEquals(leftValue.compareTo(rightValue) >= 0, evaluator.evaluate(left, right, op)); + } + } +}
http://git-wip-us.apache.org/repos/asf/metron/blob/a5b13777/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/DoubleLiteralEvaluatorTest.java ---------------------------------------------------------------------- diff --git a/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/DoubleLiteralEvaluatorTest.java b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/DoubleLiteralEvaluatorTest.java new file mode 100644 index 0000000..44c48d0 --- /dev/null +++ b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/DoubleLiteralEvaluatorTest.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.metron.stellar.common.evaluators; + +import org.apache.metron.stellar.dsl.Token; +import org.apache.metron.stellar.common.generated.StellarParser; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + +public class DoubleLiteralEvaluatorTest { + @Rule + public final ExpectedException exception = ExpectedException.none(); + + NumberEvaluator<StellarParser.DoubleLiteralContext> evaluator; + StellarParser.DoubleLiteralContext context; + + @Before + public void setUp() throws Exception { + evaluator = new DoubleLiteralEvaluator(); + context = mock(StellarParser.DoubleLiteralContext.class); + } + + @Test + public void verifyHappyPathEvaluation() throws Exception { + when(context.getText()).thenReturn("100D"); + + Token<? extends Number> evaluated = evaluator.evaluate(context, null); + assertEquals(new Token<>(100D, Double.class, null), evaluated); + + verify(context).getText(); + verifyNoMoreInteractions(context); + } + + @Test + public void verifyNumberFormationExceptionWithEmptyString() throws Exception { + exception.expect(NumberFormatException.class); + + when(context.getText()).thenReturn(""); + evaluator.evaluate(context, null); + } + + @Test + public void throwIllegalArgumentExceptionWhenContextIsNull() throws Exception { + exception.expect(IllegalArgumentException.class); + exception.expectMessage("Cannot evaluate a context that is null."); + + evaluator.evaluate(null, null); + } +} http://git-wip-us.apache.org/repos/asf/metron/blob/a5b13777/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/EqualityOperatorsEvaluatorTest.java ---------------------------------------------------------------------- diff --git a/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/EqualityOperatorsEvaluatorTest.java b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/EqualityOperatorsEvaluatorTest.java new file mode 100644 index 0000000..34708ff --- /dev/null +++ b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/EqualityOperatorsEvaluatorTest.java @@ -0,0 +1,186 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.metron.stellar.common.evaluators; + +import org.antlr.v4.runtime.tree.TerminalNode; +import org.apache.metron.stellar.dsl.Token; +import org.apache.metron.stellar.common.generated.StellarParser; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked"}) +public class EqualityOperatorsEvaluatorTest { + ComparisonExpressionEvaluator evaluator; + + @Before + public void setUp() throws Exception { + evaluator = new EqualityOperatorsEvaluator(); + } + + @Test + public void leftAndRightNullShouldBeTrue() throws Exception { + Token<Double> left = mock(Token.class); + when(left.getValue()).thenReturn(null); + + Token<Double> right = mock(Token.class); + when(right.getValue()).thenReturn(null); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.EQ()).thenReturn(mock(TerminalNode.class)); + + boolean evaluated = evaluator.evaluate(left, right, op); + + assertTrue(evaluated); + } + + @Test + public void leftNullAndRightNotShouldBeFalse() throws Exception { + Token<Double> left = mock(Token.class); + when(left.getValue()).thenReturn(null); + + Token<Double> right = mock(Token.class); + when(right.getValue()).thenReturn(1D); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.EQ()).thenReturn(mock(TerminalNode.class)); + + boolean evaluated = evaluator.evaluate(left, right, op); + + assertFalse(evaluated); + } + + @Test + public void leftNotNullAndRightNullShouldBeFalse() throws Exception { + Token<Double> left = mock(Token.class); + when(left.getValue()).thenReturn(1D); + + Token<Long> right = mock(Token.class); + when(right.getValue()).thenReturn(null); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.EQ()).thenReturn(mock(TerminalNode.class)); + + boolean evaluated = evaluator.evaluate(left, right, op); + + assertFalse(evaluated); + } + + @Test + public void eqTestForTwoLongs() throws Exception { + Token<Long> left = mock(Token.class); + when(left.getValue()).thenReturn(1L); + + Token<Long> right = mock(Token.class); + when(right.getValue()).thenReturn(1L); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.EQ()).thenReturn(mock(TerminalNode.class)); + + assertTrue(evaluator.evaluate(left, right, op)); + } + + @Test + public void eqTestForTwoDoubles() throws Exception { + Token<Double> left = mock(Token.class); + when(left.getValue()).thenReturn(1D); + + Token<Double> right = mock(Token.class); + when(right.getValue()).thenReturn(1D); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.EQ()).thenReturn(mock(TerminalNode.class)); + + assertTrue(evaluator.evaluate(left, right, op)); + } + + @Test + public void eqTestForTwoFloats() throws Exception { + Token<Float> left = mock(Token.class); + when(left.getValue()).thenReturn(1F); + + Token<Float> right = mock(Token.class); + when(right.getValue()).thenReturn(1F); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.EQ()).thenReturn(mock(TerminalNode.class)); + + assertTrue(evaluator.evaluate(left, right, op)); + } + + @Test + public void eqTestForTwoIntegers() throws Exception { + Token<Integer> left = mock(Token.class); + when(left.getValue()).thenReturn(1); + + Token<Integer> right = mock(Token.class); + when(right.getValue()).thenReturn(1); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.EQ()).thenReturn(mock(TerminalNode.class)); + + assertTrue(evaluator.evaluate(left, right, op)); + } + + @Test + public void eqTestForTwoStrings() throws Exception { + Token<String> left = mock(Token.class); + when(left.getValue()).thenReturn("1"); + + Token<String> right = mock(Token.class); + when(right.getValue()).thenReturn("1"); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.EQ()).thenReturn(mock(TerminalNode.class)); + + assertTrue(evaluator.evaluate(left, right, op)); + } + + @Test + public void eqTestForUnlikeTypes() throws Exception { + Token<String> left = mock(Token.class); + when(left.getValue()).thenReturn("1"); + + Token<Long> right = mock(Token.class); + when(right.getValue()).thenReturn(1L); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.EQ()).thenReturn(mock(TerminalNode.class)); + + assertFalse(evaluator.evaluate(left, right, op)); + } + + @Test + public void eqTestForUnlikeTypesLongString() throws Exception { + Token<Long> left = mock(Token.class); + when(left.getValue()).thenReturn(1L); + + Token<String> right = mock(Token.class); + when(right.getValue()).thenReturn("1"); + + StellarParser.ComparisonOpContext op = mock(StellarParser.ComparisonOpContext.class); + when(op.EQ()).thenReturn(mock(TerminalNode.class)); + + assertFalse(evaluator.evaluate(left, right, op)); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/metron/blob/a5b13777/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/FloatLiteralEvaluatorTest.java ---------------------------------------------------------------------- diff --git a/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/FloatLiteralEvaluatorTest.java b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/FloatLiteralEvaluatorTest.java new file mode 100644 index 0000000..cfcf33e --- /dev/null +++ b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/FloatLiteralEvaluatorTest.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.metron.stellar.common.evaluators; + +import org.apache.metron.stellar.dsl.Token; +import org.apache.metron.stellar.common.generated.StellarParser; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +public class FloatLiteralEvaluatorTest { + @Rule + public final ExpectedException exception = ExpectedException.none(); + + NumberEvaluator<StellarParser.FloatLiteralContext> evaluator; + StellarParser.FloatLiteralContext context; + + @Before + public void setUp() throws Exception { + evaluator = new FloatLiteralEvaluator(); + context = mock(StellarParser.FloatLiteralContext.class); + } + + @Test + public void verifyHappyPathEvaluation() throws Exception { + when(context.getText()).thenReturn("100f"); + + Token<? extends Number> evaluated = evaluator.evaluate(context, null); + assertEquals(new Token<>(100f, Float.class, null), evaluated); + + verify(context).getText(); + verifyNoMoreInteractions(context); + } + + @Test + public void verifyNumberFormationExceptionWithEmptyString() throws Exception { + exception.expect(NumberFormatException.class); + + when(context.getText()).thenReturn(""); + evaluator.evaluate(context, null); + } + + @Test + public void throwIllegalArgumentExceptionWhenContextIsNull() throws Exception { + exception.expect(IllegalArgumentException.class); + exception.expectMessage("Cannot evaluate a context that is null."); + + evaluator.evaluate(null, null); + } + +} http://git-wip-us.apache.org/repos/asf/metron/blob/a5b13777/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/IntLiteralEvaluatorTest.java ---------------------------------------------------------------------- diff --git a/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/IntLiteralEvaluatorTest.java b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/IntLiteralEvaluatorTest.java new file mode 100644 index 0000000..2e0ebed --- /dev/null +++ b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/IntLiteralEvaluatorTest.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.metron.stellar.common.evaluators; + +import org.apache.metron.stellar.dsl.Token; +import org.apache.metron.stellar.common.generated.StellarParser; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +public class IntLiteralEvaluatorTest { + @Rule + public final ExpectedException exception = ExpectedException.none(); + + NumberEvaluator<StellarParser.IntLiteralContext> evaluator; + StellarParser.IntLiteralContext context; + + @Before + public void setUp() throws Exception { + evaluator = new IntLiteralEvaluator(); + context = mock(StellarParser.IntLiteralContext.class); + } + + @Test + public void verifyHappyPathEvaluation() throws Exception { + when(context.getText()).thenReturn("100"); + + Token<? extends Number> evaluated = evaluator.evaluate(context, null); + assertEquals(new Token<>(100, Integer.class, null), evaluated); + + verify(context).getText(); + verifyNoMoreInteractions(context); + } + + @Test + public void verifyNumberFormationExceptionWithEmptyString() throws Exception { + exception.expect(NumberFormatException.class); + + when(context.getText()).thenReturn(""); + evaluator.evaluate(context, null); + } + + @Test + public void throwIllegalArgumentExceptionWhenContextIsNull() throws Exception { + exception.expect(IllegalArgumentException.class); + exception.expectMessage("Cannot evaluate a context that is null."); + + evaluator.evaluate(null, null); + } + +} http://git-wip-us.apache.org/repos/asf/metron/blob/a5b13777/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/LongLiteralEvaluatorTest.java ---------------------------------------------------------------------- diff --git a/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/LongLiteralEvaluatorTest.java b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/LongLiteralEvaluatorTest.java new file mode 100644 index 0000000..4bd94ce --- /dev/null +++ b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/LongLiteralEvaluatorTest.java @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.metron.stellar.common.evaluators; + +import org.apache.metron.stellar.dsl.ParseException; +import org.apache.metron.stellar.dsl.Token; +import org.apache.metron.stellar.common.generated.StellarParser; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +public class LongLiteralEvaluatorTest { + @Rule + public final ExpectedException exception = ExpectedException.none(); + + NumberEvaluator<StellarParser.LongLiteralContext> evaluator; + StellarParser.LongLiteralContext context; + + @Before + public void setUp() throws Exception { + evaluator = new LongLiteralEvaluator(); + context = mock(StellarParser.LongLiteralContext.class); + } + + @Test + public void verifyHappyPathEvaluation() throws Exception { + when(context.getText()).thenReturn("100L"); + + Token<? extends Number> evaluated = evaluator.evaluate(context, null); + assertEquals(new Token<>(100L, Long.class, null), evaluated); + + verify(context).getText(); + verifyNoMoreInteractions(context); + } + + @Test + public void verifyNumberFormationExceptionWithEmptyString() throws Exception { + exception.expect(ParseException.class); + exception.expectMessage("Invalid format for long. Failed trying to parse a long with the following value: "); + + when(context.getText()).thenReturn(""); + evaluator.evaluate(context, null); + } + + @Test + public void throwIllegalArgumentExceptionWhenContextIsNull() throws Exception { + exception.expect(IllegalArgumentException.class); + exception.expectMessage("Cannot evaluate a context that is null."); + + evaluator.evaluate(null, null); + } +} http://git-wip-us.apache.org/repos/asf/metron/blob/a5b13777/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/NumberLiteralEvaluatorTest.java ---------------------------------------------------------------------- diff --git a/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/NumberLiteralEvaluatorTest.java b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/NumberLiteralEvaluatorTest.java new file mode 100644 index 0000000..a250068 --- /dev/null +++ b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/evaluators/NumberLiteralEvaluatorTest.java @@ -0,0 +1,107 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.metron.stellar.common.evaluators; + +import org.apache.metron.stellar.dsl.ParseException; +import org.apache.metron.stellar.common.generated.StellarParser; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; + +public class NumberLiteralEvaluatorTest { + NumberEvaluator<StellarParser.IntLiteralContext> intLiteralContextNumberEvaluator; + NumberEvaluator<StellarParser.DoubleLiteralContext> doubleLiteralContextNumberEvaluator; + NumberEvaluator<StellarParser.FloatLiteralContext> floatLiteralContextNumberEvaluator; + NumberEvaluator<StellarParser.LongLiteralContext> longLiteralContextNumberEvaluator; + + Map<Class<? extends StellarParser.Arithmetic_operandsContext>, NumberEvaluator> instanceMap; + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Before + public void setUp() throws Exception { + intLiteralContextNumberEvaluator = mock(IntLiteralEvaluator.class); + doubleLiteralContextNumberEvaluator = mock(DoubleLiteralEvaluator.class); + floatLiteralContextNumberEvaluator = mock(FloatLiteralEvaluator.class); + longLiteralContextNumberEvaluator = mock(LongLiteralEvaluator.class); + instanceMap = new HashMap<Class<? extends StellarParser.Arithmetic_operandsContext>, NumberEvaluator>() {{ + put(mock(StellarParser.IntLiteralContext.class).getClass(), intLiteralContextNumberEvaluator); + put(mock(StellarParser.DoubleLiteralContext.class).getClass(), doubleLiteralContextNumberEvaluator); + put(mock(StellarParser.FloatLiteralContext.class).getClass(), floatLiteralContextNumberEvaluator); + put(mock(StellarParser.LongLiteralContext.class).getClass(), longLiteralContextNumberEvaluator); + }}; + } + + @Test + public void verifyIntLiteralContextIsProperlyEvaluated() throws Exception { + StellarParser.IntLiteralContext context = mock(StellarParser.IntLiteralContext.class); + NumberLiteralEvaluator.INSTANCE.evaluate(context, instanceMap, null); + + verify(intLiteralContextNumberEvaluator).evaluate(context, null); + verifyZeroInteractions(doubleLiteralContextNumberEvaluator, floatLiteralContextNumberEvaluator, longLiteralContextNumberEvaluator); + } + + @Test + public void verifyDoubleLiteralContextIsProperlyEvaluated() throws Exception { + StellarParser.DoubleLiteralContext context = mock(StellarParser.DoubleLiteralContext.class); + NumberLiteralEvaluator.INSTANCE.evaluate(context, instanceMap, null); + + verify(doubleLiteralContextNumberEvaluator).evaluate(context, null); + verifyZeroInteractions(intLiteralContextNumberEvaluator, floatLiteralContextNumberEvaluator, longLiteralContextNumberEvaluator); + } + + @Test + public void verifyFloatLiteralContextIsProperlyEvaluated() throws Exception { + StellarParser.FloatLiteralContext context = mock(StellarParser.FloatLiteralContext.class); + NumberLiteralEvaluator.INSTANCE.evaluate(context, instanceMap, null); + + verify(floatLiteralContextNumberEvaluator).evaluate(context, null); + verifyZeroInteractions(doubleLiteralContextNumberEvaluator, intLiteralContextNumberEvaluator, longLiteralContextNumberEvaluator); + } + + @Test + public void verifyLongLiteralContextIsProperlyEvaluated() throws Exception { + StellarParser.LongLiteralContext context = mock(StellarParser.LongLiteralContext.class); + NumberLiteralEvaluator.INSTANCE.evaluate(context, instanceMap, null); + + verify(longLiteralContextNumberEvaluator).evaluate(context, null); + verifyZeroInteractions(doubleLiteralContextNumberEvaluator, floatLiteralContextNumberEvaluator, intLiteralContextNumberEvaluator); + } + + @Test + public void verifyExceptionThrownForUnsupportedContextType() throws Exception { + StellarParser.VariableContext context = mock(StellarParser.VariableContext.class); + + exception.expect(ParseException.class); + exception.expectMessage("Does not support evaluation for type " + context.getClass()); + + NumberLiteralEvaluator.INSTANCE.evaluate(context, instanceMap, null); + + verifyZeroInteractions(longLiteralContextNumberEvaluator, doubleLiteralContextNumberEvaluator, floatLiteralContextNumberEvaluator, intLiteralContextNumberEvaluator); + } +} http://git-wip-us.apache.org/repos/asf/metron/blob/a5b13777/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/network/NetworkFunctionsTest.java ---------------------------------------------------------------------- diff --git a/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/network/NetworkFunctionsTest.java b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/network/NetworkFunctionsTest.java new file mode 100644 index 0000000..59a7b5b --- /dev/null +++ b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/network/NetworkFunctionsTest.java @@ -0,0 +1,156 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.metron.stellar.common.network; + +import com.google.common.collect.ImmutableList; +import org.junit.Test; + + +import static org.apache.metron.stellar.common.utils.StellarProcessorUtils.runWithArguments; + +public class NetworkFunctionsTest { + + @Test + public void inSubnetTest_positive() { + runWithArguments("IN_SUBNET", ImmutableList.of("192.168.0.1", "192.168.0.0/24"), true); + } + + @Test + public void inSubnetTest_negative() { + runWithArguments("IN_SUBNET", ImmutableList.of("192.168.1.1", "192.168.0.0/24"), false); + } + + @Test + public void inSubnetTest_multiple() { + runWithArguments("IN_SUBNET", ImmutableList.of("192.168.1.1", "192.168.0.0/24", "192.168.1.0/24"), true); + } + + @Test + public void removeSubdomainsTest() { + runWithArguments("DOMAIN_REMOVE_SUBDOMAINS", "www.google.co.uk", "google.co.uk"); + runWithArguments("DOMAIN_REMOVE_SUBDOMAINS", "www.google.com", "google.com"); + runWithArguments("DOMAIN_REMOVE_SUBDOMAINS", "com", "com"); + } + + @Test + public void removeSubdomainsTest_tld_square() { + runWithArguments("DOMAIN_REMOVE_SUBDOMAINS", "com.com", "com.com"); + runWithArguments("DOMAIN_REMOVE_SUBDOMAINS", "net.net", "net.net"); + runWithArguments("DOMAIN_REMOVE_SUBDOMAINS", "co.uk.co.uk", "uk.co.uk"); + runWithArguments("DOMAIN_REMOVE_SUBDOMAINS", "www.subdomain.com.com", "com.com"); + } + + @Test + public void removeSubdomainsTest_unknowntld() { + runWithArguments("DOMAIN_REMOVE_SUBDOMAINS", "www.subdomain.google.gmail", "google.gmail"); + } + + @Test + public void toTldTest() { + runWithArguments("DOMAIN_TO_TLD", "www.google.co.uk", "co.uk"); + runWithArguments("DOMAIN_TO_TLD", "www.google.com", "com"); + runWithArguments("DOMAIN_TO_TLD", "com", "com"); + } + + @Test + public void toTldTest_tld_square() { + runWithArguments("DOMAIN_TO_TLD", "com.com", "com"); + runWithArguments("DOMAIN_TO_TLD", "net.net", "net"); + runWithArguments("DOMAIN_TO_TLD", "co.uk.co.uk", "co.uk"); + runWithArguments("DOMAIN_TO_TLD", "www.subdomain.com.com", "com"); + } + + @Test + public void toTldTest_unknowntld() { + runWithArguments("DOMAIN_TO_TLD", "www.subdomain.google.gmail", "gmail"); + } + + @Test + public void removeTldTest() { + runWithArguments("DOMAIN_REMOVE_TLD", "google.com", "google"); + runWithArguments("DOMAIN_REMOVE_TLD", "www.google.co.uk", "www.google"); + runWithArguments("DOMAIN_REMOVE_TLD", "www.google.com", "www.google"); + runWithArguments("DOMAIN_REMOVE_TLD", "com", ""); + } + + @Test + public void removeTldTest_tld_square() { + runWithArguments("DOMAIN_REMOVE_TLD", "com.com", "com"); + runWithArguments("DOMAIN_REMOVE_TLD", "net.net", "net"); + runWithArguments("DOMAIN_REMOVE_TLD", "co.uk.co.uk", "co.uk"); + runWithArguments("DOMAIN_REMOVE_TLD", "www.subdomain.com.com", "www.subdomain.com"); + } + + @Test + public void removeTldTest_unknowntld() { + runWithArguments("DOMAIN_REMOVE_TLD", "www.subdomain.google.gmail", "www.subdomain.google"); + } + + @Test + public void urlToPortTest() { + runWithArguments("URL_TO_PORT", "http://www.google.com/foo/bar", 80); + runWithArguments("URL_TO_PORT", "https://www.google.com/foo/bar", 443); + runWithArguments("URL_TO_PORT", "http://www.google.com:7979/foo/bar", 7979); + } + + + @Test + public void urlToPortTest_unknowntld() { + runWithArguments("URL_TO_PORT", "http://www.google.gmail/foo/bar", 80); + } + + @Test + public void urlToHostTest() { + runWithArguments("URL_TO_HOST", "http://www.google.com/foo/bar", "www.google.com"); + runWithArguments("URL_TO_HOST", "https://www.google.com/foo/bar", "www.google.com"); + runWithArguments("URL_TO_HOST", "http://www.google.com:7979/foo/bar", "www.google.com"); + runWithArguments("URL_TO_HOST", "http://localhost:8080/a", "localhost"); + } + + + @Test + public void urlToHostTest_unknowntld() { + runWithArguments("URL_TO_HOST", "http://www.google.gmail/foo/bar", "www.google.gmail"); + } + + @Test + public void urlToProtocolTest() { + runWithArguments("URL_TO_PROTOCOL", "http://www.google.com/foo/bar", "http"); + runWithArguments("URL_TO_PROTOCOL", "https://www.google.com/foo/bar", "https"); + } + + + @Test + public void urlToProtocolTest_unknowntld() { + runWithArguments("URL_TO_PROTOCOL", "http://www.google.gmail/foo/bar", "http"); + } + + @Test + public void urlToPathTest() { + runWithArguments("URL_TO_PATH", "http://www.google.com/foo/bar", "/foo/bar"); + runWithArguments("URL_TO_PATH", "https://www.google.com/foo/bar", "/foo/bar"); + } + + + @Test + public void urlToPathTest_unknowntld() { + runWithArguments("URL_TO_PATH", "http://www.google.gmail/foo/bar", "/foo/bar"); + } + + +} http://git-wip-us.apache.org/repos/asf/metron/blob/a5b13777/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/system/ClockTest.java ---------------------------------------------------------------------- diff --git a/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/system/ClockTest.java b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/system/ClockTest.java new file mode 100644 index 0000000..2f4d3b6 --- /dev/null +++ b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/system/ClockTest.java @@ -0,0 +1,54 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.metron.stellar.common.system; + +import org.junit.Test; +import org.mockito.Mockito; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +public class ClockTest { + + @Test + public void returns_system_time() throws Exception { + Clock clock = new Clock(); + long t1 = clock.currentTimeMillis(); + Thread.sleep(50); + long t2 = clock.currentTimeMillis(); + Thread.sleep(50); + long t3 = clock.currentTimeMillis(); + assertThat("t3 should be greater", t3 > t2, equalTo(true)); + assertThat("t2 should be greater", t2 > t1, equalTo(true)); + } + + @Test + public void formats_system_time_given_passed_format() throws Exception { + Clock clock = Mockito.spy(Clock.class); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSZ"); + sdf.setTimeZone(TimeZone.getTimeZone("UTC")); + Date date = sdf.parse("20160615183527162+0000"); + Mockito.when(clock.currentTimeMillis()).thenReturn(date.getTime()); + assertThat("time not right", clock.currentTimeFormatted("yyyyMMddHHmmssSSSZ"), equalTo("20160615183527162+0000")); + } + +} http://git-wip-us.apache.org/repos/asf/metron/blob/a5b13777/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/BloomFilterTest.java ---------------------------------------------------------------------- diff --git a/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/BloomFilterTest.java b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/BloomFilterTest.java new file mode 100644 index 0000000..c3926fe --- /dev/null +++ b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/BloomFilterTest.java @@ -0,0 +1,95 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.metron.stellar.common.utils; + +import com.google.common.collect.ImmutableMap; +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.apache.metron.stellar.common.utils.StellarProcessorUtils.run; + +public class BloomFilterTest { + private Map<String, Object> variables = new HashMap<String, Object>() {{ + put("string", "casey"); + put("double", 1.0); + put("integer", 1); + put("map", ImmutableMap.of("key1", "value1", "key2", "value2")); + }}; + + @Test + public void testMerge() { + + BloomFilter bloomString = (BloomFilter)run("BLOOM_ADD(BLOOM_INIT(), string)", variables); + BloomFilter bloomDouble = (BloomFilter)run("BLOOM_ADD(BLOOM_INIT(), double)", variables); + BloomFilter bloomInteger= (BloomFilter)run("BLOOM_ADD(BLOOM_INIT(), integer)", variables); + BloomFilter bloomMap= (BloomFilter)run("BLOOM_ADD(BLOOM_INIT(), map)", variables); + BloomFilter merged = (BloomFilter)run("BLOOM_MERGE([stringFilter, doubleFilter, integerFilter, mapFilter])" + , ImmutableMap.of("stringFilter", bloomString + ,"doubleFilter", bloomDouble + ,"integerFilter", bloomInteger + ,"mapFilter", bloomMap + ) + ); + Assert.assertNotNull(merged); + for(Object val : variables.values()) { + Assert.assertTrue(merged.mightContain(val)); + } + } + + @Test + public void testAdd() { + BloomFilter result = (BloomFilter)run("BLOOM_ADD(BLOOM_INIT(), string, double, integer, map)", variables); + for(Object val : variables.values()) { + Assert.assertTrue(result.mightContain(val)); + } + Assert.assertTrue(result.mightContain(ImmutableMap.of("key1", "value1", "key2", "value2"))); + } + + @Test + public void testExists() { + { + Boolean result = (Boolean) run("BLOOM_EXISTS(BLOOM_ADD(BLOOM_INIT(), string, double, integer, map), 'casey')", variables); + Assert.assertTrue(result); + } + { + Boolean result = (Boolean) run("BLOOM_EXISTS(BLOOM_ADD(BLOOM_INIT(), string, double, integer, map), double)", variables); + Assert.assertTrue(result); + } + { + Boolean result = (Boolean) run("BLOOM_EXISTS(BLOOM_ADD(BLOOM_INIT(), string, double, integer, map), integer)", variables); + Assert.assertTrue(result); + } + { + Boolean result = (Boolean) run("BLOOM_EXISTS(BLOOM_ADD(BLOOM_INIT(), string, double, integer, map), map)", variables); + Assert.assertTrue(result); + } + { + Boolean result = (Boolean) run("BLOOM_EXISTS(BLOOM_ADD(BLOOM_INIT(), string, double, integer, map), 'samantha')", variables); + Assert.assertFalse(result); + } + { + Boolean result = (Boolean) run("BLOOM_EXISTS(BLOOM_ADD(BLOOM_INIT(), string, double, integer, map), sam)", variables); + Assert.assertFalse(result); + } + } +} http://git-wip-us.apache.org/repos/asf/metron/blob/a5b13777/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/ConversionUtilsTest.java ---------------------------------------------------------------------- diff --git a/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/ConversionUtilsTest.java b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/ConversionUtilsTest.java new file mode 100644 index 0000000..c45dec3 --- /dev/null +++ b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/ConversionUtilsTest.java @@ -0,0 +1,35 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.metron.stellar.common.utils; + +import org.apache.metron.stellar.common.utils.ConversionUtils; +import org.junit.Assert; +import org.junit.Test; + +public class ConversionUtilsTest { + + @Test + public void testIntegerConversions() { + Object o = 1; + Assert.assertEquals(Integer.valueOf(1), ConversionUtils.convert(o, Integer.class)); + Assert.assertEquals(Integer.valueOf(1), ConversionUtils.convert("1", Integer.class)); + Assert.assertNull(ConversionUtils.convert("foo", Integer.class)); + } + +} http://git-wip-us.apache.org/repos/asf/metron/blob/a5b13777/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/JSONUtilsTest.java ---------------------------------------------------------------------- diff --git a/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/JSONUtilsTest.java b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/JSONUtilsTest.java new file mode 100644 index 0000000..f4692e3 --- /dev/null +++ b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/JSONUtilsTest.java @@ -0,0 +1,102 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.metron.stellar.common.utils; + +import com.fasterxml.jackson.core.type.TypeReference; +import org.adrianwalker.multilinestring.Multiline; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +import static org.hamcrest.CoreMatchers.equalTo; + +public class JSONUtilsTest { + private static File tmpDir; + + /** + { + "a" : "hello", + "b" : "world" + } + */ + @Multiline + private static String config; + private static File configFile; + + @BeforeClass + public static void setUp() throws Exception { + tmpDir = UnitTestHelper.createTempDir(new File("target/jsonutilstest")); + configFile = UnitTestHelper.write(new File(tmpDir, "config.json"), config); + } + + @Test + public void loads_file_with_typeref() throws Exception { + Map<String, Object> expected = new HashMap<String, Object>() {{ + put("a", "hello"); + put("b", "world"); + }}; + Map<String, Object> actual = JSONUtils.INSTANCE.load(configFile, new TypeReference<Map<String, Object>>() { + }); + Assert.assertThat("config not equal", actual, equalTo(expected)); + } + + @Test + public void loads_file_with_map_class() throws Exception { + Map<String, Object> expected = new HashMap<String, Object>() {{ + put("a", "hello"); + put("b", "world"); + }}; + Map<String, Object> actual = JSONUtils.INSTANCE.load(configFile, Map.class); + Assert.assertThat("config not equal", actual, equalTo(expected)); + } + + @Test + public void loads_file_with_custom_class() throws Exception { + TestConfig expected = new TestConfig().setA("hello").setB("world"); + TestConfig actual = JSONUtils.INSTANCE.load(configFile, TestConfig.class); + Assert.assertThat("a not equal", actual.getA(), equalTo(expected.getA())); + Assert.assertThat("b not equal", actual.getB(), equalTo(expected.getB())); + } + + public static class TestConfig { + private String a; + private String b; + + public String getA() { + return a; + } + + public TestConfig setA(String a) { + this.a = a; + return this; + } + + public String getB() { + return b; + } + + public TestConfig setB(String b) { + this.b = b; + return this; + } + } +} http://git-wip-us.apache.org/repos/asf/metron/blob/a5b13777/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/SerDeUtilsTest.java ---------------------------------------------------------------------- diff --git a/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/SerDeUtilsTest.java b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/SerDeUtilsTest.java new file mode 100644 index 0000000..dc5c9ee --- /dev/null +++ b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/SerDeUtilsTest.java @@ -0,0 +1,216 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.metron.stellar.common.utils; + +import com.google.common.collect.ImmutableList; +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +/** + * Tests the Serializer. + */ +public class SerDeUtilsTest { + + @Test + public void testInteger() { + final int expected = 2; + byte[] raw = SerDeUtils.toBytes(expected); + int actual = SerDeUtils.fromBytes(raw, Integer.class); + assertEquals(expected, actual); + } + + @Test + public void testDouble() { + final double expected = 2.0; + byte[] raw = SerDeUtils.toBytes(expected); + { + double actual = SerDeUtils.fromBytes(raw, Double.class); + assertEquals(expected, actual, 0.01); + } + { + double actual = (double) SerDeUtils.fromBytes(raw, Object.class); + assertEquals(expected, actual, 0.01); + } + } + + @Test + public void testShort() { + final short expected = 2; + byte[] raw = SerDeUtils.toBytes(expected); + { + short actual = SerDeUtils.fromBytes(raw, Short.class); + assertEquals(expected, actual); + } + { + short actual = (short) SerDeUtils.fromBytes(raw, Object.class); + assertEquals(expected, actual); + } + } + + @Test + public void testLong() { + final long expected = 2L; + byte[] raw = SerDeUtils.toBytes(expected); + { + long actual = SerDeUtils.fromBytes(raw, Long.class); + assertEquals(expected, actual); + } + { + long actual = (Long) SerDeUtils.fromBytes(raw, Object.class); + assertEquals(expected, actual); + } + } + + @Test + public void testFloat() { + final Float expected = 2.2F; + byte[] raw = SerDeUtils.toBytes(expected); + { + float actual = SerDeUtils.fromBytes(raw, Float.class); + assertEquals(expected, actual, 0.01); + } + { + float actual = (float) SerDeUtils.fromBytes(raw, Object.class); + assertEquals(expected, actual, 0.01); + } + } + + @Test + public void testMap() { + final Map<String, Object> expected = new HashMap<>(); + expected.put("foo", "bar"); + expected.put( "bar", 1.0); + ; + byte[] raw = SerDeUtils.toBytes(expected); + Object actual = SerDeUtils.fromBytes(raw, Object.class); + assertEquals(expected, actual); + } + + @Test + public void testList() { + final List<String> expected = new ArrayList<String>(); + expected.add("foo"); + expected.add("bar"); + byte[] raw = SerDeUtils.toBytes(expected); + Object actual = SerDeUtils.fromBytes(raw, Object.class); + assertEquals(expected, actual); + } + + @Test + public void testBloomFilter() { + final BloomFilter<Object> expected = new BloomFilter<>(new BloomFilter.DefaultSerializer<>(), 10000, 0.01); + expected.add("foo"); + expected.add("bar"); + byte[] raw = SerDeUtils.toBytes(expected); + BloomFilter<Object> actual = (BloomFilter) SerDeUtils.fromBytes(raw, Object.class); + Assert.assertTrue(actual.mightContain("foo")); + Assert.assertFalse(actual.mightContain("timothy")); + assertEquals(expected, actual); + } + + public static class ArbitraryPojo { + private List<String> list = new ArrayList<>(); + private String string = "foo"; + private Double d = 1.0; + private Map<String, String> map = new HashMap<>(); + private List<String> immutableList = ImmutableList.of("foo"); + + public ArbitraryPojo() { + list.add("foo"); + list.add("bar"); + map.put("key1", "value1"); + map.put("key2", "value2"); + + } + + public List<String> getList() { + return list; + } + + public void setList(List<String> list) { + this.list = list; + } + + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public Double getD() { + return d; + } + + public void setD(Double d) { + this.d = d; + } + + public Map<String, String> getMap() { + return map; + } + + public void setMap(Map<String, String> map) { + this.map = map; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + ArbitraryPojo that = (ArbitraryPojo) o; + + if (getList() != null ? !getList().equals(that.getList()) : that.getList() != null) return false; + if (getString() != null ? !getString().equals(that.getString()) : that.getString() != null) return false; + if (getD() != null ? !getD().equals(that.getD()) : that.getD() != null) return false; + if (getMap() != null ? !getMap().equals(that.getMap()) : that.getMap() != null) return false; + return immutableList != null ? immutableList.equals(that.immutableList) : that.immutableList == null; + + } + + @Override + public int hashCode() { + int result = getList() != null ? getList().hashCode() : 0; + result = 31 * result + (getString() != null ? getString().hashCode() : 0); + result = 31 * result + (getD() != null ? getD().hashCode() : 0); + result = 31 * result + (getMap() != null ? getMap().hashCode() : 0); + result = 31 * result + (immutableList != null ? immutableList.hashCode() : 0); + return result; + } + } + + @Test + public void testArbitraryPojo() { + final ArbitraryPojo expected = new ArbitraryPojo(); + byte[] raw = SerDeUtils.toBytes(expected); + Object actual = SerDeUtils.fromBytes(raw, Object.class); + assertEquals(expected, actual); + } +} http://git-wip-us.apache.org/repos/asf/metron/blob/a5b13777/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/UnitTestHelper.java ---------------------------------------------------------------------- diff --git a/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/UnitTestHelper.java b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/UnitTestHelper.java new file mode 100644 index 0000000..ae0856a --- /dev/null +++ b/metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/common/utils/UnitTestHelper.java @@ -0,0 +1,244 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.metron.stellar.common.utils; + +import org.apache.log4j.ConsoleAppender; +import org.apache.log4j.Level; +import org.apache.log4j.Logger; +import org.apache.log4j.PatternLayout; +import org.junit.Assert; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.Set; +import java.util.Stack; + +import static java.lang.String.format; + +public class UnitTestHelper { + public static String findDir(String name) { + return findDir(new File("."), name); + } + + public static String findDir(File startDir, String name) { + Stack<File> s = new Stack<File>(); + s.push(startDir); + while (!s.empty()) { + File parent = s.pop(); + if (parent.getName().equalsIgnoreCase(name)) { + return parent.getAbsolutePath(); + } else { + File[] children = parent.listFiles(); + if (children != null) { + for (File child : children) { + s.push(child); + } + } + } + } + return null; + } + + public static <T> void assertSetEqual(String type, Set<T> expectedPcapIds, Set<T> found) { + boolean mismatch = false; + for (T f : found) { + if (!expectedPcapIds.contains(f)) { + mismatch = true; + System.out.println("Found " + type + " that I did not expect: " + f); + } + } + for (T expectedId : expectedPcapIds) { + if (!found.contains(expectedId)) { + mismatch = true; + System.out.println("Expected " + type + " that I did not index: " + expectedId); + } + } + Assert.assertFalse(mismatch); + } + + public static void verboseLogging() { + verboseLogging("%d [%p|%c|%C{1}] %m%n", Level.ALL); + } + + public static void verboseLogging(String pattern, Level level) { + ConsoleAppender console = new ConsoleAppender(); //create appender + //configure the appender + console.setLayout(new PatternLayout(pattern)); + console.setThreshold(level); + console.activateOptions(); + //add appender to any Logger (here is root) + Logger.getRootLogger().addAppender(console); + } + + public static void setLog4jLevel(Class clazz, Level level) { + Logger logger = Logger.getLogger(clazz); + logger.setLevel(level); + } + + public static Level getLog4jLevel(Class clazz) { + Logger logger = Logger.getLogger(clazz); + return logger.getLevel(); + } + + public static void setJavaLoggingLevel(Class clazz, java.util.logging.Level level) { + java.util.logging.Logger logger = java.util.logging.Logger.getLogger(clazz.getName()); + logger.setLevel(level); + } + + public static java.util.logging.Level getJavaLoggingLevel(Class clazz) { + java.util.logging.Logger logger = java.util.logging.Logger.getLogger(clazz.getName()); + return logger.getLevel(); + } + + public static void setJavaLoggingLevel(java.util.logging.Level level) { + java.util.logging.Logger logger = java.util.logging.Logger.getLogger(""); + logger.setLevel(level); + } + + public static java.util.logging.Level getJavaLoggingLevel(){ + java.util.logging.Logger logger = java.util.logging.Logger.getLogger(""); + return logger.getLevel(); + } + + /** + * Create directory that is automatically cleaned up after the + * JVM shuts down through use of a Runtime shutdown hook. + * + * @param dir Directory to create, including missing parent directories + * @return File handle to the created temp directory + */ + public static File createTempDir(File dir) throws IOException { + return createTempDir(dir, true); + } + + /** + * Create directory that is automatically cleaned up after the + * JVM shuts down through use of a Runtime shutdown hook. + * + * @param dir Directory to create, including missing parent directories + * @param cleanup true/false + * @return File handle to the created temp directory + */ + public static File createTempDir(File dir, boolean cleanup) throws IOException { + if (!dir.mkdirs() && !dir.exists()) { + throw new IOException(String.format("Failed to create directory structure '%s'", dir.toString())); + } + if (cleanup) { + addCleanupHook(dir.toPath()); + } + return dir; + } + + /** + * Create directory that is automatically cleaned up after the + * JVM shuts down through use of a Runtime shutdown hook. + * + * @param prefix Prefix to apply to temp directory name + * @return File handle to the created temp directory + * @throws IOException Unable to create temp directory + */ + public static File createTempDir(String prefix) throws IOException { + return createTempDir(prefix, true); + } + + /** + * Create directory that is optionally cleaned up after the + * JVM shuts down through use of a Runtime shutdown hook. + * + * @param prefix Prefix to apply to temp directory name + * @param cleanup true/false + * @return File handle to the created temp directory + * @throws IOException Unable to create temp directory + */ + public static File createTempDir(String prefix, boolean cleanup) throws IOException { + Path tmpDir = Files.createTempDirectory(prefix); + addCleanupHook(tmpDir); + return tmpDir.toFile(); + } + + /** + * Adds JVM shutdown hook that will recursively delete the passed directory + * + * @param dir Directory that will be cleaned up upon JVM shutdown + */ + public static void addCleanupHook(final Path dir) { + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override + public void run() { + try { + cleanDir(dir); + } catch (IOException e) { + System.out.println(format("Warning: Unable to clean folder '%s'", dir.toString())); + } + } + }); + } + + /** + * Recursive directory delete + * + * @param dir Directory to delete + * @throws IOException Unable to delete + */ + public static void cleanDir(Path dir) throws IOException { + Files.walkFileTree(dir, new SimpleFileVisitor<Path>() { + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + if (exc == null) { + return FileVisitResult.CONTINUE; + } else { + throw exc; + } + } + }); + Files.delete(dir); + } + + /** + * Write contents to a file + * + * @param file + * @param contents + * @return file handle + * @throws IOException + */ + public static File write(File file, String contents) throws IOException { + com.google.common.io.Files.createParentDirs(file); + com.google.common.io.Files.write(contents, file, StandardCharsets.UTF_8); + return file; + } +}
