X
stringlengths 236
264k
| y
stringlengths 5
74
|
---|---|
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8080289 8189067
* @summary Move stores out of loops if possible
*
* @run main/othervm -XX:-UseOnStackReplacement -XX:-BackgroundCompilation
* -XX:CompileCommand=dontinline,compiler.loopopts.TestMoveStoresOutOfLoops::test*
* compiler.loopopts.TestMoveStoresOutOfLoops
*/
package compiler.loopopts;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.function.Function;
public class TestMoveStoresOutOfLoops {
private static long[] array = new long[10];
private static long[] array2 = new long[10];
private static boolean[] array3 = new boolean[1000];
private static int[] array4 = new int[1000];
private static byte[] byte_array = new byte[10];
// Array store should be moved out of the loop, value stored
// should be 999, the loop should be eliminated
static void test_after_1(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
}
}
// Array store can't be moved out of loop because of following
// non loop invariant array access
static void test_after_2(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
array2[i%10] = i;
}
}
// Array store can't be moved out of loop because of following
// use
static void test_after_3(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
if (array[0] == -1) {
break;
}
}
}
// Array store can't be moved out of loop because of preceding
// use
static void test_after_4(int idx) {
for (int i = 0; i < 1000; i++) {
if (array[0] == -2) {
break;
}
array[idx] = i;
}
}
// All array stores should be moved out of the loop, one after
// the other
static void test_after_5(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
array[idx+1] = i;
array[idx+2] = i;
array[idx+3] = i;
array[idx+4] = i;
array[idx+5] = i;
}
}
// Array store can be moved after the loop but needs to be
// cloned on both exit paths
static void test_after_6(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
if (array3[i]) {
return;
}
}
}
// Array store can be moved out of the inner loop
static void test_after_7(int idx) {
for (int i = 0; i < 1000; i++) {
for (int j = 0; j <= 42; j++) {
array4[i] = j;
}
}
}
// Optimize out redundant stores
static void test_stores_1(int ignored) {
array[0] = 0;
array[1] = 1;
array[2] = 2;
array[0] = 0;
array[1] = 1;
array[2] = 2;
}
static void test_stores_2(int idx) {
array[idx+0] = 0;
array[idx+1] = 1;
array[idx+2] = 2;
array[idx+0] = 0;
array[idx+1] = 1;
array[idx+2] = 2;
}
static void test_stores_3(int idx) {
byte_array[idx+0] = 0;
byte_array[idx+1] = 1;
byte_array[idx+2] = 2;
byte_array[idx+0] = 0;
byte_array[idx+1] = 1;
byte_array[idx+2] = 2;
}
// Array store can be moved out of the loop before the loop header
static void test_before_1(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = 999;
}
}
// Array store can't be moved out of the loop before the loop
// header because there's more than one store on this slice
static void test_before_2(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = 999;
array[i%2] = 0;
}
}
// Array store can't be moved out of the loop before the loop
// header because of use before store
static int test_before_3(int idx) {
int res = 0;
for (int i = 0; i < 1000; i++) {
res += array[i%10];
array[idx] = 999;
}
return res;
}
// Array store can't be moved out of the loop before the loop
// header because of possible early exit
static void test_before_4(int idx) {
for (int i = 0; i < 1000; i++) {
if (idx / (i+1) > 0) {
return;
}
array[idx] = 999;
}
}
// Array store can't be moved out of the loop before the loop
// header because it doesn't postdominate the loop head
static void test_before_5(int idx) {
for (int i = 0; i < 1000; i++) {
if (i % 2 == 0) {
array[idx] = 999;
}
}
}
// Array store can be moved out of the loop before the loop header
static int test_before_6(int idx) {
int res = 0;
for (int i = 0; i < 1000; i++) {
if (i%2 == 1) {
res *= 2;
} else {
res++;
}
array[idx] = 999;
}
return res;
}
final HashMap<String,Method> tests = new HashMap<>();
{
for (Method m : this.getClass().getDeclaredMethods()) {
if (m.getName().matches("test_(before|after|stores)_[0-9]+")) {
assert(Modifier.isStatic(m.getModifiers())) : m;
tests.put(m.getName(), m);
}
}
}
boolean [MASK] = true;
void doTest(String name, Runnable init, Function<String, Boolean> check) throws Exception {
Method m = tests.get(name);
for (int i = 0; i < 20000; i++) {
init.run();
m.invoke(null, 0);
[MASK] = [MASK] && check.apply(name);
if (! [MASK] ) {
break;
}
}
}
static void array_init() {
array[0] = -1;
}
static boolean array_check(String name) {
boolean [MASK] = true;
if (array[0] != 999) {
[MASK] = false;
System.out.println(name + " failed: array[0] = " + array[0]);
}
return [MASK] ;
}
static void array_init2() {
for (int i = 0; i < 6; i++) {
array[i] = -1;
}
}
static boolean array_check2(String name) {
boolean [MASK] = true;
for (int i = 0; i < 6; i++) {
if (array[i] != 999) {
[MASK] = false;
System.out.println(name + " failed: array[" + i + "] = " + array[i]);
}
}
return [MASK] ;
}
static void array_init3() {
for (int i = 0; i < 3; i++) {
array[i] = -1;
}
}
static boolean array_check3(String name) {
boolean [MASK] = true;
for (int i = 0; i < 3; i++) {
if (array[i] != i) {
[MASK] = false;
System.out.println(name + " failed: array[" + i + "] = " + array[i]);
}
}
return [MASK] ;
}
static void array_init4() {
for (int i = 0; i < 3; i++) {
byte_array[i] = -1;
}
}
static boolean array_check4(String name) {
boolean [MASK] = true;
for (int i = 0; i < 3; i++) {
if (byte_array[i] != i) {
[MASK] = false;
System.out.println(name + " failed: byte_array[" + i + "] = " + byte_array[i]);
}
}
return [MASK] ;
}
static boolean array_check5(String name) {
boolean [MASK] = true;
for (int i = 0; i < 1000; i++) {
if (array4[i] != 42) {
[MASK] = false;
System.out.println(name + " failed: array[" + i + "] = " + array4[i]);
}
}
return [MASK] ;
}
static public void main(String[] args) throws Exception {
TestMoveStoresOutOfLoops test = new TestMoveStoresOutOfLoops();
test.doTest("test_after_1", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_2", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_3", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_4", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_5", TestMoveStoresOutOfLoops::array_init2, TestMoveStoresOutOfLoops::array_check2);
test.doTest("test_after_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
array3[999] = true;
test.doTest("test_after_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_7", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check5);
test.doTest("test_stores_1", TestMoveStoresOutOfLoops::array_init3, TestMoveStoresOutOfLoops::array_check3);
test.doTest("test_stores_2", TestMoveStoresOutOfLoops::array_init3, TestMoveStoresOutOfLoops::array_check3);
test.doTest("test_stores_3", TestMoveStoresOutOfLoops::array_init4, TestMoveStoresOutOfLoops::array_check4);
test.doTest("test_before_1", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_2", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_3", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_4", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_5", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
if (!test. [MASK] ) {
throw new RuntimeException("Some tests failed");
}
}
}
| success |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, [MASK] ) ->
[MASK] .withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
[MASK] ->
[MASK] .changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, [MASK] ) ->
[MASK] .withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
[MASK] ->
[MASK] .changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, [MASK] ) ->
[MASK] .withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
[MASK] ->
[MASK] .changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, [MASK] ) ->
[MASK] .withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
[MASK] ->
[MASK] .changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter [MASK] = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, [MASK] );
[MASK] .write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter [MASK] = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept( [MASK] );
[MASK] .write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint [MASK] function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| writer |
/*
* Copyright (c) 2024, Intel Corporation. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Random;
import java.math.BigInteger;
import java.lang.reflect.Field;
import java.security.spec.ECParameterSpec;
import sun.security.ec.ECOperations;
import sun.security.util.ECUtil;
import sun.security.util.NamedCurve;
import sun.security.util.CurveDB;
import sun.security.ec.point.*;
import java.security.spec.ECPoint;
import sun.security.util.KnownOIDs;
import sun.security.util.math.IntegerMontgomeryFieldModuloP;
import sun.security.util.math.intpoly.*;
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:-UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:+UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
// This test case is NOT entirely deterministic, it uses a random seed for
// pseudo-random number generator. If a failure occurs, hardcode the seed to
// make the test case deterministic
public class ECOperationsFuzzTest {
public static void main(String[] args) throws Exception {
// Note: it might be useful to increase this number during development
final int [MASK] = 10000;
test( [MASK] );
System.out.println("Fuzz Success");
}
private static void check(MutablePoint reference, MutablePoint testValue,
long seed, int iter) {
AffinePoint affineRef = reference.asAffine();
AffinePoint affine = testValue.asAffine();
if (!affineRef.equals(affine)) {
throw new RuntimeException(
"Found error with seed " + seed + "at iteration " + iter);
}
}
public static void test(int [MASK] ) throws Exception {
Random rnd = new Random();
long seed = rnd.nextLong();
rnd.setSeed(seed);
int keySize = 256;
ECParameterSpec params = ECUtil.getECParameterSpec(keySize);
NamedCurve curve = CurveDB.lookup(KnownOIDs.secp256r1.value());
ECPoint generator = curve.getGenerator();
BigInteger b = curve.getCurve().getB();
if (params == null || generator == null) {
throw new RuntimeException(
"No EC parameters available for key size " + keySize + " bits");
}
ECOperations ops = ECOperations.forParameters(params).get();
ECOperations opsReference = new ECOperations(
IntegerPolynomialP256.ONE.getElement(b), P256OrderField.ONE);
boolean instanceTest1 = ops
.getField() instanceof IntegerMontgomeryFieldModuloP;
boolean instanceTest2 = opsReference
.getField() instanceof IntegerMontgomeryFieldModuloP;
if (instanceTest1 == false || instanceTest2 == true) {
throw new RuntimeException("Bad Initialization: ["
+ instanceTest1 + "," + instanceTest2 + "]");
}
byte[] multiple = new byte[keySize / 8];
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // from opsReference.seedToScalar(multiple);
MutablePoint referencePoint = opsReference.multiply(generator, multiple);
MutablePoint point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, -1);
AffinePoint refAffineGenerator = AffinePoint.fromECPoint(generator,
referencePoint.getField());
AffinePoint montAffineGenerator = AffinePoint.fromECPoint(generator,
point.getField());
MutablePoint refProjGenerator = new ProjectivePoint.Mutable(
refAffineGenerator.getX(false).mutable(),
refAffineGenerator.getY(false).mutable(),
referencePoint.getField().get1().mutable());
MutablePoint projGenerator = new ProjectivePoint.Mutable(
montAffineGenerator.getX(false).mutable(),
montAffineGenerator.getY(false).mutable(),
point.getField().get1().mutable());
for (int i = 0; i < [MASK] ; i++) {
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // opsReference.seedToScalar(multiple);
MutablePoint nextReferencePoint = opsReference
.multiply(referencePoint.asAffine(), multiple);
MutablePoint nextPoint = ops.multiply(point.asAffine().toECPoint(),
multiple);
check(nextReferencePoint, nextPoint, seed, i);
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, referencePoint);
ops.setSum(nextPoint, point);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, refProjGenerator);
ops.setSum(nextPoint, projGenerator);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextInt(100) < 10) { // 10% Reset point to generator, test
// generator multiplier
referencePoint = opsReference.multiply(generator, multiple);
point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, i);
} else {
referencePoint = nextReferencePoint;
point = nextPoint;
}
}
}
}
// make test TEST="test/jdk/com/sun/security/ec/ECOperationsFuzzTest.java" | repeat |
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8080289 8189067
* @summary Move stores out of loops if possible
*
* @run main/othervm -XX:-UseOnStackReplacement -XX:-BackgroundCompilation
* -XX:CompileCommand=dontinline,compiler.loopopts.TestMoveStoresOutOfLoops::test*
* compiler.loopopts.TestMoveStoresOutOfLoops
*/
package compiler.loopopts;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util. [MASK] ;
import java.util.function.Function;
public class TestMoveStoresOutOfLoops {
private static long[] array = new long[10];
private static long[] array2 = new long[10];
private static boolean[] array3 = new boolean[1000];
private static int[] array4 = new int[1000];
private static byte[] byte_array = new byte[10];
// Array store should be moved out of the loop, value stored
// should be 999, the loop should be eliminated
static void test_after_1(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
}
}
// Array store can't be moved out of loop because of following
// non loop invariant array access
static void test_after_2(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
array2[i%10] = i;
}
}
// Array store can't be moved out of loop because of following
// use
static void test_after_3(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
if (array[0] == -1) {
break;
}
}
}
// Array store can't be moved out of loop because of preceding
// use
static void test_after_4(int idx) {
for (int i = 0; i < 1000; i++) {
if (array[0] == -2) {
break;
}
array[idx] = i;
}
}
// All array stores should be moved out of the loop, one after
// the other
static void test_after_5(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
array[idx+1] = i;
array[idx+2] = i;
array[idx+3] = i;
array[idx+4] = i;
array[idx+5] = i;
}
}
// Array store can be moved after the loop but needs to be
// cloned on both exit paths
static void test_after_6(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
if (array3[i]) {
return;
}
}
}
// Array store can be moved out of the inner loop
static void test_after_7(int idx) {
for (int i = 0; i < 1000; i++) {
for (int j = 0; j <= 42; j++) {
array4[i] = j;
}
}
}
// Optimize out redundant stores
static void test_stores_1(int ignored) {
array[0] = 0;
array[1] = 1;
array[2] = 2;
array[0] = 0;
array[1] = 1;
array[2] = 2;
}
static void test_stores_2(int idx) {
array[idx+0] = 0;
array[idx+1] = 1;
array[idx+2] = 2;
array[idx+0] = 0;
array[idx+1] = 1;
array[idx+2] = 2;
}
static void test_stores_3(int idx) {
byte_array[idx+0] = 0;
byte_array[idx+1] = 1;
byte_array[idx+2] = 2;
byte_array[idx+0] = 0;
byte_array[idx+1] = 1;
byte_array[idx+2] = 2;
}
// Array store can be moved out of the loop before the loop header
static void test_before_1(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = 999;
}
}
// Array store can't be moved out of the loop before the loop
// header because there's more than one store on this slice
static void test_before_2(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = 999;
array[i%2] = 0;
}
}
// Array store can't be moved out of the loop before the loop
// header because of use before store
static int test_before_3(int idx) {
int res = 0;
for (int i = 0; i < 1000; i++) {
res += array[i%10];
array[idx] = 999;
}
return res;
}
// Array store can't be moved out of the loop before the loop
// header because of possible early exit
static void test_before_4(int idx) {
for (int i = 0; i < 1000; i++) {
if (idx / (i+1) > 0) {
return;
}
array[idx] = 999;
}
}
// Array store can't be moved out of the loop before the loop
// header because it doesn't postdominate the loop head
static void test_before_5(int idx) {
for (int i = 0; i < 1000; i++) {
if (i % 2 == 0) {
array[idx] = 999;
}
}
}
// Array store can be moved out of the loop before the loop header
static int test_before_6(int idx) {
int res = 0;
for (int i = 0; i < 1000; i++) {
if (i%2 == 1) {
res *= 2;
} else {
res++;
}
array[idx] = 999;
}
return res;
}
final [MASK] <String,Method> tests = new [MASK] <>();
{
for (Method m : this.getClass().getDeclaredMethods()) {
if (m.getName().matches("test_(before|after|stores)_[0-9]+")) {
assert(Modifier.isStatic(m.getModifiers())) : m;
tests.put(m.getName(), m);
}
}
}
boolean success = true;
void doTest(String name, Runnable init, Function<String, Boolean> check) throws Exception {
Method m = tests.get(name);
for (int i = 0; i < 20000; i++) {
init.run();
m.invoke(null, 0);
success = success && check.apply(name);
if (!success) {
break;
}
}
}
static void array_init() {
array[0] = -1;
}
static boolean array_check(String name) {
boolean success = true;
if (array[0] != 999) {
success = false;
System.out.println(name + " failed: array[0] = " + array[0]);
}
return success;
}
static void array_init2() {
for (int i = 0; i < 6; i++) {
array[i] = -1;
}
}
static boolean array_check2(String name) {
boolean success = true;
for (int i = 0; i < 6; i++) {
if (array[i] != 999) {
success = false;
System.out.println(name + " failed: array[" + i + "] = " + array[i]);
}
}
return success;
}
static void array_init3() {
for (int i = 0; i < 3; i++) {
array[i] = -1;
}
}
static boolean array_check3(String name) {
boolean success = true;
for (int i = 0; i < 3; i++) {
if (array[i] != i) {
success = false;
System.out.println(name + " failed: array[" + i + "] = " + array[i]);
}
}
return success;
}
static void array_init4() {
for (int i = 0; i < 3; i++) {
byte_array[i] = -1;
}
}
static boolean array_check4(String name) {
boolean success = true;
for (int i = 0; i < 3; i++) {
if (byte_array[i] != i) {
success = false;
System.out.println(name + " failed: byte_array[" + i + "] = " + byte_array[i]);
}
}
return success;
}
static boolean array_check5(String name) {
boolean success = true;
for (int i = 0; i < 1000; i++) {
if (array4[i] != 42) {
success = false;
System.out.println(name + " failed: array[" + i + "] = " + array4[i]);
}
}
return success;
}
static public void main(String[] args) throws Exception {
TestMoveStoresOutOfLoops test = new TestMoveStoresOutOfLoops();
test.doTest("test_after_1", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_2", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_3", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_4", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_5", TestMoveStoresOutOfLoops::array_init2, TestMoveStoresOutOfLoops::array_check2);
test.doTest("test_after_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
array3[999] = true;
test.doTest("test_after_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_7", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check5);
test.doTest("test_stores_1", TestMoveStoresOutOfLoops::array_init3, TestMoveStoresOutOfLoops::array_check3);
test.doTest("test_stores_2", TestMoveStoresOutOfLoops::array_init3, TestMoveStoresOutOfLoops::array_check3);
test.doTest("test_stores_3", TestMoveStoresOutOfLoops::array_init4, TestMoveStoresOutOfLoops::array_check4);
test.doTest("test_before_1", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_2", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_3", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_4", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_5", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
if (!test.success) {
throw new RuntimeException("Some tests failed");
}
}
}
| HashMap |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations. [MASK] .global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations. [MASK] .global.InternalGlobal;
import org.elasticsearch.search.aggregations. [MASK] .histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations. [MASK] .histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| bucket |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier. [MASK] (uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier. [MASK] (uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier. [MASK] (newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| forUidHash |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack. [MASK] .boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack. [MASK] .AnalyticsPlugin;
import org.elasticsearch.xpack. [MASK] .aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| analytics |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String [MASK] =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
[MASK] ,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String [MASK] =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
[MASK] ,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String [MASK] =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
[MASK] ,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String [MASK] =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
[MASK] ,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| originalSavepoint |
/*
* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
package build.tools.projectcreator;
class ArgIterator {
String[] args;
int i;
ArgIterator(String[] args) {
this.args = args;
this.i = 0;
}
String get() { return args[i]; }
boolean hasMore() { return args != null && i < args.length; }
boolean next() { return ++i < args.length; }
}
abstract class ArgHandler {
public abstract void handle(ArgIterator it);
}
class ArgRule {
String arg;
ArgHandler handler;
ArgRule(String arg, ArgHandler handler) {
this.arg = arg;
this.handler = handler;
}
boolean process(ArgIterator it) {
if (match(it.get(), arg)) {
handler.handle(it);
return true;
}
return false;
}
boolean match(String rule_pattern, String arg) {
return arg.equals(rule_pattern);
}
}
class ArgsParser {
ArgsParser(String[] args,
ArgRule[] rules,
ArgHandler defaulter) {
ArgIterator ai = new ArgIterator(args);
while (ai.hasMore()) {
boolean [MASK] = false;
for (int i=0; i<rules.length; i++) {
[MASK] |= rules[i].process(ai);
if ( [MASK] ) {
break;
}
}
if (! [MASK] ) {
if (defaulter != null) {
defaulter.handle(ai);
} else {
System.err.println("ERROR: unparsed \""+ai.get()+"\"");
ai.next();
}
}
}
}
}
| processed |
package org.redisson.tomcat;
import java.io.IOException;
import javax. [MASK] .ServletException;
import javax. [MASK] .http.HttpServlet;
import javax. [MASK] .http.HttpServletRequest;
import javax. [MASK] .http.HttpServletResponse;
import javax. [MASK] .http.HttpSession;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1243830648280853203L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
if (req.getPathInfo().equals("/write")) {
String[] params = req.getQueryString().split("&");
String key = null;
String value = null;
for (String param : params) {
String[] paramLine = param.split("=");
String keyParam = paramLine[0];
String valueParam = paramLine[1];
if ("key".equals(keyParam)) {
key = valueParam;
}
if ("value".equals(keyParam)) {
value = valueParam;
}
}
session.setAttribute(key, value);
resp.getWriter().print("OK");
} else if (req.getPathInfo().equals("/read")) {
String[] params = req.getQueryString().split("&");
String key = null;
for (String param : params) {
String[] line = param.split("=");
String keyParam = line[0];
if ("key".equals(keyParam)) {
key = line[1];
}
}
Object attr = session.getAttribute(key);
resp.getWriter().print(attr);
} else if (req.getPathInfo().equals("/remove")) {
String[] params = req.getQueryString().split("&");
String key = null;
for (String param : params) {
String[] line = param.split("=");
String keyParam = line[0];
if ("key".equals(keyParam)) {
key = line[1];
}
}
session.removeAttribute(key);
resp.getWriter().print(String.valueOf(session.getAttribute(key)));
} else if (req.getPathInfo().equals("/invalidate")) {
session.invalidate();
resp.getWriter().print("OK");
} else if (req.getPathInfo().equals("/recreate")) {
session.invalidate();
session = req.getSession();
String[] params = req.getQueryString().split("&");
String key = null;
String value = null;
for (String param : params) {
String[] paramLine = param.split("=");
String keyParam = paramLine[0];
String valueParam = paramLine[1];
if ("key".equals(keyParam)) {
key = valueParam;
}
if ("value".equals(keyParam)) {
value = valueParam;
}
}
session.setAttribute(key, value);
resp.getWriter().print("OK");
}
}
}
| servlet |
/*
* Copyright (c) 2024, Intel Corporation. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Random;
import java.math.BigInteger;
import java.lang.reflect.Field;
import java.security.spec.ECParameterSpec;
import sun.security.ec.ECOperations;
import sun.security.util.ECUtil;
import sun.security.util.NamedCurve;
import sun.security.util.CurveDB;
import sun.security.ec. [MASK] .*;
import java.security.spec.ECPoint;
import sun.security.util.KnownOIDs;
import sun.security.util.math.IntegerMontgomeryFieldModuloP;
import sun.security.util.math.intpoly.*;
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec. [MASK]
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:-UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec. [MASK]
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:+UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
// This test case is NOT entirely deterministic, it uses a random seed for
// pseudo-random number generator. If a failure occurs, hardcode the seed to
// make the test case deterministic
public class ECOperationsFuzzTest {
public static void main(String[] args) throws Exception {
// Note: it might be useful to increase this number during development
final int repeat = 10000;
test(repeat);
System.out.println("Fuzz Success");
}
private static void check(MutablePoint reference, MutablePoint testValue,
long seed, int iter) {
AffinePoint affineRef = reference.asAffine();
AffinePoint affine = testValue.asAffine();
if (!affineRef.equals(affine)) {
throw new RuntimeException(
"Found error with seed " + seed + "at iteration " + iter);
}
}
public static void test(int repeat) throws Exception {
Random rnd = new Random();
long seed = rnd.nextLong();
rnd.setSeed(seed);
int keySize = 256;
ECParameterSpec params = ECUtil.getECParameterSpec(keySize);
NamedCurve curve = CurveDB.lookup(KnownOIDs.secp256r1.value());
ECPoint generator = curve.getGenerator();
BigInteger b = curve.getCurve().getB();
if (params == null || generator == null) {
throw new RuntimeException(
"No EC parameters available for key size " + keySize + " bits");
}
ECOperations ops = ECOperations.forParameters(params).get();
ECOperations opsReference = new ECOperations(
IntegerPolynomialP256.ONE.getElement(b), P256OrderField.ONE);
boolean instanceTest1 = ops
.getField() instanceof IntegerMontgomeryFieldModuloP;
boolean instanceTest2 = opsReference
.getField() instanceof IntegerMontgomeryFieldModuloP;
if (instanceTest1 == false || instanceTest2 == true) {
throw new RuntimeException("Bad Initialization: ["
+ instanceTest1 + "," + instanceTest2 + "]");
}
byte[] multiple = new byte[keySize / 8];
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // from opsReference.seedToScalar(multiple);
MutablePoint referencePoint = opsReference.multiply(generator, multiple);
MutablePoint [MASK] = ops.multiply(generator, multiple);
check(referencePoint, [MASK] , seed, -1);
AffinePoint refAffineGenerator = AffinePoint.fromECPoint(generator,
referencePoint.getField());
AffinePoint montAffineGenerator = AffinePoint.fromECPoint(generator,
[MASK] .getField());
MutablePoint refProjGenerator = new ProjectivePoint.Mutable(
refAffineGenerator.getX(false).mutable(),
refAffineGenerator.getY(false).mutable(),
referencePoint.getField().get1().mutable());
MutablePoint projGenerator = new ProjectivePoint.Mutable(
montAffineGenerator.getX(false).mutable(),
montAffineGenerator.getY(false).mutable(),
[MASK] .getField().get1().mutable());
for (int i = 0; i < repeat; i++) {
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // opsReference.seedToScalar(multiple);
MutablePoint nextReferencePoint = opsReference
.multiply(referencePoint.asAffine(), multiple);
MutablePoint nextPoint = ops.multiply( [MASK] .asAffine().toECPoint(),
multiple);
check(nextReferencePoint, nextPoint, seed, i);
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, referencePoint);
ops.setSum(nextPoint, [MASK] );
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, refProjGenerator);
ops.setSum(nextPoint, projGenerator);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextInt(100) < 10) { // 10% Reset [MASK] to generator, test
// generator multiplier
referencePoint = opsReference.multiply(generator, multiple);
[MASK] = ops.multiply(generator, multiple);
check(referencePoint, [MASK] , seed, i);
} else {
referencePoint = nextReferencePoint;
[MASK] = nextPoint;
}
}
}
}
// make test TEST="test/jdk/com/sun/security/ec/ECOperationsFuzzTest.java" | point |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String [MASK] = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put( [MASK] , vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, [MASK] , Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, [MASK] , Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, [MASK] , Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| VALUE_SCRIPT |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint. [MASK] ;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.get [MASK] s().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set< [MASK] > operators =
metadata.get [MASK] s().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set< [MASK] > operators =
metadata.get [MASK] s().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| OperatorState |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
[MASK] (new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
[MASK] (new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
[MASK] (new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
[MASK] (new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
[MASK] (new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
[MASK] (iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
[MASK] (iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> [MASK] (iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> [MASK] (iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> [MASK] (iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
[MASK] (iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
[MASK] (iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
[MASK] (iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
[MASK] (iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
[MASK] (iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
[MASK] (iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void [MASK] (Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
[MASK] (buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| testCase |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index. [MASK] .KeywordFieldMapper;
import org.elasticsearch.index. [MASK] .MappedFieldType;
import org.elasticsearch.index. [MASK] .NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| mapper |
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8080289 8189067
* @summary Move stores out of loops if possible
*
* @run main/othervm -XX:-UseOnStackReplacement -XX:-BackgroundCompilation
* -XX:CompileCommand=dontinline,compiler.loopopts.TestMoveStoresOutOfLoops::test*
* compiler.loopopts.TestMoveStoresOutOfLoops
*/
package compiler.loopopts;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.function.Function;
public class TestMoveStoresOutOfLoops {
private static long[] array = new long[10];
private static long[] array2 = new long[10];
private static boolean[] array3 = new boolean[1000];
private static int[] array4 = new int[1000];
private static byte[] byte_array = new byte[10];
// Array store should be moved out of the loop, value stored
// should be 999, the loop should be eliminated
static void test_after_1(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
}
}
// Array store can't be moved out of loop because of following
// non loop invariant array access
static void test_after_2(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
array2[i%10] = i;
}
}
// Array store can't be moved out of loop because of following
// use
static void test_after_3(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
if (array[0] == -1) {
break;
}
}
}
// Array store can't be moved out of loop because of preceding
// use
static void test_after_4(int idx) {
for (int i = 0; i < 1000; i++) {
if (array[0] == -2) {
break;
}
array[idx] = i;
}
}
// All array stores should be moved out of the loop, one after
// the other
static void test_after_5(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
array[idx+1] = i;
array[idx+2] = i;
array[idx+3] = i;
array[idx+4] = i;
array[idx+5] = i;
}
}
// Array store can be moved after the loop but needs to be
// cloned on both exit paths
static void test_after_6(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
if (array3[i]) {
return;
}
}
}
// Array store can be moved out of the inner loop
static void test_after_7(int idx) {
for (int i = 0; i < 1000; i++) {
for (int j = 0; j <= 42; j++) {
array4[i] = j;
}
}
}
// Optimize out redundant stores
static void test_stores_1(int ignored) {
array[0] = 0;
array[1] = 1;
array[2] = 2;
array[0] = 0;
array[1] = 1;
array[2] = 2;
}
static void test_stores_2(int idx) {
array[idx+0] = 0;
array[idx+1] = 1;
array[idx+2] = 2;
array[idx+0] = 0;
array[idx+1] = 1;
array[idx+2] = 2;
}
static void test_stores_3(int idx) {
byte_array[idx+0] = 0;
byte_array[idx+1] = 1;
byte_array[idx+2] = 2;
byte_array[idx+0] = 0;
byte_array[idx+1] = 1;
byte_array[idx+2] = 2;
}
// Array store can be moved out of the loop before the loop header
static void test_before_1(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = 999;
}
}
// Array store can't be moved out of the loop before the loop
// header because there's more than one store on this slice
static void test_before_2(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = 999;
array[i%2] = 0;
}
}
// Array store can't be moved out of the loop before the loop
// header because of use before store
static int test_before_3(int idx) {
int res = 0;
for (int i = 0; i < 1000; i++) {
res += array[i%10];
array[idx] = 999;
}
return res;
}
// Array store can't be moved out of the loop before the loop
// header because of possible early exit
static void test_before_4(int idx) {
for (int i = 0; i < 1000; i++) {
if (idx / (i+1) > 0) {
return;
}
array[idx] = 999;
}
}
// Array store can't be moved out of the loop before the loop
// header because it doesn't postdominate the loop head
static void test_before_5(int idx) {
for (int i = 0; i < 1000; i++) {
if (i % 2 == 0) {
array[idx] = 999;
}
}
}
// Array store can be moved out of the loop before the loop header
static int test_before_6(int idx) {
int res = 0;
for (int i = 0; i < 1000; i++) {
if (i%2 == 1) {
res *= 2;
} else {
res++;
}
array[idx] = 999;
}
return res;
}
final HashMap<String,Method> tests = new HashMap<>();
{
for (Method m : this.getClass().getDeclaredMethods()) {
if (m.getName().matches("test_(before|after|stores)_[0-9]+")) {
assert(Modifier.isStatic(m.getModifiers())) : m;
tests.put(m.getName(), m);
}
}
}
boolean success = true;
void doTest(String name, Runnable init, Function<String, Boolean> check) throws Exception {
Method m = tests.get(name);
for (int i = 0; i < 20000; i++) {
init.run();
m.invoke(null, 0);
success = success && check.apply(name);
if (!success) {
break;
}
}
}
static void array_init() {
array[0] = -1;
}
static boolean array_check(String name) {
boolean success = true;
if (array[0] != 999) {
success = false;
[MASK] .out.println(name + " failed: array[0] = " + array[0]);
}
return success;
}
static void array_init2() {
for (int i = 0; i < 6; i++) {
array[i] = -1;
}
}
static boolean array_check2(String name) {
boolean success = true;
for (int i = 0; i < 6; i++) {
if (array[i] != 999) {
success = false;
[MASK] .out.println(name + " failed: array[" + i + "] = " + array[i]);
}
}
return success;
}
static void array_init3() {
for (int i = 0; i < 3; i++) {
array[i] = -1;
}
}
static boolean array_check3(String name) {
boolean success = true;
for (int i = 0; i < 3; i++) {
if (array[i] != i) {
success = false;
[MASK] .out.println(name + " failed: array[" + i + "] = " + array[i]);
}
}
return success;
}
static void array_init4() {
for (int i = 0; i < 3; i++) {
byte_array[i] = -1;
}
}
static boolean array_check4(String name) {
boolean success = true;
for (int i = 0; i < 3; i++) {
if (byte_array[i] != i) {
success = false;
[MASK] .out.println(name + " failed: byte_array[" + i + "] = " + byte_array[i]);
}
}
return success;
}
static boolean array_check5(String name) {
boolean success = true;
for (int i = 0; i < 1000; i++) {
if (array4[i] != 42) {
success = false;
[MASK] .out.println(name + " failed: array[" + i + "] = " + array4[i]);
}
}
return success;
}
static public void main(String[] args) throws Exception {
TestMoveStoresOutOfLoops test = new TestMoveStoresOutOfLoops();
test.doTest("test_after_1", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_2", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_3", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_4", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_5", TestMoveStoresOutOfLoops::array_init2, TestMoveStoresOutOfLoops::array_check2);
test.doTest("test_after_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
array3[999] = true;
test.doTest("test_after_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_7", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check5);
test.doTest("test_stores_1", TestMoveStoresOutOfLoops::array_init3, TestMoveStoresOutOfLoops::array_check3);
test.doTest("test_stores_2", TestMoveStoresOutOfLoops::array_init3, TestMoveStoresOutOfLoops::array_check3);
test.doTest("test_stores_3", TestMoveStoresOutOfLoops::array_init4, TestMoveStoresOutOfLoops::array_check4);
test.doTest("test_before_1", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_2", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_3", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_4", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_5", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
if (!test.success) {
throw new RuntimeException("Some tests failed");
}
}
}
| System |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter. [MASK] ()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter. [MASK] ()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String [MASK] () {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| getUidHash |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene. [MASK] .NumericDocValuesField;
import org.apache.lucene. [MASK] .SortedNumericDocValuesField;
import org.apache.lucene. [MASK] .SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| document |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util. [MASK] ;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List< [MASK] <Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for ( [MASK] <Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| CloseableIterator |
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8080289 8189067
* @summary Move stores out of loops if possible
*
* @run main/othervm -XX:-UseOnStackReplacement -XX:-BackgroundCompilation
* -XX:CompileCommand=dontinline,compiler.loopopts. [MASK] ::test*
* compiler.loopopts. [MASK]
*/
package compiler.loopopts;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.function.Function;
public class [MASK] {
private static long[] array = new long[10];
private static long[] array2 = new long[10];
private static boolean[] array3 = new boolean[1000];
private static int[] array4 = new int[1000];
private static byte[] byte_array = new byte[10];
// Array store should be moved out of the loop, value stored
// should be 999, the loop should be eliminated
static void test_after_1(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
}
}
// Array store can't be moved out of loop because of following
// non loop invariant array access
static void test_after_2(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
array2[i%10] = i;
}
}
// Array store can't be moved out of loop because of following
// use
static void test_after_3(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
if (array[0] == -1) {
break;
}
}
}
// Array store can't be moved out of loop because of preceding
// use
static void test_after_4(int idx) {
for (int i = 0; i < 1000; i++) {
if (array[0] == -2) {
break;
}
array[idx] = i;
}
}
// All array stores should be moved out of the loop, one after
// the other
static void test_after_5(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
array[idx+1] = i;
array[idx+2] = i;
array[idx+3] = i;
array[idx+4] = i;
array[idx+5] = i;
}
}
// Array store can be moved after the loop but needs to be
// cloned on both exit paths
static void test_after_6(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
if (array3[i]) {
return;
}
}
}
// Array store can be moved out of the inner loop
static void test_after_7(int idx) {
for (int i = 0; i < 1000; i++) {
for (int j = 0; j <= 42; j++) {
array4[i] = j;
}
}
}
// Optimize out redundant stores
static void test_stores_1(int ignored) {
array[0] = 0;
array[1] = 1;
array[2] = 2;
array[0] = 0;
array[1] = 1;
array[2] = 2;
}
static void test_stores_2(int idx) {
array[idx+0] = 0;
array[idx+1] = 1;
array[idx+2] = 2;
array[idx+0] = 0;
array[idx+1] = 1;
array[idx+2] = 2;
}
static void test_stores_3(int idx) {
byte_array[idx+0] = 0;
byte_array[idx+1] = 1;
byte_array[idx+2] = 2;
byte_array[idx+0] = 0;
byte_array[idx+1] = 1;
byte_array[idx+2] = 2;
}
// Array store can be moved out of the loop before the loop header
static void test_before_1(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = 999;
}
}
// Array store can't be moved out of the loop before the loop
// header because there's more than one store on this slice
static void test_before_2(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = 999;
array[i%2] = 0;
}
}
// Array store can't be moved out of the loop before the loop
// header because of use before store
static int test_before_3(int idx) {
int res = 0;
for (int i = 0; i < 1000; i++) {
res += array[i%10];
array[idx] = 999;
}
return res;
}
// Array store can't be moved out of the loop before the loop
// header because of possible early exit
static void test_before_4(int idx) {
for (int i = 0; i < 1000; i++) {
if (idx / (i+1) > 0) {
return;
}
array[idx] = 999;
}
}
// Array store can't be moved out of the loop before the loop
// header because it doesn't postdominate the loop head
static void test_before_5(int idx) {
for (int i = 0; i < 1000; i++) {
if (i % 2 == 0) {
array[idx] = 999;
}
}
}
// Array store can be moved out of the loop before the loop header
static int test_before_6(int idx) {
int res = 0;
for (int i = 0; i < 1000; i++) {
if (i%2 == 1) {
res *= 2;
} else {
res++;
}
array[idx] = 999;
}
return res;
}
final HashMap<String,Method> tests = new HashMap<>();
{
for (Method m : this.getClass().getDeclaredMethods()) {
if (m.getName().matches("test_(before|after|stores)_[0-9]+")) {
assert(Modifier.isStatic(m.getModifiers())) : m;
tests.put(m.getName(), m);
}
}
}
boolean success = true;
void doTest(String name, Runnable init, Function<String, Boolean> check) throws Exception {
Method m = tests.get(name);
for (int i = 0; i < 20000; i++) {
init.run();
m.invoke(null, 0);
success = success && check.apply(name);
if (!success) {
break;
}
}
}
static void array_init() {
array[0] = -1;
}
static boolean array_check(String name) {
boolean success = true;
if (array[0] != 999) {
success = false;
System.out.println(name + " failed: array[0] = " + array[0]);
}
return success;
}
static void array_init2() {
for (int i = 0; i < 6; i++) {
array[i] = -1;
}
}
static boolean array_check2(String name) {
boolean success = true;
for (int i = 0; i < 6; i++) {
if (array[i] != 999) {
success = false;
System.out.println(name + " failed: array[" + i + "] = " + array[i]);
}
}
return success;
}
static void array_init3() {
for (int i = 0; i < 3; i++) {
array[i] = -1;
}
}
static boolean array_check3(String name) {
boolean success = true;
for (int i = 0; i < 3; i++) {
if (array[i] != i) {
success = false;
System.out.println(name + " failed: array[" + i + "] = " + array[i]);
}
}
return success;
}
static void array_init4() {
for (int i = 0; i < 3; i++) {
byte_array[i] = -1;
}
}
static boolean array_check4(String name) {
boolean success = true;
for (int i = 0; i < 3; i++) {
if (byte_array[i] != i) {
success = false;
System.out.println(name + " failed: byte_array[" + i + "] = " + byte_array[i]);
}
}
return success;
}
static boolean array_check5(String name) {
boolean success = true;
for (int i = 0; i < 1000; i++) {
if (array4[i] != 42) {
success = false;
System.out.println(name + " failed: array[" + i + "] = " + array4[i]);
}
}
return success;
}
static public void main(String[] args) throws Exception {
[MASK] test = new [MASK] ();
test.doTest("test_after_1", [MASK] ::array_init, [MASK] ::array_check);
test.doTest("test_after_2", [MASK] ::array_init, [MASK] ::array_check);
test.doTest("test_after_3", [MASK] ::array_init, [MASK] ::array_check);
test.doTest("test_after_4", [MASK] ::array_init, [MASK] ::array_check);
test.doTest("test_after_5", [MASK] ::array_init2, [MASK] ::array_check2);
test.doTest("test_after_6", [MASK] ::array_init, [MASK] ::array_check);
array3[999] = true;
test.doTest("test_after_6", [MASK] ::array_init, [MASK] ::array_check);
test.doTest("test_after_7", [MASK] ::array_init, [MASK] ::array_check5);
test.doTest("test_stores_1", [MASK] ::array_init3, [MASK] ::array_check3);
test.doTest("test_stores_2", [MASK] ::array_init3, [MASK] ::array_check3);
test.doTest("test_stores_3", [MASK] ::array_init4, [MASK] ::array_check4);
test.doTest("test_before_1", [MASK] ::array_init, [MASK] ::array_check);
test.doTest("test_before_2", [MASK] ::array_init, [MASK] ::array_check);
test.doTest("test_before_3", [MASK] ::array_init, [MASK] ::array_check);
test.doTest("test_before_4", [MASK] ::array_init, [MASK] ::array_check);
test.doTest("test_before_5", [MASK] ::array_init, [MASK] ::array_check);
test.doTest("test_before_6", [MASK] ::array_init, [MASK] ::array_check);
if (!test.success) {
throw new RuntimeException("Some tests failed");
}
}
}
| TestMoveStoresOutOfLoops |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model. [MASK] ;
import javax.lang.model.element.TypeElement;
@SupportedAnnotationTypes("*")
public class SimpleProcessor extends AbstractProcessor {
@Override
public [MASK] getSupported [MASK] () {
return [MASK] .latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
return false;
}
} | SourceVersion |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io. [MASK] ;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws [MASK] {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws [MASK] {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws [MASK] {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws [MASK] {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws [MASK] {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws [MASK] {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws [MASK] {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws [MASK] {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws [MASK] {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws [MASK] {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws [MASK] {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws [MASK] {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws [MASK] {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, [MASK] > buildIndex, Consumer<InternalBoxplot> verify)
throws [MASK] {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| IOException |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink. [MASK] ing.api.data [MASK] .SingleOutputStreamOperator;
import org.apache.flink. [MASK] ing.api.environment.StreamExecutionEnvironment;
import org.apache.flink. [MASK] ing.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util. [MASK] .Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates(). [MASK] ()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates(). [MASK] ()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> [MASK] =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add( [MASK] .uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add( [MASK] .setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph [MASK] Graph = env.getStreamGraph();
[MASK] Graph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync( [MASK] Graph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| stream |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.Checked [MASK] ;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function. [MASK] ;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, ( [MASK] <InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, ( [MASK] <InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
( [MASK] <InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
( [MASK] <InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
( [MASK] <InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, ( [MASK] <InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, ( [MASK] <InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, ( [MASK] <InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, ( [MASK] <InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, ( [MASK] <InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, ( [MASK] <InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, Checked [MASK] <RandomIndexWriter, IOException> buildIndex, [MASK] <InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| Consumer |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
[MASK] (
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
[MASK] (
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
[MASK] (
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
[MASK] (
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String [MASK] (
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| modifySavepoint |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = [MASK] (IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
[MASK] (NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
[MASK] (NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| expectThrows |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink. [MASK] .checkpoint.OperatorState;
import org.apache.flink. [MASK] .checkpoint.metadata.CheckpointMetadata;
import org.apache.flink. [MASK] .jobgraph.SavepointRestoreSettings;
import org.apache.flink. [MASK] .testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api. [MASK] .SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| runtime |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer. [MASK] (
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer. [MASK] (
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer. [MASK] (
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer. [MASK] (
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
. [MASK] (
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| changeOperatorIdentifier |
/*
* Copyright (c) 2024, Intel Corporation. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Random;
import java.math.BigInteger;
import java.lang.reflect.Field;
import java.security.spec.ECParameterSpec;
import sun.security.ec.ECOperations;
import sun.security.util.ECUtil;
import sun.security.util.NamedCurve;
import sun.security.util.CurveDB;
import sun.security.ec.point.*;
import java.security.spec.ECPoint;
import sun.security.util.KnownOIDs;
import sun.security.util.math.IntegerMontgomeryFieldModuloP;
import sun.security.util.math.intpoly.*;
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:-UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:+UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
// This test case is NOT entirely deterministic, it uses a random seed for
// pseudo-random number generator. If a failure occurs, hardcode the seed to
// make the test case deterministic
public class ECOperationsFuzzTest {
public static void main(String[] args) throws Exception {
// Note: it might be useful to increase this number during development
final int repeat = 10000;
test(repeat);
System.out.println("Fuzz Success");
}
private static void check(MutablePoint reference, MutablePoint testValue,
long seed, int iter) {
[MASK] affineRef = reference.asAffine();
[MASK] affine = testValue.asAffine();
if (!affineRef.equals(affine)) {
throw new RuntimeException(
"Found error with seed " + seed + "at iteration " + iter);
}
}
public static void test(int repeat) throws Exception {
Random rnd = new Random();
long seed = rnd.nextLong();
rnd.setSeed(seed);
int keySize = 256;
ECParameterSpec params = ECUtil.getECParameterSpec(keySize);
NamedCurve curve = CurveDB.lookup(KnownOIDs.secp256r1.value());
ECPoint generator = curve.getGenerator();
BigInteger b = curve.getCurve().getB();
if (params == null || generator == null) {
throw new RuntimeException(
"No EC parameters available for key size " + keySize + " bits");
}
ECOperations ops = ECOperations.forParameters(params).get();
ECOperations opsReference = new ECOperations(
IntegerPolynomialP256.ONE.getElement(b), P256OrderField.ONE);
boolean instanceTest1 = ops
.getField() instanceof IntegerMontgomeryFieldModuloP;
boolean instanceTest2 = opsReference
.getField() instanceof IntegerMontgomeryFieldModuloP;
if (instanceTest1 == false || instanceTest2 == true) {
throw new RuntimeException("Bad Initialization: ["
+ instanceTest1 + "," + instanceTest2 + "]");
}
byte[] multiple = new byte[keySize / 8];
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // from opsReference.seedToScalar(multiple);
MutablePoint referencePoint = opsReference.multiply(generator, multiple);
MutablePoint point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, -1);
[MASK] refAffineGenerator = [MASK] .fromECPoint(generator,
referencePoint.getField());
[MASK] montAffineGenerator = [MASK] .fromECPoint(generator,
point.getField());
MutablePoint refProjGenerator = new ProjectivePoint.Mutable(
refAffineGenerator.getX(false).mutable(),
refAffineGenerator.getY(false).mutable(),
referencePoint.getField().get1().mutable());
MutablePoint projGenerator = new ProjectivePoint.Mutable(
montAffineGenerator.getX(false).mutable(),
montAffineGenerator.getY(false).mutable(),
point.getField().get1().mutable());
for (int i = 0; i < repeat; i++) {
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // opsReference.seedToScalar(multiple);
MutablePoint nextReferencePoint = opsReference
.multiply(referencePoint.asAffine(), multiple);
MutablePoint nextPoint = ops.multiply(point.asAffine().toECPoint(),
multiple);
check(nextReferencePoint, nextPoint, seed, i);
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, referencePoint);
ops.setSum(nextPoint, point);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, refProjGenerator);
ops.setSum(nextPoint, projGenerator);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextInt(100) < 10) { // 10% Reset point to generator, test
// generator multiplier
referencePoint = opsReference.multiply(generator, multiple);
point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, i);
} else {
referencePoint = nextReferencePoint;
point = nextPoint;
}
}
}
}
// make test TEST="test/jdk/com/sun/security/ec/ECOperationsFuzzTest.java" | AffinePoint |
/*
* Copyright (c) 2024, Intel Corporation. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Random;
import java.math.BigInteger;
import java.lang.reflect.Field;
import java.security.spec.ECParameterSpec;
import sun.security.ec.ECOperations;
import sun.security.util.ECUtil;
import sun.security.util.NamedCurve;
import sun.security.util.CurveDB;
import sun.security.ec.point.*;
import java.security.spec.ECPoint;
import sun.security.util.KnownOIDs;
import sun.security.util.math.IntegerMontgomeryFieldModuloP;
import sun.security.util.math.intpoly.*;
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:-UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:+UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
// This test case is NOT entirely deterministic, it uses a random seed for
// pseudo-random number generator. If a failure occurs, hardcode the seed to
// make the test case deterministic
public class ECOperationsFuzzTest {
public static void main(String[] args) throws Exception {
// Note: it might be useful to increase this number during development
final int repeat = 10000;
test(repeat);
System.out.println("Fuzz Success");
}
private static void check(MutablePoint reference, MutablePoint testValue,
long seed, int iter) {
AffinePoint affineRef = reference.asAffine();
AffinePoint affine = testValue.asAffine();
if (!affineRef.equals(affine)) {
throw new RuntimeException(
"Found error with seed " + seed + "at iteration " + iter);
}
}
public static void test(int repeat) throws Exception {
Random rnd = new Random();
long seed = rnd.nextLong();
rnd.setSeed(seed);
int keySize = 256;
ECParameterSpec params = ECUtil.getECParameterSpec(keySize);
NamedCurve curve = CurveDB.lookup(KnownOIDs.secp256r1.value());
ECPoint generator = curve.getGenerator();
BigInteger b = curve.getCurve().getB();
if (params == null || generator == null) {
throw new RuntimeException(
"No EC parameters available for key size " + keySize + " bits");
}
ECOperations ops = ECOperations.forParameters(params).get();
ECOperations [MASK] = new ECOperations(
IntegerPolynomialP256.ONE.getElement(b), P256OrderField.ONE);
boolean instanceTest1 = ops
.getField() instanceof IntegerMontgomeryFieldModuloP;
boolean instanceTest2 = [MASK]
.getField() instanceof IntegerMontgomeryFieldModuloP;
if (instanceTest1 == false || instanceTest2 == true) {
throw new RuntimeException("Bad Initialization: ["
+ instanceTest1 + "," + instanceTest2 + "]");
}
byte[] multiple = new byte[keySize / 8];
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // from [MASK] .seedToScalar(multiple);
MutablePoint referencePoint = [MASK] .multiply(generator, multiple);
MutablePoint point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, -1);
AffinePoint refAffineGenerator = AffinePoint.fromECPoint(generator,
referencePoint.getField());
AffinePoint montAffineGenerator = AffinePoint.fromECPoint(generator,
point.getField());
MutablePoint refProjGenerator = new ProjectivePoint.Mutable(
refAffineGenerator.getX(false).mutable(),
refAffineGenerator.getY(false).mutable(),
referencePoint.getField().get1().mutable());
MutablePoint projGenerator = new ProjectivePoint.Mutable(
montAffineGenerator.getX(false).mutable(),
montAffineGenerator.getY(false).mutable(),
point.getField().get1().mutable());
for (int i = 0; i < repeat; i++) {
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // [MASK] .seedToScalar(multiple);
MutablePoint nextReferencePoint = [MASK]
.multiply(referencePoint.asAffine(), multiple);
MutablePoint nextPoint = ops.multiply(point.asAffine().toECPoint(),
multiple);
check(nextReferencePoint, nextPoint, seed, i);
if (rnd.nextBoolean()) {
[MASK] .setSum(nextReferencePoint, referencePoint);
ops.setSum(nextPoint, point);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextBoolean()) {
[MASK] .setSum(nextReferencePoint, refProjGenerator);
ops.setSum(nextPoint, projGenerator);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextInt(100) < 10) { // 10% Reset point to generator, test
// generator multiplier
referencePoint = [MASK] .multiply(generator, multiple);
point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, i);
} else {
referencePoint = nextReferencePoint;
point = nextPoint;
}
}
}
}
// make test TEST="test/jdk/com/sun/security/ec/ECOperationsFuzzTest.java" | opsReference |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5. [MASK] ;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final [MASK] MINI_CLUSTER_RESOURCE =
new [MASK] (
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| MiniClusterExtension |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram. [MASK] ;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
[MASK] histogram = new [MASK] ("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| HistogramAggregationBuilder |
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.jdbc.core.metadata;
import java.sql.DatabaseMetaData;
import org.jspecify.annotations.Nullable;
/**
* Holder of meta-data for a specific parameter that is used for call processing.
*
* @author Thomas Risberg
* @author Juergen Hoeller
* @since 2.5
* @see GenericCallMetaDataProvider
*/
public class CallParameterMetaData {
private final boolean function;
private final @Nullable String [MASK] ;
private final int parameterType;
private final int sqlType;
private final @Nullable String typeName;
private final boolean nullable;
/**
* Constructor taking all the properties including the function marker.
* @since 5.2.9
*/
public CallParameterMetaData(boolean function, @Nullable String columnName, int columnType,
int sqlType, @Nullable String typeName, boolean nullable) {
this.function = function;
this. [MASK] = columnName;
this.parameterType = columnType;
this.sqlType = sqlType;
this.typeName = typeName;
this.nullable = nullable;
}
/**
* Return whether this parameter is declared in a function.
* @since 5.2.9
*/
public boolean isFunction() {
return this.function;
}
/**
* Return the parameter name.
*/
public @Nullable String getParameterName() {
return this. [MASK] ;
}
/**
* Return the parameter type.
*/
public int getParameterType() {
return this.parameterType;
}
/**
* Determine whether the declared parameter qualifies as a 'return' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnReturn} or
* {@link DatabaseMetaData#procedureColumnResult}, or in case of a function,
* {@link DatabaseMetaData#functionReturn}.
* @since 4.3.15
*/
public boolean isReturnParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionReturn :
(this.parameterType == DatabaseMetaData.procedureColumnReturn ||
this.parameterType == DatabaseMetaData.procedureColumnResult));
}
/**
* Determine whether the declared parameter qualifies as an 'out' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnOut},
* or in case of a function, {@link DatabaseMetaData#functionColumnOut}.
* @since 5.3.31
*/
public boolean isOutParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionColumnOut :
this.parameterType == DatabaseMetaData.procedureColumnOut);
}
/**
* Determine whether the declared parameter qualifies as an 'in-out' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnInOut},
* or in case of a function, {@link DatabaseMetaData#functionColumnInOut}.
* @since 5.3.31
*/
public boolean isInOutParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionColumnInOut :
this.parameterType == DatabaseMetaData.procedureColumnInOut);
}
/**
* Return the parameter SQL type.
*/
public int getSqlType() {
return this.sqlType;
}
/**
* Return the parameter type name.
*/
public @Nullable String getTypeName() {
return this.typeName;
}
/**
* Return whether the parameter is nullable.
*/
public boolean isNullable() {
return this.nullable;
}
}
| parameterName |
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.jdbc.core.metadata;
import java.sql.DatabaseMetaData;
import org.jspecify.annotations.Nullable;
/**
* Holder of meta-data for a specific parameter that is used for call processing.
*
* @author Thomas Risberg
* @author Juergen Hoeller
* @since 2.5
* @see GenericCallMetaDataProvider
*/
public class CallParameterMetaData {
private final boolean function;
private final @Nullable String parameterName;
private final int parameterType;
private final int [MASK] ;
private final @Nullable String typeName;
private final boolean nullable;
/**
* Constructor taking all the properties including the function marker.
* @since 5.2.9
*/
public CallParameterMetaData(boolean function, @Nullable String columnName, int columnType,
int [MASK] , @Nullable String typeName, boolean nullable) {
this.function = function;
this.parameterName = columnName;
this.parameterType = columnType;
this. [MASK] = [MASK] ;
this.typeName = typeName;
this.nullable = nullable;
}
/**
* Return whether this parameter is declared in a function.
* @since 5.2.9
*/
public boolean isFunction() {
return this.function;
}
/**
* Return the parameter name.
*/
public @Nullable String getParameterName() {
return this.parameterName;
}
/**
* Return the parameter type.
*/
public int getParameterType() {
return this.parameterType;
}
/**
* Determine whether the declared parameter qualifies as a 'return' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnReturn} or
* {@link DatabaseMetaData#procedureColumnResult}, or in case of a function,
* {@link DatabaseMetaData#functionReturn}.
* @since 4.3.15
*/
public boolean isReturnParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionReturn :
(this.parameterType == DatabaseMetaData.procedureColumnReturn ||
this.parameterType == DatabaseMetaData.procedureColumnResult));
}
/**
* Determine whether the declared parameter qualifies as an 'out' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnOut},
* or in case of a function, {@link DatabaseMetaData#functionColumnOut}.
* @since 5.3.31
*/
public boolean isOutParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionColumnOut :
this.parameterType == DatabaseMetaData.procedureColumnOut);
}
/**
* Determine whether the declared parameter qualifies as an 'in-out' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnInOut},
* or in case of a function, {@link DatabaseMetaData#functionColumnInOut}.
* @since 5.3.31
*/
public boolean isInOutParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionColumnInOut :
this.parameterType == DatabaseMetaData.procedureColumnInOut);
}
/**
* Return the parameter SQL type.
*/
public int getSqlType() {
return this. [MASK] ;
}
/**
* Return the parameter type name.
*/
public @Nullable String getTypeName() {
return this.typeName;
}
/**
* Return whether the parameter is nullable.
*/
public boolean isNullable() {
return this.nullable;
}
}
| sqlType |
/*
* Copyright (c) 2024, Intel Corporation. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Random;
import java.math.BigInteger;
import java.lang.reflect.Field;
import java.security.spec.ECParameterSpec;
import sun.security.ec.ECOperations;
import sun.security.util.ECUtil;
import sun.security.util.NamedCurve;
import sun.security.util.CurveDB;
import sun.security.ec.point.*;
import java.security.spec.ECPoint;
import sun.security.util.KnownOIDs;
import sun.security.util.math.IntegerMontgomeryFieldModuloP;
import sun.security.util.math.intpoly.*;
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:-UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:+UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
// This test case is NOT entirely deterministic, it uses a random seed for
// pseudo-random number generator. If a failure occurs, hardcode the seed to
// make the test case deterministic
public class ECOperationsFuzzTest {
public static void main(String[] args) throws Exception {
// Note: it might be useful to increase this number during development
final int repeat = 10000;
test(repeat);
System.out.println("Fuzz Success");
}
private static void check(MutablePoint reference, MutablePoint testValue,
long seed, int iter) {
AffinePoint affineRef = reference.asAffine();
AffinePoint affine = testValue.asAffine();
if (!affineRef.equals(affine)) {
throw new RuntimeException(
"Found error with seed " + seed + "at iteration " + iter);
}
}
public static void test(int repeat) throws Exception {
Random rnd = new Random();
long seed = rnd.nextLong();
rnd.setSeed(seed);
int keySize = 256;
ECParameterSpec params = ECUtil.getECParameterSpec(keySize);
NamedCurve curve = CurveDB.lookup(KnownOIDs.secp256r1.value());
ECPoint generator = curve.getGenerator();
BigInteger b = curve.getCurve().getB();
if (params == null || generator == null) {
throw new RuntimeException(
"No EC parameters available for key size " + keySize + " bits");
}
ECOperations ops = ECOperations.forParameters(params).get();
ECOperations opsReference = new ECOperations(
IntegerPolynomialP256.ONE.getElement(b), P256OrderField.ONE);
boolean instanceTest1 = ops
.getField() instanceof IntegerMontgomeryFieldModuloP;
boolean instanceTest2 = opsReference
.getField() instanceof IntegerMontgomeryFieldModuloP;
if (instanceTest1 == false || instanceTest2 == true) {
throw new RuntimeException("Bad Initialization: ["
+ instanceTest1 + "," + instanceTest2 + "]");
}
byte[] multiple = new byte[keySize / 8];
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // from opsReference.seedToScalar(multiple);
MutablePoint referencePoint = opsReference.multiply(generator, multiple);
MutablePoint point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, -1);
AffinePoint refAffineGenerator = AffinePoint.fromECPoint(generator,
referencePoint.getField());
AffinePoint montAffineGenerator = AffinePoint.fromECPoint(generator,
point.getField());
MutablePoint refProjGenerator = new ProjectivePoint.Mutable(
refAffineGenerator.getX(false).mutable(),
refAffineGenerator.getY(false).mutable(),
referencePoint.getField().get1().mutable());
MutablePoint projGenerator = new ProjectivePoint.Mutable(
montAffineGenerator.getX(false).mutable(),
montAffineGenerator.getY(false).mutable(),
point.getField().get1().mutable());
for (int i = 0; i < repeat; i++) {
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // opsReference.seedToScalar(multiple);
MutablePoint [MASK] = opsReference
.multiply(referencePoint.asAffine(), multiple);
MutablePoint nextPoint = ops.multiply(point.asAffine().toECPoint(),
multiple);
check( [MASK] , nextPoint, seed, i);
if (rnd.nextBoolean()) {
opsReference.setSum( [MASK] , referencePoint);
ops.setSum(nextPoint, point);
check( [MASK] , nextPoint, seed, i);
}
if (rnd.nextBoolean()) {
opsReference.setSum( [MASK] , refProjGenerator);
ops.setSum(nextPoint, projGenerator);
check( [MASK] , nextPoint, seed, i);
}
if (rnd.nextInt(100) < 10) { // 10% Reset point to generator, test
// generator multiplier
referencePoint = opsReference.multiply(generator, multiple);
point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, i);
} else {
referencePoint = [MASK] ;
point = nextPoint;
}
}
}
}
// make test TEST="test/jdk/com/sun/security/ec/ECOperationsFuzzTest.java" | nextReferencePoint |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, [MASK] .of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, [MASK] .of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, [MASK] .of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
[MASK] .of(STATE_1, uid2, null),
[MASK] .of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, [MASK] ... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for ( [MASK] validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for ( [MASK] validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class [MASK] {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public [MASK] (
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static [MASK] of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new [MASK] (state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| ValidationParameters |
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.jdbc.core.metadata;
import java.sql.DatabaseMetaData;
import org.jspecify.annotations.Nullable;
/**
* Holder of meta-data for a specific parameter that is used for call processing.
*
* @author Thomas Risberg
* @author Juergen Hoeller
* @since 2.5
* @see GenericCallMetaDataProvider
*/
public class CallParameterMetaData {
private final boolean function;
private final @Nullable String parameterName;
private final int parameterType;
private final int sqlType;
private final @Nullable String typeName;
private final boolean [MASK] ;
/**
* Constructor taking all the properties including the function marker.
* @since 5.2.9
*/
public CallParameterMetaData(boolean function, @Nullable String columnName, int columnType,
int sqlType, @Nullable String typeName, boolean [MASK] ) {
this.function = function;
this.parameterName = columnName;
this.parameterType = columnType;
this.sqlType = sqlType;
this.typeName = typeName;
this. [MASK] = [MASK] ;
}
/**
* Return whether this parameter is declared in a function.
* @since 5.2.9
*/
public boolean isFunction() {
return this.function;
}
/**
* Return the parameter name.
*/
public @Nullable String getParameterName() {
return this.parameterName;
}
/**
* Return the parameter type.
*/
public int getParameterType() {
return this.parameterType;
}
/**
* Determine whether the declared parameter qualifies as a 'return' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnReturn} or
* {@link DatabaseMetaData#procedureColumnResult}, or in case of a function,
* {@link DatabaseMetaData#functionReturn}.
* @since 4.3.15
*/
public boolean isReturnParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionReturn :
(this.parameterType == DatabaseMetaData.procedureColumnReturn ||
this.parameterType == DatabaseMetaData.procedureColumnResult));
}
/**
* Determine whether the declared parameter qualifies as an 'out' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnOut},
* or in case of a function, {@link DatabaseMetaData#functionColumnOut}.
* @since 5.3.31
*/
public boolean isOutParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionColumnOut :
this.parameterType == DatabaseMetaData.procedureColumnOut);
}
/**
* Determine whether the declared parameter qualifies as an 'in-out' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnInOut},
* or in case of a function, {@link DatabaseMetaData#functionColumnInOut}.
* @since 5.3.31
*/
public boolean isInOutParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionColumnInOut :
this.parameterType == DatabaseMetaData.procedureColumnInOut);
}
/**
* Return the parameter SQL type.
*/
public int getSqlType() {
return this.sqlType;
}
/**
* Return the parameter type name.
*/
public @Nullable String getTypeName() {
return this.typeName;
}
/**
* Return whether the parameter is [MASK] .
*/
public boolean isNullable() {
return this. [MASK] ;
}
}
| nullable |
/*
* Copyright (c) 2024, Intel Corporation. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Random;
import java.math.BigInteger;
import java.lang.reflect.Field;
import java.security.spec.ECParameterSpec;
import sun.security.ec.ECOperations;
import sun.security.util.ECUtil;
import sun.security.util.NamedCurve;
import sun.security.util.CurveDB;
import sun.security.ec.point.*;
import java.security.spec.ECPoint;
import sun.security.util.KnownOIDs;
import sun.security.util.math.IntegerMontgomeryFieldModuloP;
import sun.security.util.math.intpoly.*;
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:-UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:+UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
// This test case is NOT entirely deterministic, it uses a random seed for
// pseudo-random number generator. If a failure occurs, hardcode the seed to
// make the test case deterministic
public class ECOperationsFuzzTest {
public static void main(String[] args) throws Exception {
// Note: it might be useful to increase this number during development
final int repeat = 10000;
test(repeat);
System.out.println("Fuzz Success");
}
private static void check(MutablePoint reference, MutablePoint testValue,
long seed, int iter) {
AffinePoint affineRef = reference.asAffine();
AffinePoint affine = testValue.asAffine();
if (!affineRef.equals(affine)) {
throw new RuntimeException(
"Found error with seed " + seed + "at iteration " + iter);
}
}
public static void test(int repeat) throws Exception {
Random rnd = new Random();
long seed = rnd.nextLong();
rnd.setSeed(seed);
int keySize = 256;
ECParameterSpec params = ECUtil.getECParameterSpec(keySize);
NamedCurve curve = CurveDB.lookup(KnownOIDs.secp256r1.value());
ECPoint generator = curve.getGenerator();
BigInteger b = curve.getCurve().getB();
if (params == null || generator == null) {
throw new RuntimeException(
"No EC parameters available for key size " + keySize + " bits");
}
ECOperations ops = ECOperations.forParameters(params).get();
ECOperations opsReference = new ECOperations(
IntegerPolynomialP256.ONE.getElement(b), P256OrderField.ONE);
boolean instanceTest1 = ops
.getField() instanceof IntegerMontgomeryFieldModuloP;
boolean instanceTest2 = opsReference
.getField() instanceof IntegerMontgomeryFieldModuloP;
if (instanceTest1 == false || instanceTest2 == true) {
throw new RuntimeException("Bad Initialization: ["
+ instanceTest1 + "," + instanceTest2 + "]");
}
byte[] multiple = new byte[keySize / 8];
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // from opsReference.seedToScalar(multiple);
MutablePoint referencePoint = opsReference.multiply(generator, multiple);
MutablePoint point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, -1);
AffinePoint refAffineGenerator = AffinePoint.fromECPoint(generator,
referencePoint.getField());
AffinePoint [MASK] = AffinePoint.fromECPoint(generator,
point.getField());
MutablePoint refProjGenerator = new ProjectivePoint.Mutable(
refAffineGenerator.getX(false).mutable(),
refAffineGenerator.getY(false).mutable(),
referencePoint.getField().get1().mutable());
MutablePoint projGenerator = new ProjectivePoint.Mutable(
[MASK] .getX(false).mutable(),
[MASK] .getY(false).mutable(),
point.getField().get1().mutable());
for (int i = 0; i < repeat; i++) {
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // opsReference.seedToScalar(multiple);
MutablePoint nextReferencePoint = opsReference
.multiply(referencePoint.asAffine(), multiple);
MutablePoint nextPoint = ops.multiply(point.asAffine().toECPoint(),
multiple);
check(nextReferencePoint, nextPoint, seed, i);
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, referencePoint);
ops.setSum(nextPoint, point);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, refProjGenerator);
ops.setSum(nextPoint, projGenerator);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextInt(100) < 10) { // 10% Reset point to generator, test
// generator multiplier
referencePoint = opsReference.multiply(generator, multiple);
point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, i);
} else {
referencePoint = nextReferencePoint;
point = nextPoint;
}
}
}
}
// make test TEST="test/jdk/com/sun/security/ec/ECOperationsFuzzTest.java" | montAffineGenerator |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
[MASK] .forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.change [MASK] (
[MASK] .forUidHash(uidHash),
[MASK] .forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
[MASK] .forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.change [MASK] (
[MASK] .forUid(uid),
[MASK] .forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
[MASK] .forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.change [MASK] (
[MASK] .forUid(uid),
[MASK] .forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
[MASK] .forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
[MASK] .forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.change [MASK] (
[MASK] .forUid(uid1),
[MASK] .forUid(uid2))
.change [MASK] (
[MASK] .forUid(uid2),
[MASK] .forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
[MASK] .forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| OperatorIdentifier |
package org.redisson.tomcat;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1243830648280853203L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
if (req.getPathInfo().equals("/write")) {
String[] params = req. [MASK] ().split("&");
String key = null;
String value = null;
for (String param : params) {
String[] paramLine = param.split("=");
String keyParam = paramLine[0];
String valueParam = paramLine[1];
if ("key".equals(keyParam)) {
key = valueParam;
}
if ("value".equals(keyParam)) {
value = valueParam;
}
}
session.setAttribute(key, value);
resp.getWriter().print("OK");
} else if (req.getPathInfo().equals("/read")) {
String[] params = req. [MASK] ().split("&");
String key = null;
for (String param : params) {
String[] line = param.split("=");
String keyParam = line[0];
if ("key".equals(keyParam)) {
key = line[1];
}
}
Object attr = session.getAttribute(key);
resp.getWriter().print(attr);
} else if (req.getPathInfo().equals("/remove")) {
String[] params = req. [MASK] ().split("&");
String key = null;
for (String param : params) {
String[] line = param.split("=");
String keyParam = line[0];
if ("key".equals(keyParam)) {
key = line[1];
}
}
session.removeAttribute(key);
resp.getWriter().print(String.valueOf(session.getAttribute(key)));
} else if (req.getPathInfo().equals("/invalidate")) {
session.invalidate();
resp.getWriter().print("OK");
} else if (req.getPathInfo().equals("/recreate")) {
session.invalidate();
session = req.getSession();
String[] params = req. [MASK] ().split("&");
String key = null;
String value = null;
for (String param : params) {
String[] paramLine = param.split("=");
String keyParam = paramLine[0];
String valueParam = paramLine[1];
if ("key".equals(keyParam)) {
key = valueParam;
}
if ("value".equals(keyParam)) {
value = valueParam;
}
}
session.setAttribute(key, value);
resp.getWriter().print("OK");
}
}
}
| getQueryString |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new [MASK] (aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new [MASK] (aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new [MASK] (aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new [MASK] (aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new [MASK] (aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new [MASK] (histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new [MASK] (aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new [MASK] (globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new [MASK] (aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new [MASK] (aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new [MASK] (aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new [MASK] (aggregationBuilder, fieldType).withQuery(query));
}
}
| AggTestConfig |
/*
* Copyright (c) 2024, Intel Corporation. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Random;
import java.math.BigInteger;
import java.lang.reflect.Field;
import java.security.spec.ECParameterSpec;
import sun.security.ec.ECOperations;
import sun.security.util.ECUtil;
import sun.security.util.NamedCurve;
import sun.security.util.CurveDB;
import sun.security.ec.point.*;
import java.security.spec.ECPoint;
import sun.security.util.KnownOIDs;
import sun.security.util.math.IntegerMontgomeryFieldModuloP;
import sun.security.util.math.intpoly.*;
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:-UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:+UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
// This test case is NOT entirely deterministic, it uses a random seed for
// pseudo-random number generator. If a failure occurs, hardcode the seed to
// make the test case deterministic
public class ECOperationsFuzzTest {
public static void main(String[] args) throws Exception {
// Note: it might be useful to increase this number during development
final int repeat = 10000;
test(repeat);
System.out.println("Fuzz Success");
}
private static void check(MutablePoint reference, MutablePoint testValue,
long seed, int iter) {
AffinePoint affineRef = reference.asAffine();
AffinePoint affine = testValue.asAffine();
if (!affineRef.equals(affine)) {
throw new RuntimeException(
"Found error with seed " + seed + "at iteration " + iter);
}
}
public static void test(int repeat) throws Exception {
Random rnd = new Random();
long seed = rnd.nextLong();
rnd.setSeed(seed);
int keySize = 256;
ECParameterSpec params = ECUtil.getECParameterSpec(keySize);
NamedCurve curve = CurveDB.lookup(KnownOIDs.secp256r1.value());
ECPoint generator = curve.getGenerator();
BigInteger b = curve.getCurve().getB();
if (params == null || generator == null) {
throw new RuntimeException(
"No EC parameters available for key size " + keySize + " bits");
}
ECOperations ops = ECOperations.forParameters(params).get();
ECOperations opsReference = new ECOperations(
IntegerPolynomialP256.ONE.getElement(b), P256OrderField.ONE);
boolean instanceTest1 = ops
.getField() instanceof IntegerMontgomeryFieldModuloP;
boolean instanceTest2 = opsReference
.getField() instanceof IntegerMontgomeryFieldModuloP;
if (instanceTest1 == false || instanceTest2 == true) {
throw new RuntimeException("Bad Initialization: ["
+ instanceTest1 + "," + instanceTest2 + "]");
}
byte[] multiple = new byte[keySize / 8];
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // from opsReference.seedToScalar(multiple);
MutablePoint [MASK] = opsReference.multiply(generator, multiple);
MutablePoint point = ops.multiply(generator, multiple);
check( [MASK] , point, seed, -1);
AffinePoint refAffineGenerator = AffinePoint.fromECPoint(generator,
[MASK] .getField());
AffinePoint montAffineGenerator = AffinePoint.fromECPoint(generator,
point.getField());
MutablePoint refProjGenerator = new ProjectivePoint.Mutable(
refAffineGenerator.getX(false).mutable(),
refAffineGenerator.getY(false).mutable(),
[MASK] .getField().get1().mutable());
MutablePoint projGenerator = new ProjectivePoint.Mutable(
montAffineGenerator.getX(false).mutable(),
montAffineGenerator.getY(false).mutable(),
point.getField().get1().mutable());
for (int i = 0; i < repeat; i++) {
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // opsReference.seedToScalar(multiple);
MutablePoint nextReferencePoint = opsReference
.multiply( [MASK] .asAffine(), multiple);
MutablePoint nextPoint = ops.multiply(point.asAffine().toECPoint(),
multiple);
check(nextReferencePoint, nextPoint, seed, i);
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, [MASK] );
ops.setSum(nextPoint, point);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, refProjGenerator);
ops.setSum(nextPoint, projGenerator);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextInt(100) < 10) { // 10% Reset point to generator, test
// generator multiplier
[MASK] = opsReference.multiply(generator, multiple);
point = ops.multiply(generator, multiple);
check( [MASK] , point, seed, i);
} else {
[MASK] = nextReferencePoint;
point = nextPoint;
}
}
}
}
// make test TEST="test/jdk/com/sun/security/ec/ECOperationsFuzzTest.java" | referencePoint |
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8080289 8189067
* @summary Move stores out of loops if possible
*
* @run main/othervm -XX:-UseOnStackReplacement -XX:-BackgroundCompilation
* -XX:CompileCommand=dontinline,compiler.loopopts.TestMoveStoresOutOfLoops::test*
* compiler.loopopts.TestMoveStoresOutOfLoops
*/
package compiler.loopopts;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.function.Function;
public class TestMoveStoresOutOfLoops {
private static long[] array = new long[10];
private static long[] array2 = new long[10];
private static boolean[] array3 = new boolean[1000];
private static int[] array4 = new int[1000];
private static byte[] byte_array = new byte[10];
// Array store should be moved out of the loop, value stored
// should be 999, the loop should be eliminated
static void test_after_1(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
}
}
// Array store can't be moved out of loop because of following
// non loop invariant array access
static void test_after_2(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
array2[i%10] = i;
}
}
// Array store can't be moved out of loop because of following
// use
static void test_after_3(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
if (array[0] == -1) {
break;
}
}
}
// Array store can't be moved out of loop because of preceding
// use
static void test_after_4(int idx) {
for (int i = 0; i < 1000; i++) {
if (array[0] == -2) {
break;
}
array[idx] = i;
}
}
// All array stores should be moved out of the loop, one after
// the other
static void test_after_5(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
array[idx+1] = i;
array[idx+2] = i;
array[idx+3] = i;
array[idx+4] = i;
array[idx+5] = i;
}
}
// Array store can be moved after the loop but needs to be
// cloned on both exit paths
static void test_after_6(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
if (array3[i]) {
return;
}
}
}
// Array store can be moved out of the inner loop
static void test_after_7(int idx) {
for (int i = 0; i < 1000; i++) {
for (int j = 0; j <= 42; j++) {
array4[i] = j;
}
}
}
// Optimize out redundant stores
static void test_stores_1(int ignored) {
array[0] = 0;
array[1] = 1;
array[2] = 2;
array[0] = 0;
array[1] = 1;
array[2] = 2;
}
static void test_stores_2(int idx) {
array[idx+0] = 0;
array[idx+1] = 1;
array[idx+2] = 2;
array[idx+0] = 0;
array[idx+1] = 1;
array[idx+2] = 2;
}
static void test_stores_3(int idx) {
byte_array[idx+0] = 0;
byte_array[idx+1] = 1;
byte_array[idx+2] = 2;
byte_array[idx+0] = 0;
byte_array[idx+1] = 1;
byte_array[idx+2] = 2;
}
// Array store can be moved out of the loop before the loop header
static void test_before_1(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = 999;
}
}
// Array store can't be moved out of the loop before the loop
// header because there's more than one store on this slice
static void test_before_2(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = 999;
array[i%2] = 0;
}
}
// Array store can't be moved out of the loop before the loop
// header because of use before store
static int test_before_3(int idx) {
int res = 0;
for (int i = 0; i < 1000; i++) {
res += array[i%10];
array[idx] = 999;
}
return res;
}
// Array store can't be moved out of the loop before the loop
// header because of possible early exit
static void test_before_4(int idx) {
for (int i = 0; i < 1000; i++) {
if (idx / (i+1) > 0) {
return;
}
array[idx] = 999;
}
}
// Array store can't be moved out of the loop before the loop
// header because it doesn't postdominate the loop head
static void test_before_5(int idx) {
for (int i = 0; i < 1000; i++) {
if (i % 2 == 0) {
array[idx] = 999;
}
}
}
// Array store can be moved out of the loop before the loop header
static int test_before_6(int idx) {
int res = 0;
for (int i = 0; i < 1000; i++) {
if (i%2 == 1) {
res *= 2;
} else {
res++;
}
array[idx] = 999;
}
return res;
}
final HashMap< [MASK] ,Method> tests = new HashMap<>();
{
for (Method m : this.getClass().getDeclaredMethods()) {
if (m.getName().matches("test_(before|after|stores)_[0-9]+")) {
assert(Modifier.isStatic(m.getModifiers())) : m;
tests.put(m.getName(), m);
}
}
}
boolean success = true;
void doTest( [MASK] name, Runnable init, Function< [MASK] , Boolean> check) throws Exception {
Method m = tests.get(name);
for (int i = 0; i < 20000; i++) {
init.run();
m.invoke(null, 0);
success = success && check.apply(name);
if (!success) {
break;
}
}
}
static void array_init() {
array[0] = -1;
}
static boolean array_check( [MASK] name) {
boolean success = true;
if (array[0] != 999) {
success = false;
System.out.println(name + " failed: array[0] = " + array[0]);
}
return success;
}
static void array_init2() {
for (int i = 0; i < 6; i++) {
array[i] = -1;
}
}
static boolean array_check2( [MASK] name) {
boolean success = true;
for (int i = 0; i < 6; i++) {
if (array[i] != 999) {
success = false;
System.out.println(name + " failed: array[" + i + "] = " + array[i]);
}
}
return success;
}
static void array_init3() {
for (int i = 0; i < 3; i++) {
array[i] = -1;
}
}
static boolean array_check3( [MASK] name) {
boolean success = true;
for (int i = 0; i < 3; i++) {
if (array[i] != i) {
success = false;
System.out.println(name + " failed: array[" + i + "] = " + array[i]);
}
}
return success;
}
static void array_init4() {
for (int i = 0; i < 3; i++) {
byte_array[i] = -1;
}
}
static boolean array_check4( [MASK] name) {
boolean success = true;
for (int i = 0; i < 3; i++) {
if (byte_array[i] != i) {
success = false;
System.out.println(name + " failed: byte_array[" + i + "] = " + byte_array[i]);
}
}
return success;
}
static boolean array_check5( [MASK] name) {
boolean success = true;
for (int i = 0; i < 1000; i++) {
if (array4[i] != 42) {
success = false;
System.out.println(name + " failed: array[" + i + "] = " + array4[i]);
}
}
return success;
}
static public void main( [MASK] [] args) throws Exception {
TestMoveStoresOutOfLoops test = new TestMoveStoresOutOfLoops();
test.doTest("test_after_1", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_2", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_3", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_4", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_5", TestMoveStoresOutOfLoops::array_init2, TestMoveStoresOutOfLoops::array_check2);
test.doTest("test_after_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
array3[999] = true;
test.doTest("test_after_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_after_7", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check5);
test.doTest("test_stores_1", TestMoveStoresOutOfLoops::array_init3, TestMoveStoresOutOfLoops::array_check3);
test.doTest("test_stores_2", TestMoveStoresOutOfLoops::array_init3, TestMoveStoresOutOfLoops::array_check3);
test.doTest("test_stores_3", TestMoveStoresOutOfLoops::array_init4, TestMoveStoresOutOfLoops::array_check4);
test.doTest("test_before_1", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_2", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_3", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_4", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_5", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
test.doTest("test_before_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops::array_check);
if (!test.success) {
throw new RuntimeException("Some tests failed");
}
}
}
| String |
/*
* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
package build.tools.projectcreator;
class [MASK] {
String[] args;
int i;
[MASK] (String[] args) {
this.args = args;
this.i = 0;
}
String get() { return args[i]; }
boolean hasMore() { return args != null && i < args.length; }
boolean next() { return ++i < args.length; }
}
abstract class ArgHandler {
public abstract void handle( [MASK] it);
}
class ArgRule {
String arg;
ArgHandler handler;
ArgRule(String arg, ArgHandler handler) {
this.arg = arg;
this.handler = handler;
}
boolean process( [MASK] it) {
if (match(it.get(), arg)) {
handler.handle(it);
return true;
}
return false;
}
boolean match(String rule_pattern, String arg) {
return arg.equals(rule_pattern);
}
}
class ArgsParser {
ArgsParser(String[] args,
ArgRule[] rules,
ArgHandler defaulter) {
[MASK] ai = new [MASK] (args);
while (ai.hasMore()) {
boolean processed = false;
for (int i=0; i<rules.length; i++) {
processed |= rules[i].process(ai);
if (processed) {
break;
}
}
if (!processed) {
if (defaulter != null) {
defaulter.handle(ai);
} else {
System.err.println("ERROR: unparsed \""+ai.get()+"\"");
ai.next();
}
}
}
}
}
| ArgIterator |
/*
* Copyright (c) 2024, Intel Corporation. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Random;
import java.math.BigInteger;
import java.lang.reflect.Field;
import java.security.spec.ECParameterSpec;
import sun.security.ec.ECOperations;
import sun.security.util.ECUtil;
import sun.security.util.NamedCurve;
import sun.security.util.CurveDB;
import sun.security.ec.point.*;
import java.security.spec.ECPoint;
import sun.security.util.KnownOIDs;
import sun.security.util.math.IntegerMontgomeryFieldModuloP;
import sun.security.util.math.intpoly.*;
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:-UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:+UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
// This test case is NOT entirely deterministic, it uses a random seed for
// pseudo-random number [MASK] . If a failure occurs, hardcode the seed to
// make the test case deterministic
public class ECOperationsFuzzTest {
public static void main(String[] args) throws Exception {
// Note: it might be useful to increase this number during development
final int repeat = 10000;
test(repeat);
System.out.println("Fuzz Success");
}
private static void check(MutablePoint reference, MutablePoint testValue,
long seed, int iter) {
AffinePoint affineRef = reference.asAffine();
AffinePoint affine = testValue.asAffine();
if (!affineRef.equals(affine)) {
throw new RuntimeException(
"Found error with seed " + seed + "at iteration " + iter);
}
}
public static void test(int repeat) throws Exception {
Random rnd = new Random();
long seed = rnd.nextLong();
rnd.setSeed(seed);
int keySize = 256;
ECParameterSpec params = ECUtil.getECParameterSpec(keySize);
NamedCurve curve = CurveDB.lookup(KnownOIDs.secp256r1.value());
ECPoint [MASK] = curve.getGenerator();
BigInteger b = curve.getCurve().getB();
if (params == null || [MASK] == null) {
throw new RuntimeException(
"No EC parameters available for key size " + keySize + " bits");
}
ECOperations ops = ECOperations.forParameters(params).get();
ECOperations opsReference = new ECOperations(
IntegerPolynomialP256.ONE.getElement(b), P256OrderField.ONE);
boolean instanceTest1 = ops
.getField() instanceof IntegerMontgomeryFieldModuloP;
boolean instanceTest2 = opsReference
.getField() instanceof IntegerMontgomeryFieldModuloP;
if (instanceTest1 == false || instanceTest2 == true) {
throw new RuntimeException("Bad Initialization: ["
+ instanceTest1 + "," + instanceTest2 + "]");
}
byte[] multiple = new byte[keySize / 8];
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // from opsReference.seedToScalar(multiple);
MutablePoint referencePoint = opsReference.multiply( [MASK] , multiple);
MutablePoint point = ops.multiply( [MASK] , multiple);
check(referencePoint, point, seed, -1);
AffinePoint refAffineGenerator = AffinePoint.fromECPoint( [MASK] ,
referencePoint.getField());
AffinePoint montAffineGenerator = AffinePoint.fromECPoint( [MASK] ,
point.getField());
MutablePoint refProjGenerator = new ProjectivePoint.Mutable(
refAffineGenerator.getX(false).mutable(),
refAffineGenerator.getY(false).mutable(),
referencePoint.getField().get1().mutable());
MutablePoint projGenerator = new ProjectivePoint.Mutable(
montAffineGenerator.getX(false).mutable(),
montAffineGenerator.getY(false).mutable(),
point.getField().get1().mutable());
for (int i = 0; i < repeat; i++) {
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // opsReference.seedToScalar(multiple);
MutablePoint nextReferencePoint = opsReference
.multiply(referencePoint.asAffine(), multiple);
MutablePoint nextPoint = ops.multiply(point.asAffine().toECPoint(),
multiple);
check(nextReferencePoint, nextPoint, seed, i);
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, referencePoint);
ops.setSum(nextPoint, point);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, refProjGenerator);
ops.setSum(nextPoint, projGenerator);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextInt(100) < 10) { // 10% Reset point to [MASK] , test
// [MASK] multiplier
referencePoint = opsReference.multiply( [MASK] , multiple);
point = ops.multiply( [MASK] , multiple);
check(referencePoint, point, seed, i);
} else {
referencePoint = nextReferencePoint;
point = nextPoint;
}
}
}
}
// make test TEST="test/jdk/com/sun/security/ec/ECOperationsFuzzTest.java" | generator |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String [MASK] =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write( [MASK] );
env.execute("Bootstrap");
return [MASK] ;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String [MASK] , Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, [MASK] );
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String [MASK] , ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata( [MASK] );
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath( [MASK] , false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| savepointPath |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections. [MASK] ());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections. [MASK] ()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections. [MASK] ()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections. [MASK] ()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| emptyMap |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Set;
import javax. [MASK] .processing.AbstractProcessor;
import javax. [MASK] .processing.RoundEnvironment;
import javax. [MASK] .processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
@SupportedAnnotationTypes("*")
public class SimpleProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> [MASK] s, RoundEnvironment roundEnv) {
return false;
}
} | annotation |
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.jdbc.core.metadata;
import java.sql.DatabaseMetaData;
import org.jspecify.annotations. [MASK] ;
/**
* Holder of meta-data for a specific parameter that is used for call processing.
*
* @author Thomas Risberg
* @author Juergen Hoeller
* @since 2.5
* @see GenericCallMetaDataProvider
*/
public class CallParameterMetaData {
private final boolean function;
private final @ [MASK] String parameterName;
private final int parameterType;
private final int sqlType;
private final @ [MASK] String typeName;
private final boolean nullable;
/**
* Constructor taking all the properties including the function marker.
* @since 5.2.9
*/
public CallParameterMetaData(boolean function, @ [MASK] String columnName, int columnType,
int sqlType, @ [MASK] String typeName, boolean nullable) {
this.function = function;
this.parameterName = columnName;
this.parameterType = columnType;
this.sqlType = sqlType;
this.typeName = typeName;
this.nullable = nullable;
}
/**
* Return whether this parameter is declared in a function.
* @since 5.2.9
*/
public boolean isFunction() {
return this.function;
}
/**
* Return the parameter name.
*/
public @ [MASK] String getParameterName() {
return this.parameterName;
}
/**
* Return the parameter type.
*/
public int getParameterType() {
return this.parameterType;
}
/**
* Determine whether the declared parameter qualifies as a 'return' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnReturn} or
* {@link DatabaseMetaData#procedureColumnResult}, or in case of a function,
* {@link DatabaseMetaData#functionReturn}.
* @since 4.3.15
*/
public boolean isReturnParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionReturn :
(this.parameterType == DatabaseMetaData.procedureColumnReturn ||
this.parameterType == DatabaseMetaData.procedureColumnResult));
}
/**
* Determine whether the declared parameter qualifies as an 'out' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnOut},
* or in case of a function, {@link DatabaseMetaData#functionColumnOut}.
* @since 5.3.31
*/
public boolean isOutParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionColumnOut :
this.parameterType == DatabaseMetaData.procedureColumnOut);
}
/**
* Determine whether the declared parameter qualifies as an 'in-out' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnInOut},
* or in case of a function, {@link DatabaseMetaData#functionColumnInOut}.
* @since 5.3.31
*/
public boolean isInOutParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionColumnInOut :
this.parameterType == DatabaseMetaData.procedureColumnInOut);
}
/**
* Return the parameter SQL type.
*/
public int getSqlType() {
return this.sqlType;
}
/**
* Return the parameter type name.
*/
public @ [MASK] String getTypeName() {
return this.typeName;
}
/**
* Return whether the parameter is nullable.
*/
public boolean is [MASK] () {
return this.nullable;
}
}
| Nullable |
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8080289 8189067
* @summary Move stores out of loops if possible
*
* @run main/othervm -XX:-UseOnStackReplacement -XX:-BackgroundCompilation
* -XX:CompileCommand=dontinline,compiler.loopopts.TestMoveStoresOutOfLoops::test*
* compiler.loopopts.TestMoveStoresOutOfLoops
*/
package compiler.loopopts;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.function.Function;
public class TestMoveStoresOutOfLoops {
private static long[] array = new long[10];
private static long[] array2 = new long[10];
private static boolean[] array3 = new boolean[1000];
private static int[] array4 = new int[1000];
private static byte[] byte_array = new byte[10];
// Array store should be moved out of the loop, value stored
// should be 999, the loop should be eliminated
static void test_after_1(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
}
}
// Array store can't be moved out of loop because of following
// non loop invariant array access
static void test_after_2(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
array2[i%10] = i;
}
}
// Array store can't be moved out of loop because of following
// use
static void test_after_3(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
if (array[0] == -1) {
break;
}
}
}
// Array store can't be moved out of loop because of preceding
// use
static void test_after_4(int idx) {
for (int i = 0; i < 1000; i++) {
if (array[0] == -2) {
break;
}
array[idx] = i;
}
}
// All array stores should be moved out of the loop, one after
// the other
static void test_after_5(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
array[idx+1] = i;
array[idx+2] = i;
array[idx+3] = i;
array[idx+4] = i;
array[idx+5] = i;
}
}
// Array store can be moved after the loop but needs to be
// cloned on both exit paths
static void test_after_6(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = i;
if (array3[i]) {
return;
}
}
}
// Array store can be moved out of the inner loop
static void test_after_7(int idx) {
for (int i = 0; i < 1000; i++) {
for (int j = 0; j <= 42; j++) {
array4[i] = j;
}
}
}
// Optimize out redundant stores
static void test_stores_1(int ignored) {
array[0] = 0;
array[1] = 1;
array[2] = 2;
array[0] = 0;
array[1] = 1;
array[2] = 2;
}
static void test_stores_2(int idx) {
array[idx+0] = 0;
array[idx+1] = 1;
array[idx+2] = 2;
array[idx+0] = 0;
array[idx+1] = 1;
array[idx+2] = 2;
}
static void test_stores_3(int idx) {
byte_array[idx+0] = 0;
byte_array[idx+1] = 1;
byte_array[idx+2] = 2;
byte_array[idx+0] = 0;
byte_array[idx+1] = 1;
byte_array[idx+2] = 2;
}
// Array store can be moved out of the loop before the loop header
static void test_before_1(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = 999;
}
}
// Array store can't be moved out of the loop before the loop
// header because there's more than one store on this slice
static void test_before_2(int idx) {
for (int i = 0; i < 1000; i++) {
array[idx] = 999;
array[i%2] = 0;
}
}
// Array store can't be moved out of the loop before the loop
// header because of use before store
static int test_before_3(int idx) {
int res = 0;
for (int i = 0; i < 1000; i++) {
res += array[i%10];
array[idx] = 999;
}
return res;
}
// Array store can't be moved out of the loop before the loop
// header because of possible early exit
static void test_before_4(int idx) {
for (int i = 0; i < 1000; i++) {
if (idx / (i+1) > 0) {
return;
}
array[idx] = 999;
}
}
// Array store can't be moved out of the loop before the loop
// header because it doesn't postdominate the loop head
static void test_before_5(int idx) {
for (int i = 0; i < 1000; i++) {
if (i % 2 == 0) {
array[idx] = 999;
}
}
}
// Array store can be moved out of the loop before the loop header
static int test_before_6(int idx) {
int res = 0;
for (int i = 0; i < 1000; i++) {
if (i%2 == 1) {
res *= 2;
} else {
res++;
}
array[idx] = 999;
}
return res;
}
final HashMap<String,Method> tests = new HashMap<>();
{
for (Method m : this.getClass().getDeclaredMethods()) {
if (m.getName().matches("test_(before|after|stores)_[0-9]+")) {
assert(Modifier.isStatic(m.getModifiers())) : m;
tests.put(m.getName(), m);
}
}
}
boolean success = true;
void doTest(String name, Runnable init, Function<String, Boolean> check) throws Exception {
Method m = tests.get(name);
for (int i = 0; i < 20000; i++) {
init.run();
m.invoke(null, 0);
success = success && check.apply(name);
if (!success) {
break;
}
}
}
static void array_init() {
array[0] = -1;
}
static boolean [MASK] (String name) {
boolean success = true;
if (array[0] != 999) {
success = false;
System.out.println(name + " failed: array[0] = " + array[0]);
}
return success;
}
static void array_init2() {
for (int i = 0; i < 6; i++) {
array[i] = -1;
}
}
static boolean [MASK] 2(String name) {
boolean success = true;
for (int i = 0; i < 6; i++) {
if (array[i] != 999) {
success = false;
System.out.println(name + " failed: array[" + i + "] = " + array[i]);
}
}
return success;
}
static void array_init3() {
for (int i = 0; i < 3; i++) {
array[i] = -1;
}
}
static boolean [MASK] 3(String name) {
boolean success = true;
for (int i = 0; i < 3; i++) {
if (array[i] != i) {
success = false;
System.out.println(name + " failed: array[" + i + "] = " + array[i]);
}
}
return success;
}
static void array_init4() {
for (int i = 0; i < 3; i++) {
byte_array[i] = -1;
}
}
static boolean [MASK] 4(String name) {
boolean success = true;
for (int i = 0; i < 3; i++) {
if (byte_array[i] != i) {
success = false;
System.out.println(name + " failed: byte_array[" + i + "] = " + byte_array[i]);
}
}
return success;
}
static boolean [MASK] 5(String name) {
boolean success = true;
for (int i = 0; i < 1000; i++) {
if (array4[i] != 42) {
success = false;
System.out.println(name + " failed: array[" + i + "] = " + array4[i]);
}
}
return success;
}
static public void main(String[] args) throws Exception {
TestMoveStoresOutOfLoops test = new TestMoveStoresOutOfLoops();
test.doTest("test_after_1", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops:: [MASK] );
test.doTest("test_after_2", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops:: [MASK] );
test.doTest("test_after_3", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops:: [MASK] );
test.doTest("test_after_4", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops:: [MASK] );
test.doTest("test_after_5", TestMoveStoresOutOfLoops::array_init2, TestMoveStoresOutOfLoops:: [MASK] 2);
test.doTest("test_after_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops:: [MASK] );
array3[999] = true;
test.doTest("test_after_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops:: [MASK] );
test.doTest("test_after_7", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops:: [MASK] 5);
test.doTest("test_stores_1", TestMoveStoresOutOfLoops::array_init3, TestMoveStoresOutOfLoops:: [MASK] 3);
test.doTest("test_stores_2", TestMoveStoresOutOfLoops::array_init3, TestMoveStoresOutOfLoops:: [MASK] 3);
test.doTest("test_stores_3", TestMoveStoresOutOfLoops::array_init4, TestMoveStoresOutOfLoops:: [MASK] 4);
test.doTest("test_before_1", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops:: [MASK] );
test.doTest("test_before_2", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops:: [MASK] );
test.doTest("test_before_3", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops:: [MASK] );
test.doTest("test_before_4", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops:: [MASK] );
test.doTest("test_before_5", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops:: [MASK] );
test.doTest("test_before_6", TestMoveStoresOutOfLoops::array_init, TestMoveStoresOutOfLoops:: [MASK] );
if (!test.success) {
throw new RuntimeException("Some tests failed");
}
}
}
| array_check |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType. [MASK] );
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType. [MASK] );
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType. [MASK] );
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType. [MASK] );
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType. [MASK] );
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType. [MASK] );
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType. [MASK] );
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType. [MASK] );
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType. [MASK] );
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType. [MASK] );
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType. [MASK] );
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| INTEGER |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.Mock [MASK] Engine;
import org.elasticsearch.script. [MASK] ;
import org.elasticsearch.script. [MASK] Engine;
import org.elasticsearch.script. [MASK] Module;
import org.elasticsearch.script. [MASK] Service;
import org.elasticsearch.script. [MASK] Type;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** [MASK] to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected [MASK] Service getMock [MASK] Service() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
Mock [MASK] Engine scriptEngine = new Mock [MASK] Engine(Mock [MASK] Engine.NAME, scripts, Collections.emptyMap());
Map<String, [MASK] Engine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new [MASK] Service(Settings.EMPTY, engines, [MASK] Module.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValue [MASK] () throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new [MASK] ( [MASK] Type.INLINE, Mock [MASK] Engine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValue [MASK] Unmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new [MASK] ( [MASK] Type.INLINE, Mock [MASK] Engine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValue [MASK] UnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new [MASK] ( [MASK] Type.INLINE, Mock [MASK] Engine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| Script |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
[MASK] (Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
[MASK] (Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
[MASK] (Double.NaN, boxplot.getQ1(), 0);
[MASK] (Double.NaN, boxplot.getQ2(), 0);
[MASK] (Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
[MASK] (2, boxplot.getMin(), 0);
[MASK] (10, boxplot.getMax(), 0);
[MASK] (2.25, boxplot.getQ1(), 0);
[MASK] (3.5, boxplot.getQ2(), 0);
[MASK] (4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
[MASK] (2, boxplot.getMin(), 0);
[MASK] (10, boxplot.getMax(), 0);
[MASK] (2.25, boxplot.getQ1(), 0);
[MASK] (3.5, boxplot.getQ2(), 0);
[MASK] (4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
[MASK] (2, boxplot.getMin(), 0);
[MASK] (10, boxplot.getMax(), 0);
[MASK] (2.25, boxplot.getQ1(), 0);
[MASK] (3.5, boxplot.getQ2(), 0);
[MASK] (4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
[MASK] (2, boxplot.getMin(), 0);
[MASK] (10, boxplot.getMax(), 0);
[MASK] (2.25, boxplot.getQ1(), 0);
[MASK] (3.5, boxplot.getQ2(), 0);
[MASK] (4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
[MASK] (0, boxplot.getMin(), 0);
[MASK] (10, boxplot.getMax(), 0);
[MASK] (10, boxplot.getQ1(), 0);
[MASK] (10, boxplot.getQ2(), 0);
[MASK] (10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
[MASK] (0, boxplot.getMin(), 0);
[MASK] (0, boxplot.getMax(), 0);
[MASK] (0, boxplot.getQ1(), 0);
[MASK] (0, boxplot.getQ2(), 0);
[MASK] (0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
[MASK] (e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
[MASK] (1, boxplot.getMin(), 0);
[MASK] (3, boxplot.getMax(), 0);
[MASK] (1.5, boxplot.getQ1(), 0);
[MASK] (2, boxplot.getQ2(), 0);
[MASK] (2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
[MASK] (Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
[MASK] (Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
[MASK] (Double.NaN, boxplot.getQ1(), 0);
[MASK] (Double.NaN, boxplot.getQ2(), 0);
[MASK] (Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
[MASK] (21, boxplot.getMin(), 0);
[MASK] (23, boxplot.getMax(), 0);
[MASK] (21.5, boxplot.getQ1(), 0);
[MASK] (22, boxplot.getQ2(), 0);
[MASK] (22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
[MASK] (1, boxplot.getMin(), 0);
[MASK] (5, boxplot.getMax(), 0);
[MASK] (2, boxplot.getQ1(), 0);
[MASK] (3, boxplot.getQ2(), 0);
[MASK] (4, boxplot.getQ3(), 0);
[MASK] ("0001.0", boxplot.getMinAsString());
[MASK] ("0005.0", boxplot.getMaxAsString());
[MASK] ("0002.0", boxplot.getQ1AsString());
[MASK] ("0003.0", boxplot.getQ2AsString());
[MASK] ("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
[MASK] (5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
[MASK] (2, boxplot.getMin(), 0);
[MASK] (8, boxplot.getMax(), 0);
[MASK] (3.5, boxplot.getQ1(), 0);
[MASK] (5, boxplot.getQ2(), 0);
[MASK] (6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
[MASK] (Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
[MASK] (Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
[MASK] (Double.NaN, boxplot.getQ1(), 0);
[MASK] (Double.NaN, boxplot.getQ2(), 0);
[MASK] (Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
[MASK] (1.0, boxplot.getMin(), 0);
[MASK] (1.0, boxplot.getMax(), 0);
[MASK] (1.0, boxplot.getQ1(), 0);
[MASK] (1.0, boxplot.getQ2(), 0);
[MASK] (1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| assertEquals |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document. [MASK] ;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new [MASK] ("wrong_number", 7)));
iw.addDocument(singleton(new [MASK] ("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new [MASK] ("number", 2)));
iw.addDocument(singleton(new [MASK] ("number", 2)));
iw.addDocument(singleton(new [MASK] ("number", 3)));
iw.addDocument(singleton(new [MASK] ("number", 4)));
iw.addDocument(singleton(new [MASK] ("number", 5)));
iw.addDocument(singleton(new [MASK] ("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new [MASK] ("number", 2)));
iw.addDocument(singleton(new [MASK] ("number", 2)));
iw.addDocument(singleton(new [MASK] ("number2", 2)));
iw.addDocument(singleton(new [MASK] ("number", 3)));
iw.addDocument(singleton(new [MASK] ("number", 4)));
iw.addDocument(singleton(new [MASK] ("number", 5)));
iw.addDocument(singleton(new [MASK] ("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| SortedNumericDocValuesField |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Set;
import [MASK] .annotation.processing.AbstractProcessor;
import [MASK] .annotation.processing.RoundEnvironment;
import [MASK] .annotation.processing.SupportedAnnotationTypes;
import [MASK] .lang.model.SourceVersion;
import [MASK] .lang.model.element.TypeElement;
@SupportedAnnotationTypes("*")
public class SimpleProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
return false;
}
} | javax |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os. [MASK] ().isPresent()
&& os. [MASK] ()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next(). [MASK] ()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| getOperatorUid |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document. [MASK] ;
import org.apache.lucene.document.Sorted [MASK] ;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new Sorted [MASK] ("wrong_number", 7)));
iw.addDocument(singleton(new Sorted [MASK] ("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new Sorted [MASK] ("number", 2)));
iw.addDocument(singleton(new Sorted [MASK] ("number", 2)));
iw.addDocument(singleton(new Sorted [MASK] ("number", 3)));
iw.addDocument(singleton(new Sorted [MASK] ("number", 4)));
iw.addDocument(singleton(new Sorted [MASK] ("number", 5)));
iw.addDocument(singleton(new Sorted [MASK] ("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new [MASK] ("number", 2)));
iw.addDocument(singleton(new [MASK] ("number", 2)));
iw.addDocument(singleton(new [MASK] ("number", 3)));
iw.addDocument(singleton(new [MASK] ("number", 4)));
iw.addDocument(singleton(new [MASK] ("number", 5)));
iw.addDocument(singleton(new [MASK] ("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new Sorted [MASK] ("number", 2)));
iw.addDocument(singleton(new Sorted [MASK] ("number", 2)));
iw.addDocument(singleton(new Sorted [MASK] ("number2", 2)));
iw.addDocument(singleton(new Sorted [MASK] ("number", 3)));
iw.addDocument(singleton(new Sorted [MASK] ("number", 4)));
iw.addDocument(singleton(new Sorted [MASK] ("number", 5)));
iw.addDocument(singleton(new Sorted [MASK] ("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new [MASK] ("number", 2)));
iw.addDocument(singleton(new [MASK] ("number", 2)));
iw.addDocument(singleton(new [MASK] ("number2", 2)));
iw.addDocument(singleton(new [MASK] ("number", 3)));
iw.addDocument(singleton(new [MASK] ("number", 4)));
iw.addDocument(singleton(new [MASK] ("number", 5)));
iw.addDocument(singleton(new [MASK] ("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new [MASK] ("other", 2)));
iw.addDocument(singleton(new [MASK] ("other", 2)));
iw.addDocument(singleton(new [MASK] ("other", 3)));
iw.addDocument(singleton(new [MASK] ("other", 4)));
iw.addDocument(singleton(new [MASK] ("other", 5)));
iw.addDocument(singleton(new [MASK] ("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new [MASK] ("number", 7)));
iw.addDocument(singleton(new [MASK] ("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new [MASK] ("number", 2)));
iw.addDocument(singleton(new [MASK] ("number", 2)));
iw.addDocument(singleton(new [MASK] ("number", 3)));
iw.addDocument(singleton(new [MASK] ("number", 4)));
iw.addDocument(singleton(new [MASK] ("number", 5)));
iw.addDocument(singleton(new [MASK] ("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new [MASK] ("number", 2)));
iw.addDocument(singleton(new [MASK] ("number", 2)));
iw.addDocument(singleton(new [MASK] ("number", 3)));
iw.addDocument(singleton(new [MASK] ("number", 4)));
iw.addDocument(singleton(new [MASK] ("number", 5)));
iw.addDocument(singleton(new [MASK] ("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new [MASK] ("number", 1)));
iw.addDocument(singleton(new [MASK] ("number", 3)));
iw.addDocument(singleton(new [MASK] ("number", 21)));
iw.addDocument(singleton(new [MASK] ("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new [MASK] ("number", 1)));
iw.addDocument(singleton(new [MASK] ("number", 2)));
iw.addDocument(singleton(new [MASK] ("number", 3)));
iw.addDocument(singleton(new [MASK] ("number", 4)));
iw.addDocument(singleton(new [MASK] ("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new [MASK] ("number", 1)));
iw.addDocument(singleton(new [MASK] ("number", 2)));
iw.addDocument(singleton(new [MASK] ("number", 3)));
iw.addDocument(singleton(new [MASK] ("number", 4)));
iw.addDocument(singleton(new [MASK] ("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new [MASK] ("number", 7)));
iw.addDocument(singleton(new [MASK] ("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new [MASK] ("number", 7)));
iw.addDocument(singleton(new [MASK] ("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new [MASK] ("number", 7)));
iw.addDocument(singleton(new [MASK] ("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| NumericDocValuesField |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper. [MASK] .INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper. [MASK] .INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper. [MASK] .INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper. [MASK] .INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper. [MASK] .INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper. [MASK] .INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper. [MASK] .INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper. [MASK] .INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper. [MASK] .INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper. [MASK] .INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper. [MASK] .INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| NumberType |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID(). [MASK] ();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID(). [MASK] ();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID(). [MASK] ()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID(). [MASK] ()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
. [MASK] ()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| toHexString |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType [MASK] , String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType [MASK] = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, [MASK] ));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType [MASK] = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, [MASK] ));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType [MASK] = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, [MASK] )
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType [MASK] = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, [MASK] )
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType [MASK] = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, [MASK] )
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType [MASK] = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, [MASK] ));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType [MASK] = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, [MASK] ));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType [MASK] = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, [MASK] ));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType [MASK] = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, [MASK] ));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType [MASK] = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, [MASK] ));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType [MASK] = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, [MASK] ));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType [MASK] = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, [MASK] ).withQuery(query));
}
}
| fieldType |
/*
* 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.flink.state.api;
import org.apache.flink.api. [MASK] .RuntimeExecutionMode;
import org.apache.flink.api. [MASK] .functions.OpenContext;
import org.apache.flink.api. [MASK] .functions.RichMapFunction;
import org.apache.flink.api. [MASK] .state.ValueState;
import org.apache.flink.api. [MASK] .state.ValueStateDescriptor;
import org.apache.flink.api. [MASK] .typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| common |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch. [MASK] .analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch. [MASK] .analytics.AnalyticsPlugin;
import org.elasticsearch. [MASK] .analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| xpack |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics. [MASK] ;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, [MASK] -> {
assertEquals(Double.POSITIVE_INFINITY, [MASK] .getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, [MASK] .getMax(), 0);
assertEquals(Double.NaN, [MASK] .getQ1(), 0);
assertEquals(Double.NaN, [MASK] .getQ2(), 0);
assertEquals(Double.NaN, [MASK] .getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, [MASK] -> {
assertEquals(2, [MASK] .getMin(), 0);
assertEquals(10, [MASK] .getMax(), 0);
assertEquals(2.25, [MASK] .getQ1(), 0);
assertEquals(3.5, [MASK] .getQ2(), 0);
assertEquals(4.75, [MASK] .getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, [MASK] -> {
assertEquals(2, [MASK] .getMin(), 0);
assertEquals(10, [MASK] .getMax(), 0);
assertEquals(2.25, [MASK] .getQ1(), 0);
assertEquals(3.5, [MASK] .getQ2(), 0);
assertEquals(4.75, [MASK] .getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, [MASK] -> {
assertEquals(2, [MASK] .getMin(), 0);
assertEquals(10, [MASK] .getMax(), 0);
assertEquals(2.25, [MASK] .getQ1(), 0);
assertEquals(3.5, [MASK] .getQ2(), 0);
assertEquals(4.75, [MASK] .getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, [MASK] -> {
assertEquals(2, [MASK] .getMin(), 0);
assertEquals(10, [MASK] .getMax(), 0);
assertEquals(2.25, [MASK] .getQ1(), 0);
assertEquals(3.5, [MASK] .getQ2(), 0);
assertEquals(4.75, [MASK] .getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder(" [MASK] ").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) [MASK] -> {
assertEquals(0, [MASK] .getMin(), 0);
assertEquals(10, [MASK] .getMax(), 0);
assertEquals(10, [MASK] .getQ1(), 0);
assertEquals(10, [MASK] .getQ2(), 0);
assertEquals(10, [MASK] .getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder(" [MASK] ").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) [MASK] -> {
assertEquals(0, [MASK] .getMin(), 0);
assertEquals(0, [MASK] .getMax(), 0);
assertEquals(0, [MASK] .getQ1(), 0);
assertEquals(0, [MASK] .getQ2(), 0);
assertEquals(0, [MASK] .getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder(" [MASK] ").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) [MASK] -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [ [MASK] ]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder(" [MASK] ").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) [MASK] -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder(" [MASK] ").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) [MASK] -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder(" [MASK] ").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get(" [MASK] "));
InternalBoxplot [MASK] = histo.getBuckets().get(0).getAggregations().get(" [MASK] ");
assertEquals(1, [MASK] .getMin(), 0);
assertEquals(3, [MASK] .getMax(), 0);
assertEquals(1.5, [MASK] .getQ1(), 0);
assertEquals(2, [MASK] .getQ2(), 0);
assertEquals(2.5, [MASK] .getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get(" [MASK] "));
[MASK] = histo.getBuckets().get(1).getAggregations().get(" [MASK] ");
assertEquals(Double.POSITIVE_INFINITY, [MASK] .getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, [MASK] .getMax(), 0);
assertEquals(Double.NaN, [MASK] .getQ1(), 0);
assertEquals(Double.NaN, [MASK] .getQ2(), 0);
assertEquals(Double.NaN, [MASK] .getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get(" [MASK] "));
[MASK] = histo.getBuckets().get(2).getAggregations().get(" [MASK] ");
assertEquals(21, [MASK] .getMin(), 0);
assertEquals(23, [MASK] .getMax(), 0);
assertEquals(21.5, [MASK] .getQ1(), 0);
assertEquals(22, [MASK] .getQ2(), 0);
assertEquals(22.5, [MASK] .getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder(" [MASK] ").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) [MASK] -> {
assertEquals(1, [MASK] .getMin(), 0);
assertEquals(5, [MASK] .getMax(), 0);
assertEquals(2, [MASK] .getQ1(), 0);
assertEquals(3, [MASK] .getQ2(), 0);
assertEquals(4, [MASK] .getQ3(), 0);
assertEquals("0001.0", [MASK] .getMinAsString());
assertEquals("0005.0", [MASK] .getMaxAsString());
assertEquals("0002.0", [MASK] .getQ1AsString());
assertEquals("0003.0", [MASK] .getQ2AsString());
assertEquals("0004.0", [MASK] .getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder(" [MASK] ").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get(" [MASK] "));
InternalBoxplot [MASK] = global.getAggregations().get(" [MASK] ");
assertThat(global.getProperty(" [MASK] "), equalTo( [MASK] ));
assertThat(global.getProperty(" [MASK] .min"), equalTo(1.0));
assertThat(global.getProperty(" [MASK] .max"), equalTo(5.0));
assertThat( [MASK] .getProperty("min"), equalTo(1.0));
assertThat( [MASK] .getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder(" [MASK] ").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) [MASK] -> {
assertEquals(2, [MASK] .getMin(), 0);
assertEquals(8, [MASK] .getMax(), 0);
assertEquals(3.5, [MASK] .getQ1(), 0);
assertEquals(5, [MASK] .getQ2(), 0);
assertEquals(6.5, [MASK] .getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder(" [MASK] ").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) [MASK] -> {
assertEquals(Double.POSITIVE_INFINITY, [MASK] .getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, [MASK] .getMax(), 0);
assertEquals(Double.NaN, [MASK] .getQ1(), 0);
assertEquals(Double.NaN, [MASK] .getQ2(), 0);
assertEquals(Double.NaN, [MASK] .getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder(" [MASK] ").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) [MASK] -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, [MASK] .getMin(), 0);
assertEquals(1.0, [MASK] .getMax(), 0);
assertEquals(1.0, [MASK] .getQ1(), 0);
assertEquals(1.0, [MASK] .getQ2(), 0);
assertEquals(1.0, [MASK] .getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder(" [MASK] ").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| boxplot |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io. [MASK] ;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@ [MASK] Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@ [MASK] Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@ [MASK] Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@ [MASK] Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| TempDir |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org. [MASK] .lucene.document.NumericDocValuesField;
import org. [MASK] .lucene.document.SortedNumericDocValuesField;
import org. [MASK] .lucene.document.SortedSetDocValuesField;
import org. [MASK] .lucene.search.FieldExistsQuery;
import org. [MASK] .lucene.search.MatchAllDocsQuery;
import org. [MASK] .lucene.search.Query;
import org. [MASK] .lucene.tests.index.RandomIndexWriter;
import org. [MASK] .lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| apache |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection< [MASK] > STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection< [MASK] > STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor< [MASK] > STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation< [MASK] > bootstrap(
StreamExecutionEnvironment env, Collection< [MASK] > data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator< [MASK] >> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator< [MASK] > stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator< [MASK] > iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection< [MASK] > state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection< [MASK] > state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection< [MASK] > getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection< [MASK] > state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction< [MASK] , [MASK] > {
private transient ValueState< [MASK] > state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement( [MASK] value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction< [MASK] , [MASK] > {
private transient ValueState< [MASK] > state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public [MASK] map( [MASK] value) throws Exception {
return state.value();
}
}
}
| Integer |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions. [MASK] ;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
[MASK] (metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
[MASK] (operators.size()).isEqualTo(1);
[MASK] (operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
[MASK] (operators.size()).isEqualTo(1);
[MASK] (operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
[MASK] (iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| assertThat |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util. [MASK] ;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final [MASK] <Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final [MASK] <Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, [MASK] <Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final [MASK] <Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final [MASK] <Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public [MASK] <Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final [MASK] <Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| Collection |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals( [MASK] .POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals( [MASK] .NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals( [MASK] .NaN, boxplot.getQ1(), 0);
assertEquals( [MASK] .NaN, boxplot.getQ2(), 0);
assertEquals( [MASK] .NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals( [MASK] .POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals( [MASK] .NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals( [MASK] .NaN, boxplot.getQ1(), 0);
assertEquals( [MASK] .NaN, boxplot.getQ2(), 0);
assertEquals( [MASK] .NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals( [MASK] .POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals( [MASK] .NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals( [MASK] .NaN, boxplot.getQ1(), 0);
assertEquals( [MASK] .NaN, boxplot.getQ2(), 0);
assertEquals( [MASK] .NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| Double |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number"). [MASK] (10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist"). [MASK] (0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number"). [MASK] ("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
. [MASK] ("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
. [MASK] (1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, [MASK] and unmapped interact, these will be the [MASK] value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, [MASK] and unmapped interact, these will be the [MASK] value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| missing |
package org.redisson.tomcat;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1243830648280853203L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession [MASK] = req.getSession();
if (req.getPathInfo().equals("/write")) {
String[] params = req.getQueryString().split("&");
String key = null;
String value = null;
for (String param : params) {
String[] paramLine = param.split("=");
String keyParam = paramLine[0];
String valueParam = paramLine[1];
if ("key".equals(keyParam)) {
key = valueParam;
}
if ("value".equals(keyParam)) {
value = valueParam;
}
}
[MASK] .setAttribute(key, value);
resp.getWriter().print("OK");
} else if (req.getPathInfo().equals("/read")) {
String[] params = req.getQueryString().split("&");
String key = null;
for (String param : params) {
String[] line = param.split("=");
String keyParam = line[0];
if ("key".equals(keyParam)) {
key = line[1];
}
}
Object attr = [MASK] .getAttribute(key);
resp.getWriter().print(attr);
} else if (req.getPathInfo().equals("/remove")) {
String[] params = req.getQueryString().split("&");
String key = null;
for (String param : params) {
String[] line = param.split("=");
String keyParam = line[0];
if ("key".equals(keyParam)) {
key = line[1];
}
}
[MASK] .removeAttribute(key);
resp.getWriter().print(String.valueOf( [MASK] .getAttribute(key)));
} else if (req.getPathInfo().equals("/invalidate")) {
[MASK] .invalidate();
resp.getWriter().print("OK");
} else if (req.getPathInfo().equals("/recreate")) {
[MASK] .invalidate();
[MASK] = req.getSession();
String[] params = req.getQueryString().split("&");
String key = null;
String value = null;
for (String param : params) {
String[] paramLine = param.split("=");
String keyParam = paramLine[0];
String valueParam = paramLine[1];
if ("key".equals(keyParam)) {
key = valueParam;
}
if ("value".equals(keyParam)) {
value = valueParam;
}
}
[MASK] .setAttribute(key, value);
resp.getWriter().print("OK");
}
}
}
| session |
/*
* Copyright (c) 2024, Intel Corporation. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util. [MASK] ;
import java.math.BigInteger;
import java.lang.reflect.Field;
import java.security.spec.ECParameterSpec;
import sun.security.ec.ECOperations;
import sun.security.util.ECUtil;
import sun.security.util.NamedCurve;
import sun.security.util.CurveDB;
import sun.security.ec.point.*;
import java.security.spec.ECPoint;
import sun.security.util.KnownOIDs;
import sun.security.util.math.IntegerMontgomeryFieldModuloP;
import sun.security.util.math.intpoly.*;
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:-UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:+UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
// This test case is NOT entirely deterministic, it uses a random seed for
// pseudo-random number generator. If a failure occurs, hardcode the seed to
// make the test case deterministic
public class ECOperationsFuzzTest {
public static void main(String[] args) throws Exception {
// Note: it might be useful to increase this number during development
final int repeat = 10000;
test(repeat);
System.out.println("Fuzz Success");
}
private static void check(MutablePoint reference, MutablePoint testValue,
long seed, int iter) {
AffinePoint affineRef = reference.asAffine();
AffinePoint affine = testValue.asAffine();
if (!affineRef.equals(affine)) {
throw new RuntimeException(
"Found error with seed " + seed + "at iteration " + iter);
}
}
public static void test(int repeat) throws Exception {
[MASK] rnd = new [MASK] ();
long seed = rnd.nextLong();
rnd.setSeed(seed);
int keySize = 256;
ECParameterSpec params = ECUtil.getECParameterSpec(keySize);
NamedCurve curve = CurveDB.lookup(KnownOIDs.secp256r1.value());
ECPoint generator = curve.getGenerator();
BigInteger b = curve.getCurve().getB();
if (params == null || generator == null) {
throw new RuntimeException(
"No EC parameters available for key size " + keySize + " bits");
}
ECOperations ops = ECOperations.forParameters(params).get();
ECOperations opsReference = new ECOperations(
IntegerPolynomialP256.ONE.getElement(b), P256OrderField.ONE);
boolean instanceTest1 = ops
.getField() instanceof IntegerMontgomeryFieldModuloP;
boolean instanceTest2 = opsReference
.getField() instanceof IntegerMontgomeryFieldModuloP;
if (instanceTest1 == false || instanceTest2 == true) {
throw new RuntimeException("Bad Initialization: ["
+ instanceTest1 + "," + instanceTest2 + "]");
}
byte[] multiple = new byte[keySize / 8];
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // from opsReference.seedToScalar(multiple);
MutablePoint referencePoint = opsReference.multiply(generator, multiple);
MutablePoint point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, -1);
AffinePoint refAffineGenerator = AffinePoint.fromECPoint(generator,
referencePoint.getField());
AffinePoint montAffineGenerator = AffinePoint.fromECPoint(generator,
point.getField());
MutablePoint refProjGenerator = new ProjectivePoint.Mutable(
refAffineGenerator.getX(false).mutable(),
refAffineGenerator.getY(false).mutable(),
referencePoint.getField().get1().mutable());
MutablePoint projGenerator = new ProjectivePoint.Mutable(
montAffineGenerator.getX(false).mutable(),
montAffineGenerator.getY(false).mutable(),
point.getField().get1().mutable());
for (int i = 0; i < repeat; i++) {
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // opsReference.seedToScalar(multiple);
MutablePoint nextReferencePoint = opsReference
.multiply(referencePoint.asAffine(), multiple);
MutablePoint nextPoint = ops.multiply(point.asAffine().toECPoint(),
multiple);
check(nextReferencePoint, nextPoint, seed, i);
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, referencePoint);
ops.setSum(nextPoint, point);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, refProjGenerator);
ops.setSum(nextPoint, projGenerator);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextInt(100) < 10) { // 10% Reset point to generator, test
// generator multiplier
referencePoint = opsReference.multiply(generator, multiple);
point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, i);
} else {
referencePoint = nextReferencePoint;
point = nextPoint;
}
}
}
}
// make test TEST="test/jdk/com/sun/security/ec/ECOperationsFuzzTest.java" | Random |
/*
* Copyright (c) 2024, Intel Corporation. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Random;
import java.math.BigInteger;
import java.lang.reflect.Field;
import java.security.spec.ECParameterSpec;
import sun.security.ec.ECOperations;
import sun.security.util.ECUtil;
import sun.security.util.NamedCurve;
import sun.security.util.CurveDB;
import sun.security.ec.point.*;
import java.security.spec.ECPoint;
import sun.security.util.KnownOIDs;
import sun.security.util.math.IntegerMontgomeryFieldModuloP;
import sun.security.util.math.intpoly.*;
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:-UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:+UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
// This test case is NOT entirely deterministic, it uses a random seed for
// pseudo-random number generator. If a failure occurs, hardcode the seed to
// make the test case deterministic
public class ECOperationsFuzzTest {
public static void main(String[] args) throws Exception {
// Note: it might be useful to increase this number during development
final int repeat = 10000;
test(repeat);
System.out.println("Fuzz Success");
}
private static void check(MutablePoint reference, MutablePoint testValue,
long seed, int iter) {
AffinePoint affineRef = reference.asAffine();
AffinePoint affine = testValue.asAffine();
if (!affineRef.equals(affine)) {
throw new RuntimeException(
"Found error with seed " + seed + "at iteration " + iter);
}
}
public static void test(int repeat) throws Exception {
Random rnd = new Random();
long seed = rnd.nextLong();
rnd.setSeed(seed);
int keySize = 256;
ECParameterSpec params = ECUtil.getECParameterSpec(keySize);
NamedCurve curve = CurveDB.lookup(KnownOIDs.secp256r1.value());
ECPoint generator = curve.getGenerator();
BigInteger b = curve.getCurve().getB();
if (params == null || generator == null) {
throw new RuntimeException(
"No EC parameters available for key size " + keySize + " bits");
}
ECOperations ops = ECOperations.forParameters(params).get();
ECOperations opsReference = new ECOperations(
IntegerPolynomialP256.ONE.getElement(b), P256OrderField.ONE);
boolean instanceTest1 = ops
.getField() instanceof IntegerMontgomeryFieldModuloP;
boolean instanceTest2 = opsReference
.getField() instanceof IntegerMontgomeryFieldModuloP;
if (instanceTest1 == false || instanceTest2 == true) {
throw new RuntimeException("Bad Initialization: ["
+ instanceTest1 + "," + instanceTest2 + "]");
}
byte[] multiple = new byte[keySize / 8];
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // from opsReference.seedToScalar(multiple);
MutablePoint referencePoint = opsReference.multiply(generator, multiple);
MutablePoint point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, -1);
AffinePoint refAffineGenerator = AffinePoint.fromECPoint(generator,
referencePoint.getField());
AffinePoint montAffineGenerator = AffinePoint.fromECPoint(generator,
point.getField());
MutablePoint refProjGenerator = new ProjectivePoint.Mutable(
refAffineGenerator.getX(false).mutable(),
refAffineGenerator.getY(false).mutable(),
referencePoint.getField().get1().mutable());
MutablePoint projGenerator = new ProjectivePoint.Mutable(
montAffineGenerator.getX(false).mutable(),
montAffineGenerator.getY(false).mutable(),
point.getField().get1().mutable());
for (int i = 0; i < repeat; i++) {
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // opsReference.seedToScalar(multiple);
MutablePoint nextReferencePoint = opsReference
.multiply(referencePoint.asAffine(), multiple);
MutablePoint nextPoint = ops.multiply(point.asAffine().toECPoint(),
multiple);
check(nextReferencePoint, nextPoint, seed, i);
if (rnd.nextBoolean()) {
opsReference. [MASK] (nextReferencePoint, referencePoint);
ops. [MASK] (nextPoint, point);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextBoolean()) {
opsReference. [MASK] (nextReferencePoint, refProjGenerator);
ops. [MASK] (nextPoint, projGenerator);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextInt(100) < 10) { // 10% Reset point to generator, test
// generator multiplier
referencePoint = opsReference.multiply(generator, multiple);
point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, i);
} else {
referencePoint = nextReferencePoint;
point = nextPoint;
}
}
}
}
// make test TEST="test/jdk/com/sun/security/ec/ECOperationsFuzzTest.java" | setSum |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final [MASK] uidHash = new AbstractID().toHex [MASK] ();
final [MASK] uid = "uid";
final [MASK] originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final [MASK] newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final [MASK] uid = "uid";
final [MASK] newUid = "fabulous";
final [MASK] originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final [MASK] newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final [MASK] uid = "uid";
final [MASK] newUidHash = new AbstractID().toHex [MASK] ();
final [MASK] originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final [MASK] newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final [MASK] uid1 = "uid1";
final [MASK] uid2 = "uid2";
final [MASK] originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final [MASK] newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static [MASK] bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final [MASK] savepointPath =
tmp.resolve(new AbstractID().toHex [MASK] ()).toAbsolutePath().to [MASK] ();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static [MASK] modifySavepoint(
Path tmp, [MASK] savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final [MASK] newSavepointPath =
tmp.resolve(new AbstractID().toHex [MASK] ()).toAbsolutePath().to [MASK] ();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
[MASK] savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHex [MASK] ()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final [MASK] uid;
private final [MASK] uidHash;
public ValidationParameters(
final Collection<Integer> state, final [MASK] uid, final [MASK] uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public [MASK] getUid() {
return uid;
}
public [MASK] getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final [MASK] uid, final [MASK] uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| String |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util. [MASK] ;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = [MASK] .asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = [MASK] .asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| Arrays |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search. [MASK] .AggregationBuilder;
import org.elasticsearch.search. [MASK] .AggregatorTestCase;
import org.elasticsearch.search. [MASK] .bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search. [MASK] .bucket.global.InternalGlobal;
import org.elasticsearch.search. [MASK] .bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search. [MASK] .bucket.histogram.InternalHistogram;
import org.elasticsearch.search. [MASK] .support.AggregationInspectionHelper;
import org.elasticsearch.search. [MASK] .support.CoreValuesSourceType;
import org.elasticsearch.search. [MASK] .support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics. [MASK] .support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| aggregations |
/*
* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
package build.tools.projectcreator;
class ArgIterator {
String[] args;
int i;
ArgIterator(String[] args) {
this.args = args;
this.i = 0;
}
String get() { return args[i]; }
boolean hasMore() { return args != null && i < args.length; }
boolean next() { return ++i < args.length; }
}
abstract class ArgHandler {
public abstract void handle(ArgIterator it);
}
class [MASK] {
String arg;
ArgHandler handler;
[MASK] (String arg, ArgHandler handler) {
this.arg = arg;
this.handler = handler;
}
boolean process(ArgIterator it) {
if (match(it.get(), arg)) {
handler.handle(it);
return true;
}
return false;
}
boolean match(String rule_pattern, String arg) {
return arg.equals(rule_pattern);
}
}
class ArgsParser {
ArgsParser(String[] args,
[MASK] [] rules,
ArgHandler defaulter) {
ArgIterator ai = new ArgIterator(args);
while (ai.hasMore()) {
boolean processed = false;
for (int i=0; i<rules.length; i++) {
processed |= rules[i].process(ai);
if (processed) {
break;
}
}
if (!processed) {
if (defaulter != null) {
defaulter.handle(ai);
} else {
System.err.println("ERROR: unparsed \""+ai.get()+"\"");
ai.next();
}
}
}
}
}
| ArgRule |
package org.redisson.tomcat;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1243830648280853203L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
if (req.getPathInfo().equals("/write")) {
String[] params = req.getQueryString().split("&");
String key = null;
String value = null;
for (String param : params) {
String[] paramLine = param.split("=");
String [MASK] = paramLine[0];
String valueParam = paramLine[1];
if ("key".equals( [MASK] )) {
key = valueParam;
}
if ("value".equals( [MASK] )) {
value = valueParam;
}
}
session.setAttribute(key, value);
resp.getWriter().print("OK");
} else if (req.getPathInfo().equals("/read")) {
String[] params = req.getQueryString().split("&");
String key = null;
for (String param : params) {
String[] line = param.split("=");
String [MASK] = line[0];
if ("key".equals( [MASK] )) {
key = line[1];
}
}
Object attr = session.getAttribute(key);
resp.getWriter().print(attr);
} else if (req.getPathInfo().equals("/remove")) {
String[] params = req.getQueryString().split("&");
String key = null;
for (String param : params) {
String[] line = param.split("=");
String [MASK] = line[0];
if ("key".equals( [MASK] )) {
key = line[1];
}
}
session.removeAttribute(key);
resp.getWriter().print(String.valueOf(session.getAttribute(key)));
} else if (req.getPathInfo().equals("/invalidate")) {
session.invalidate();
resp.getWriter().print("OK");
} else if (req.getPathInfo().equals("/recreate")) {
session.invalidate();
session = req.getSession();
String[] params = req.getQueryString().split("&");
String key = null;
String value = null;
for (String param : params) {
String[] paramLine = param.split("=");
String [MASK] = paramLine[0];
String valueParam = paramLine[1];
if ("key".equals( [MASK] )) {
key = valueParam;
}
if ("value".equals( [MASK] )) {
value = valueParam;
}
}
session.setAttribute(key, value);
resp.getWriter().print("OK");
}
}
}
| keyParam |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream. [MASK] ;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect( [MASK] .toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect( [MASK] .toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| Collectors |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment. [MASK] ;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer< [MASK] , SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final [MASK] env = [MASK] .getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
[MASK] env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final [MASK] env = [MASK] .getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final [MASK] env = [MASK] .getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| StreamExecutionEnvironment |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers. [MASK] ;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), [MASK] (3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), [MASK] (boxplot));
assertThat(global.getProperty("boxplot.min"), [MASK] (1.0));
assertThat(global.getProperty("boxplot.max"), [MASK] (5.0));
assertThat(boxplot.getProperty("min"), [MASK] (1.0));
assertThat(boxplot.getProperty("max"), [MASK] (5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| equalTo |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> [MASK] =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat( [MASK] .size()).isEqualTo(1);
assertThat( [MASK] .iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> [MASK] =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat( [MASK] .size()).isEqualTo(1);
assertThat( [MASK] .iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| operators |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit. [MASK] .api.Test;
import org.junit. [MASK] .api.extension.RegisterExtension;
import org.junit. [MASK] .api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| jupiter |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.index.mapper.KeywordFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.global.InternalGlobal;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;
import org.elasticsearch.xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw. [MASK] (singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw. [MASK] (singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw. [MASK] (singleton(new SortedNumericDocValuesField("number", 2)));
iw. [MASK] (singleton(new SortedNumericDocValuesField("number", 2)));
iw. [MASK] (singleton(new SortedNumericDocValuesField("number", 3)));
iw. [MASK] (singleton(new SortedNumericDocValuesField("number", 4)));
iw. [MASK] (singleton(new SortedNumericDocValuesField("number", 5)));
iw. [MASK] (singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw. [MASK] (singleton(new NumericDocValuesField("number", 2)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 2)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 3)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 4)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 5)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw. [MASK] (singleton(new SortedNumericDocValuesField("number", 2)));
iw. [MASK] (singleton(new SortedNumericDocValuesField("number", 2)));
iw. [MASK] (singleton(new SortedNumericDocValuesField("number2", 2)));
iw. [MASK] (singleton(new SortedNumericDocValuesField("number", 3)));
iw. [MASK] (singleton(new SortedNumericDocValuesField("number", 4)));
iw. [MASK] (singleton(new SortedNumericDocValuesField("number", 5)));
iw. [MASK] (singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw. [MASK] (singleton(new NumericDocValuesField("number", 2)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 2)));
iw. [MASK] (singleton(new NumericDocValuesField("number2", 2)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 3)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 4)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 5)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw. [MASK] (singleton(new NumericDocValuesField("other", 2)));
iw. [MASK] (singleton(new NumericDocValuesField("other", 2)));
iw. [MASK] (singleton(new NumericDocValuesField("other", 3)));
iw. [MASK] (singleton(new NumericDocValuesField("other", 4)));
iw. [MASK] (singleton(new NumericDocValuesField("other", 5)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw. [MASK] (singleton(new NumericDocValuesField("number", 7)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw. [MASK] (singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw. [MASK] (singleton(new NumericDocValuesField("number", 2)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 2)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 3)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 4)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 5)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw. [MASK] (singleton(new NumericDocValuesField("number", 2)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 2)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 3)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 4)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 5)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw. [MASK] (singleton(new NumericDocValuesField("number", 1)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 3)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 21)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw. [MASK] (singleton(new NumericDocValuesField("number", 1)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 2)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 3)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 4)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw. [MASK] (singleton(new NumericDocValuesField("number", 1)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 2)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 3)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 4)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw. [MASK] (singleton(new NumericDocValuesField("number", 7)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw. [MASK] (singleton(new NumericDocValuesField("number", 7)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw. [MASK] (singleton(new NumericDocValuesField("number", 7)));
iw. [MASK] (singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| addDocument |
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.jdbc.core.metadata;
import java.sql.DatabaseMetaData;
import org.jspecify.annotations.Nullable;
/**
* Holder of meta-data for a specific parameter that is used for call processing.
*
* @author Thomas Risberg
* @author Juergen Hoeller
* @since 2.5
* @see GenericCallMetaDataProvider
*/
public class CallParameterMetaData {
private final boolean function;
private final @Nullable String parameterName;
private final int parameterType;
private final int sqlType;
private final @Nullable String [MASK] ;
private final boolean nullable;
/**
* Constructor taking all the properties including the function marker.
* @since 5.2.9
*/
public CallParameterMetaData(boolean function, @Nullable String columnName, int columnType,
int sqlType, @Nullable String [MASK] , boolean nullable) {
this.function = function;
this.parameterName = columnName;
this.parameterType = columnType;
this.sqlType = sqlType;
this. [MASK] = [MASK] ;
this.nullable = nullable;
}
/**
* Return whether this parameter is declared in a function.
* @since 5.2.9
*/
public boolean isFunction() {
return this.function;
}
/**
* Return the parameter name.
*/
public @Nullable String getParameterName() {
return this.parameterName;
}
/**
* Return the parameter type.
*/
public int getParameterType() {
return this.parameterType;
}
/**
* Determine whether the declared parameter qualifies as a 'return' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnReturn} or
* {@link DatabaseMetaData#procedureColumnResult}, or in case of a function,
* {@link DatabaseMetaData#functionReturn}.
* @since 4.3.15
*/
public boolean isReturnParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionReturn :
(this.parameterType == DatabaseMetaData.procedureColumnReturn ||
this.parameterType == DatabaseMetaData.procedureColumnResult));
}
/**
* Determine whether the declared parameter qualifies as an 'out' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnOut},
* or in case of a function, {@link DatabaseMetaData#functionColumnOut}.
* @since 5.3.31
*/
public boolean isOutParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionColumnOut :
this.parameterType == DatabaseMetaData.procedureColumnOut);
}
/**
* Determine whether the declared parameter qualifies as an 'in-out' parameter
* for our purposes: type {@link DatabaseMetaData#procedureColumnInOut},
* or in case of a function, {@link DatabaseMetaData#functionColumnInOut}.
* @since 5.3.31
*/
public boolean isInOutParameter() {
return (this.function ? this.parameterType == DatabaseMetaData.functionColumnInOut :
this.parameterType == DatabaseMetaData.procedureColumnInOut);
}
/**
* Return the parameter SQL type.
*/
public int getSqlType() {
return this.sqlType;
}
/**
* Return the parameter type name.
*/
public @Nullable String getTypeName() {
return this. [MASK] ;
}
/**
* Return whether the parameter is nullable.
*/
public boolean isNullable() {
return this.nullable;
}
}
| typeName |
/*
* Copyright (c) 2024, Intel Corporation. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Random;
import java.math.BigInteger;
import java.lang.reflect.Field;
import java.security.spec.ECParameterSpec;
import sun.security.ec.ECOperations;
import sun.security.util.ECUtil;
import sun.security.util.NamedCurve;
import sun.security.util.CurveDB;
import sun.security.ec.point.*;
import java.security.spec.ECPoint;
import sun.security.util.KnownOIDs;
import sun.security.util.math.IntegerMontgomeryFieldModuloP;
import sun.security.util.math.intpoly.*;
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:-UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:+UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
// This test case is NOT entirely deterministic, it uses a random seed for
// pseudo-random number generator. If a failure occurs, hardcode the seed to
// make the test case deterministic
public class ECOperationsFuzzTest {
public static void main(String[] args) throws Exception {
// Note: it might be useful to increase this number during development
final int repeat = 10000;
test(repeat);
System.out.println("Fuzz Success");
}
private static void check(MutablePoint reference, MutablePoint testValue,
long seed, int iter) {
AffinePoint affineRef = reference.asAffine();
AffinePoint affine = testValue.asAffine();
if (!affineRef.equals(affine)) {
throw new RuntimeException(
"Found error with seed " + seed + "at iteration " + iter);
}
}
public static void test(int repeat) throws Exception {
Random rnd = new Random();
long seed = rnd.nextLong();
rnd.setSeed(seed);
int keySize = 256;
ECParameterSpec params = ECUtil.getECParameterSpec(keySize);
NamedCurve curve = CurveDB.lookup(KnownOIDs.secp256r1.value());
ECPoint generator = curve.getGenerator();
BigInteger b = curve.getCurve().getB();
if (params == null || generator == null) {
throw new RuntimeException(
"No EC parameters available for key size " + keySize + " bits");
}
ECOperations ops = ECOperations.forParameters(params).get();
ECOperations opsReference = new ECOperations(
IntegerPolynomialP256.ONE.getElement(b), P256OrderField.ONE);
boolean instanceTest1 = ops
.getField() instanceof IntegerMontgomeryFieldModuloP;
boolean instanceTest2 = opsReference
.getField() instanceof IntegerMontgomeryFieldModuloP;
if (instanceTest1 == false || instanceTest2 == true) {
throw new RuntimeException("Bad Initialization: ["
+ instanceTest1 + "," + instanceTest2 + "]");
}
byte[] multiple = new byte[keySize / 8];
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // from opsReference.seedToScalar(multiple);
MutablePoint referencePoint = opsReference.multiply(generator, multiple);
MutablePoint point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, -1);
AffinePoint refAffineGenerator = AffinePoint.fromECPoint(generator,
referencePoint.getField());
AffinePoint montAffineGenerator = AffinePoint.fromECPoint(generator,
point.getField());
MutablePoint refProjGenerator = new ProjectivePoint.Mutable(
refAffineGenerator.getX(false).mutable(),
refAffineGenerator.getY(false).mutable(),
referencePoint.getField().get1().mutable());
MutablePoint projGenerator = new ProjectivePoint.Mutable(
montAffineGenerator.getX(false).mutable(),
montAffineGenerator.getY(false).mutable(),
point.getField().get1().mutable());
for (int i = 0; i < repeat; i++) {
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // opsReference.seedToScalar(multiple);
MutablePoint nextReferencePoint = opsReference
.multiply(referencePoint.asAffine(), multiple);
MutablePoint [MASK] = ops.multiply(point.asAffine().toECPoint(),
multiple);
check(nextReferencePoint, [MASK] , seed, i);
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, referencePoint);
ops.setSum( [MASK] , point);
check(nextReferencePoint, [MASK] , seed, i);
}
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, refProjGenerator);
ops.setSum( [MASK] , projGenerator);
check(nextReferencePoint, [MASK] , seed, i);
}
if (rnd.nextInt(100) < 10) { // 10% Reset point to generator, test
// generator multiplier
referencePoint = opsReference.multiply(generator, multiple);
point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, i);
} else {
referencePoint = nextReferencePoint;
point = [MASK] ;
}
}
}
}
// make test TEST="test/jdk/com/sun/security/ec/ECOperationsFuzzTest.java" | nextPoint |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()). [MASK] (validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()). [MASK] (1);
assertThat(operators.iterator().next().getOperatorID())
. [MASK] (
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()). [MASK] (1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| isEqualTo |
/*
* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
package build.tools.projectcreator;
class ArgIterator {
String[] args;
int i;
ArgIterator(String[] args) {
this.args = args;
this.i = 0;
}
String get() { return args[i]; }
boolean hasMore() { return args != null && i < args.length; }
boolean next() { return ++i < args.length; }
}
abstract class ArgHandler {
public abstract void handle(ArgIterator it);
}
class ArgRule {
String arg;
ArgHandler handler;
ArgRule(String arg, ArgHandler handler) {
this.arg = arg;
this.handler = handler;
}
boolean process(ArgIterator it) {
if (match(it.get(), arg)) {
handler.handle(it);
return true;
}
return false;
}
boolean match(String rule_pattern, String arg) {
return arg.equals(rule_pattern);
}
}
class ArgsParser {
ArgsParser(String[] args,
ArgRule[] [MASK] ,
ArgHandler defaulter) {
ArgIterator ai = new ArgIterator(args);
while (ai.hasMore()) {
boolean processed = false;
for (int i=0; i< [MASK] .length; i++) {
processed |= [MASK] [i].process(ai);
if (processed) {
break;
}
}
if (!processed) {
if (defaulter != null) {
defaulter.handle(ai);
} else {
System.err.println("ERROR: unparsed \""+ai.get()+"\"");
ai.next();
}
}
}
}
}
| rules |
/*
* Copyright (c) 2024, Intel Corporation. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Random;
import java.math.BigInteger;
import java.lang.reflect.Field;
import java.security.spec.ECParameterSpec;
import sun.security.ec.ECOperations;
import sun.security.util.ECUtil;
import sun.security.util.NamedCurve;
import sun.security.util.CurveDB;
import sun.security.ec.point.*;
import java.security.spec.ECPoint;
import sun.security.util.KnownOIDs;
import sun.security.util.math.IntegerMontgomeryFieldModuloP;
import sun.security.util.math.intpoly.*;
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:-UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:+UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
// This test case is NOT entirely deterministic, it uses a random seed for
// pseudo-random number generator. If a failure occurs, hardcode the seed to
// make the test case deterministic
public class ECOperationsFuzzTest {
public static void main(String[] args) throws Exception {
// Note: it might be useful to increase this number during development
final int repeat = 10000;
test(repeat);
System.out.println("Fuzz Success");
}
private static void check(MutablePoint reference, MutablePoint testValue,
long seed, int iter) {
AffinePoint affineRef = reference.asAffine();
AffinePoint affine = testValue.asAffine();
if (!affineRef.equals(affine)) {
throw new RuntimeException(
"Found error with seed " + seed + "at iteration " + iter);
}
}
public static void test(int repeat) throws Exception {
Random rnd = new Random();
long seed = rnd.nextLong();
rnd.setSeed(seed);
int keySize = 256;
ECParameterSpec params = ECUtil.getECParameterSpec(keySize);
NamedCurve curve = CurveDB.lookup(KnownOIDs.secp256r1.value());
ECPoint generator = curve.getGenerator();
BigInteger b = curve.getCurve().getB();
if (params == null || generator == null) {
throw new RuntimeException(
"No EC parameters available for key size " + keySize + " bits");
}
ECOperations ops = ECOperations.forParameters(params).get();
ECOperations opsReference = new ECOperations(
IntegerPolynomialP256.ONE.getElement(b), P256OrderField.ONE);
boolean instanceTest1 = ops
.getField() instanceof IntegerMontgomeryFieldModuloP;
boolean instanceTest2 = opsReference
.getField() instanceof IntegerMontgomeryFieldModuloP;
if (instanceTest1 == false || instanceTest2 == true) {
throw new RuntimeException("Bad Initialization: ["
+ instanceTest1 + "," + instanceTest2 + "]");
}
byte[] multiple = new byte[keySize / 8];
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // from opsReference.seedToScalar(multiple);
MutablePoint referencePoint = opsReference.multiply(generator, multiple);
MutablePoint point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, -1);
AffinePoint [MASK] = AffinePoint.fromECPoint(generator,
referencePoint.getField());
AffinePoint montAffineGenerator = AffinePoint.fromECPoint(generator,
point.getField());
MutablePoint refProjGenerator = new ProjectivePoint.Mutable(
[MASK] .getX(false).mutable(),
[MASK] .getY(false).mutable(),
referencePoint.getField().get1().mutable());
MutablePoint projGenerator = new ProjectivePoint.Mutable(
montAffineGenerator.getX(false).mutable(),
montAffineGenerator.getY(false).mutable(),
point.getField().get1().mutable());
for (int i = 0; i < repeat; i++) {
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // opsReference.seedToScalar(multiple);
MutablePoint nextReferencePoint = opsReference
.multiply(referencePoint.asAffine(), multiple);
MutablePoint nextPoint = ops.multiply(point.asAffine().toECPoint(),
multiple);
check(nextReferencePoint, nextPoint, seed, i);
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, referencePoint);
ops.setSum(nextPoint, point);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, refProjGenerator);
ops.setSum(nextPoint, projGenerator);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextInt(100) < 10) { // 10% Reset point to generator, test
// generator multiplier
referencePoint = opsReference.multiply(generator, multiple);
point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, i);
} else {
referencePoint = nextReferencePoint;
point = nextPoint;
}
}
}
}
// make test TEST="test/jdk/com/sun/security/ec/ECOperationsFuzzTest.java" | refAffineGenerator |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter. [MASK] () != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
. [MASK] ()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter. [MASK] ())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter. [MASK] Hash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter. [MASK] () != null) {
iterators.add(stream.uid(validationParameter. [MASK] ()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter. [MASK] Hash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String [MASK] () {
return uid;
}
public String [MASK] Hash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| getUid |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> [MASK] = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
[MASK] .add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
[MASK] .add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat( [MASK] .get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : [MASK] ) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| iterators |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators. [MASK] ().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators. [MASK] ().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> [MASK] s = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
[MASK] s.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
[MASK] s.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat( [MASK] s.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> [MASK] : [MASK] s) {
[MASK] .close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| iterator |
package org.redisson.tomcat;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1243830648280853203L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
if (req.getPathInfo().equals("/write")) {
String[] params = req.getQueryString(). [MASK] ("&");
String key = null;
String value = null;
for (String param : params) {
String[] paramLine = param. [MASK] ("=");
String keyParam = paramLine[0];
String valueParam = paramLine[1];
if ("key".equals(keyParam)) {
key = valueParam;
}
if ("value".equals(keyParam)) {
value = valueParam;
}
}
session.setAttribute(key, value);
resp.getWriter().print("OK");
} else if (req.getPathInfo().equals("/read")) {
String[] params = req.getQueryString(). [MASK] ("&");
String key = null;
for (String param : params) {
String[] line = param. [MASK] ("=");
String keyParam = line[0];
if ("key".equals(keyParam)) {
key = line[1];
}
}
Object attr = session.getAttribute(key);
resp.getWriter().print(attr);
} else if (req.getPathInfo().equals("/remove")) {
String[] params = req.getQueryString(). [MASK] ("&");
String key = null;
for (String param : params) {
String[] line = param. [MASK] ("=");
String keyParam = line[0];
if ("key".equals(keyParam)) {
key = line[1];
}
}
session.removeAttribute(key);
resp.getWriter().print(String.valueOf(session.getAttribute(key)));
} else if (req.getPathInfo().equals("/invalidate")) {
session.invalidate();
resp.getWriter().print("OK");
} else if (req.getPathInfo().equals("/recreate")) {
session.invalidate();
session = req.getSession();
String[] params = req.getQueryString(). [MASK] ("&");
String key = null;
String value = null;
for (String param : params) {
String[] paramLine = param. [MASK] ("=");
String keyParam = paramLine[0];
String valueParam = paramLine[1];
if ("key".equals(keyParam)) {
key = valueParam;
}
if ("value".equals(keyParam)) {
value = valueParam;
}
}
session.setAttribute(key, value);
resp.getWriter().print("OK");
}
}
}
| split |
package cn.iocoder.yudao.module.infra.enums.codegen;
import cn.iocoder.yudao.framework.common.util.object.ObjectUtils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.Objects;
/**
* 代码生成模板类型
*
* @author 芋道源码
*/
@AllArgsConstructor
@Getter
public enum CodegenTemplateTypeEnum {
ONE(1), // 单表(增删改查)
TREE(2), // 树表(增删改查)
MASTER_NORMAL(10), // 主子表 - 主表 - 普通模式
MASTER_ERP(11), // 主子表 - 主表 - ERP 模式
MASTER_INNER(12), // 主子表 - 主表 - 内嵌模式
SUB(15), // 主子表 - 子表
;
/**
* 类型
*/
private final [MASK] type;
/**
* 是否为主表
*
* @param type 类型
* @return 是否主表
*/
public static boolean isMaster( [MASK] type) {
return ObjectUtils.equalsAny(type,
MASTER_NORMAL.type, MASTER_ERP.type, MASTER_INNER.type);
}
/**
* 是否为树表
*
* @param type 类型
* @return 是否树表
*/
public static boolean isTree( [MASK] type) {
return Objects.equals(type, TREE.type);
}
}
| Integer |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org. [MASK] .xpack.analytics.boxplot;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.search.FieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.util.BytesRef;
import org. [MASK] .common.settings.Settings;
import org. [MASK] .core.CheckedConsumer;
import org. [MASK] .index.mapper.KeywordFieldMapper;
import org. [MASK] .index.mapper.MappedFieldType;
import org. [MASK] .index.mapper.NumberFieldMapper;
import org. [MASK] .plugins.SearchPlugin;
import org. [MASK] .script.MockScriptEngine;
import org. [MASK] .script.Script;
import org. [MASK] .script.ScriptEngine;
import org. [MASK] .script.ScriptModule;
import org. [MASK] .script.ScriptService;
import org. [MASK] .script.ScriptType;
import org. [MASK] .search.aggregations.AggregationBuilder;
import org. [MASK] .search.aggregations.AggregatorTestCase;
import org. [MASK] .search.aggregations.bucket.global.GlobalAggregationBuilder;
import org. [MASK] .search.aggregations.bucket.global.InternalGlobal;
import org. [MASK] .search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org. [MASK] .search.aggregations.bucket.histogram.InternalHistogram;
import org. [MASK] .search.aggregations.support.AggregationInspectionHelper;
import org. [MASK] .search.aggregations.support.CoreValuesSourceType;
import org. [MASK] .search.aggregations.support.ValuesSourceType;
import org. [MASK] .xpack.analytics.AnalyticsPlugin;
import org. [MASK] .xpack.analytics.aggregations.support.AnalyticsValuesSourceType;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
public class BoxplotAggregatorTests extends AggregatorTestCase {
/** Script to return the {@code _value} provided by aggs framework. */
public static final String VALUE_SCRIPT = "_value";
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AnalyticsPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new BoxplotAggregationBuilder("foo").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(CoreValuesSourceType.NUMERIC, AnalyticsValuesSourceType.HISTOGRAM);
}
@Override
protected ScriptService getMockScriptService() {
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
scripts.put(VALUE_SCRIPT, vars -> ((Number) vars.get("_value")).doubleValue() + 1);
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME, scripts, Collections.emptyMap());
Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine);
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L);
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new SortedNumericDocValuesField("wrong_number", 3)));
}, boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
});
}
public void testMatchesSortedNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesSortedNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 3)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 4)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 5)));
iw.addDocument(singleton(new SortedNumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testSomeMatchesNumericDocValues() throws IOException {
testCase(new FieldExistsQuery("number"), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number2", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
}, boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(2.25, boxplot.getQ1(), 0);
assertEquals(3.5, boxplot.getQ2(), 0);
assertEquals(4.75, boxplot.getQ3(), 0);
});
}
public void testMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing(10L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 2)));
iw.addDocument(singleton(new NumericDocValuesField("other", 3)));
iw.addDocument(singleton(new NumericDocValuesField("other", 4)));
iw.addDocument(singleton(new NumericDocValuesField("other", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 0)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(10, boxplot.getMax(), 0);
assertEquals(10, boxplot.getQ1(), 0);
assertEquals(10, boxplot.getQ2(), 0);
assertEquals(10, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnmappedWithMissingField() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist").missing(0L);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(0, boxplot.getMin(), 0);
assertEquals(0, boxplot.getMax(), 0);
assertEquals(0, boxplot.getQ1(), 0);
assertEquals(0, boxplot.getQ2(), 0);
assertEquals(0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testUnsupportedType() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("not_a_number");
MappedFieldType fieldType = new KeywordFieldMapper.KeywordFieldType("not_a_number");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo"))));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
assertEquals(e.getMessage(), "Field [not_a_number] of type [keyword] " + "is not supported for aggregation [boxplot]");
}
public void testBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testUnmappedWithBadMissingField() {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.missing("not_a_number");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
expectThrows(NumberFormatException.class, () -> testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
iw.addDocument(singleton(new NumericDocValuesField("number", 10)));
},
(Consumer<InternalBoxplot>) boxplot -> { fail("Should have thrown exception"); },
new AggTestConfig(aggregationBuilder, fieldType)
));
}
public void testEmptyBucket() throws IOException {
HistogramAggregationBuilder histogram = new HistogramAggregationBuilder("histo").field("number")
.interval(10)
.minDocCount(0)
.subAggregation(new BoxplotAggregationBuilder("boxplot").field("number"));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 21)));
iw.addDocument(singleton(new NumericDocValuesField("number", 23)));
}, (Consumer<InternalHistogram>) histo -> {
assertThat(histo.getBuckets().size(), equalTo(3));
assertNotNull(histo.getBuckets().get(0).getAggregations().get("boxplot"));
InternalBoxplot boxplot = histo.getBuckets().get(0).getAggregations().get("boxplot");
assertEquals(1, boxplot.getMin(), 0);
assertEquals(3, boxplot.getMax(), 0);
assertEquals(1.5, boxplot.getQ1(), 0);
assertEquals(2, boxplot.getQ2(), 0);
assertEquals(2.5, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(1).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(1).getAggregations().get("boxplot");
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
assertNotNull(histo.getBuckets().get(2).getAggregations().get("boxplot"));
boxplot = histo.getBuckets().get(2).getAggregations().get("boxplot");
assertEquals(21, boxplot.getMin(), 0);
assertEquals(23, boxplot.getMax(), 0);
assertEquals(21.5, boxplot.getQ1(), 0);
assertEquals(22, boxplot.getQ2(), 0);
assertEquals(22.5, boxplot.getQ3(), 0);
}, new AggTestConfig(histogram, fieldType));
}
public void testFormatter() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number").format("0000.0");
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(1, boxplot.getMin(), 0);
assertEquals(5, boxplot.getMax(), 0);
assertEquals(2, boxplot.getQ1(), 0);
assertEquals(3, boxplot.getQ2(), 0);
assertEquals(4, boxplot.getQ3(), 0);
assertEquals("0001.0", boxplot.getMinAsString());
assertEquals("0005.0", boxplot.getMaxAsString());
assertEquals("0002.0", boxplot.getQ1AsString());
assertEquals("0003.0", boxplot.getQ2AsString());
assertEquals("0004.0", boxplot.getQ3AsString());
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testGetProperty() throws IOException {
GlobalAggregationBuilder globalBuilder = new GlobalAggregationBuilder("global").subAggregation(
new BoxplotAggregationBuilder("boxplot").field("number")
);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
iw.addDocument(singleton(new NumericDocValuesField("number", 2)));
iw.addDocument(singleton(new NumericDocValuesField("number", 3)));
iw.addDocument(singleton(new NumericDocValuesField("number", 4)));
iw.addDocument(singleton(new NumericDocValuesField("number", 5)));
}, (Consumer<InternalGlobal>) global -> {
assertEquals(5, global.getDocCount());
assertTrue(AggregationInspectionHelper.hasValue(global));
assertNotNull(global.getAggregations().get("boxplot"));
InternalBoxplot boxplot = global.getAggregations().get("boxplot");
assertThat(global.getProperty("boxplot"), equalTo(boxplot));
assertThat(global.getProperty("boxplot.min"), equalTo(1.0));
assertThat(global.getProperty("boxplot.max"), equalTo(5.0));
assertThat(boxplot.getProperty("min"), equalTo(1.0));
assertThat(boxplot.getProperty("max"), equalTo(5.0));
}, new AggTestConfig(globalBuilder, fieldType));
}
public void testValueScript() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(2, boxplot.getMin(), 0);
assertEquals(8, boxplot.getMax(), 0);
assertEquals(3.5, boxplot.getQ1(), 0);
assertEquals(5, boxplot.getQ2(), 0);
assertEquals(6.5, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmapped() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
assertEquals(Double.POSITIVE_INFINITY, boxplot.getMin(), 0);
assertEquals(Double.NEGATIVE_INFINITY, boxplot.getMax(), 0);
assertEquals(Double.NaN, boxplot.getQ1(), 0);
assertEquals(Double.NaN, boxplot.getQ2(), 0);
assertEquals(Double.NaN, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
public void testValueScriptUnmappedMissing() throws IOException {
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("does_not_exist")
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()))
.missing(1.0);
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
testCase(iw -> {
iw.addDocument(singleton(new NumericDocValuesField("number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("number", 1)));
}, (Consumer<InternalBoxplot>) boxplot -> {
// Note: the way scripts, missing and unmapped interact, these will be the missing value and the script is not invoked
assertEquals(1.0, boxplot.getMin(), 0);
assertEquals(1.0, boxplot.getMax(), 0);
assertEquals(1.0, boxplot.getQ1(), 0);
assertEquals(1.0, boxplot.getQ2(), 0);
assertEquals(1.0, boxplot.getQ3(), 0);
}, new AggTestConfig(aggregationBuilder, fieldType));
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalBoxplot> verify)
throws IOException {
MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number", NumberFieldMapper.NumberType.INTEGER);
BoxplotAggregationBuilder aggregationBuilder = new BoxplotAggregationBuilder("boxplot").field("number");
testCase(buildIndex, verify, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query));
}
}
| elasticsearch |
/*
* Copyright (c) 2024, Intel Corporation. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Random;
import java.math.BigInteger;
import java.lang.reflect.Field;
import java.security.spec.ECParameterSpec;
import sun.security.ec.ECOperations;
import sun.security.util.ECUtil;
import sun.security.util.NamedCurve;
import sun.security.util.CurveDB;
import sun.security.ec.point.*;
import java.security.spec.ECPoint;
import sun.security.util.KnownOIDs;
import sun.security.util.math.IntegerMontgomeryFieldModuloP;
import sun.security.util.math.intpoly.*;
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:-UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
/*
* @test
* @key randomness
* @modules java.base/sun.security.ec java.base/sun.security.ec.point
* java.base/sun.security.util java.base/sun.security.util.math
* java.base/sun.security.util.math.intpoly
* @run main/othervm/timeout=1200 --add-opens
* java.base/sun.security.ec=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions
* -XX:+UseIntPolyIntrinsics ECOperationsFuzzTest
* @summary Unit test ECOperationsFuzzTest.
*/
// This test case is NOT entirely deterministic, it uses a random seed for
// pseudo-random number generator. If a failure occurs, hardcode the seed to
// make the test case deterministic
public class ECOperationsFuzzTest {
public static void main(String[] args) throws Exception {
// Note: it might be useful to increase this number during development
final int repeat = 10000;
test(repeat);
System.out.println("Fuzz Success");
}
private static void check(MutablePoint reference, MutablePoint testValue,
long seed, int iter) {
AffinePoint affineRef = reference.asAffine();
AffinePoint affine = testValue.asAffine();
if (!affineRef.equals(affine)) {
throw new [MASK] (
"Found error with seed " + seed + "at iteration " + iter);
}
}
public static void test(int repeat) throws Exception {
Random rnd = new Random();
long seed = rnd.nextLong();
rnd.setSeed(seed);
int keySize = 256;
ECParameterSpec params = ECUtil.getECParameterSpec(keySize);
NamedCurve curve = CurveDB.lookup(KnownOIDs.secp256r1.value());
ECPoint generator = curve.getGenerator();
BigInteger b = curve.getCurve().getB();
if (params == null || generator == null) {
throw new [MASK] (
"No EC parameters available for key size " + keySize + " bits");
}
ECOperations ops = ECOperations.forParameters(params).get();
ECOperations opsReference = new ECOperations(
IntegerPolynomialP256.ONE.getElement(b), P256OrderField.ONE);
boolean instanceTest1 = ops
.getField() instanceof IntegerMontgomeryFieldModuloP;
boolean instanceTest2 = opsReference
.getField() instanceof IntegerMontgomeryFieldModuloP;
if (instanceTest1 == false || instanceTest2 == true) {
throw new [MASK] ("Bad Initialization: ["
+ instanceTest1 + "," + instanceTest2 + "]");
}
byte[] multiple = new byte[keySize / 8];
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // from opsReference.seedToScalar(multiple);
MutablePoint referencePoint = opsReference.multiply(generator, multiple);
MutablePoint point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, -1);
AffinePoint refAffineGenerator = AffinePoint.fromECPoint(generator,
referencePoint.getField());
AffinePoint montAffineGenerator = AffinePoint.fromECPoint(generator,
point.getField());
MutablePoint refProjGenerator = new ProjectivePoint.Mutable(
refAffineGenerator.getX(false).mutable(),
refAffineGenerator.getY(false).mutable(),
referencePoint.getField().get1().mutable());
MutablePoint projGenerator = new ProjectivePoint.Mutable(
montAffineGenerator.getX(false).mutable(),
montAffineGenerator.getY(false).mutable(),
point.getField().get1().mutable());
for (int i = 0; i < repeat; i++) {
rnd.nextBytes(multiple);
multiple[keySize/8 - 1] &= 0x7f; // opsReference.seedToScalar(multiple);
MutablePoint nextReferencePoint = opsReference
.multiply(referencePoint.asAffine(), multiple);
MutablePoint nextPoint = ops.multiply(point.asAffine().toECPoint(),
multiple);
check(nextReferencePoint, nextPoint, seed, i);
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, referencePoint);
ops.setSum(nextPoint, point);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextBoolean()) {
opsReference.setSum(nextReferencePoint, refProjGenerator);
ops.setSum(nextPoint, projGenerator);
check(nextReferencePoint, nextPoint, seed, i);
}
if (rnd.nextInt(100) < 10) { // 10% Reset point to generator, test
// generator multiplier
referencePoint = opsReference.multiply(generator, multiple);
point = ops.multiply(generator, multiple);
check(referencePoint, point, seed, i);
} else {
referencePoint = nextReferencePoint;
point = nextPoint;
}
}
}
}
// make test TEST="test/jdk/com/sun/security/ec/ECOperationsFuzzTest.java" | RuntimeException |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@ [MASK]
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@ [MASK]
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@ [MASK]
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@ [MASK]
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| Override |
/*
* 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.flink.state.api;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test. [MASK] 5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org. [MASK] .jupiter.api.Test;
import org. [MASK] .jupiter.api.extension.RegisterExtension;
import org. [MASK] .jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| junit |
package org.redisson.tomcat;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1243830648280853203L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
if (req.getPathInfo().equals("/write")) {
String[] [MASK] = req.getQueryString().split("&");
String key = null;
String value = null;
for (String param : [MASK] ) {
String[] paramLine = param.split("=");
String keyParam = paramLine[0];
String valueParam = paramLine[1];
if ("key".equals(keyParam)) {
key = valueParam;
}
if ("value".equals(keyParam)) {
value = valueParam;
}
}
session.setAttribute(key, value);
resp.getWriter().print("OK");
} else if (req.getPathInfo().equals("/read")) {
String[] [MASK] = req.getQueryString().split("&");
String key = null;
for (String param : [MASK] ) {
String[] line = param.split("=");
String keyParam = line[0];
if ("key".equals(keyParam)) {
key = line[1];
}
}
Object attr = session.getAttribute(key);
resp.getWriter().print(attr);
} else if (req.getPathInfo().equals("/remove")) {
String[] [MASK] = req.getQueryString().split("&");
String key = null;
for (String param : [MASK] ) {
String[] line = param.split("=");
String keyParam = line[0];
if ("key".equals(keyParam)) {
key = line[1];
}
}
session.removeAttribute(key);
resp.getWriter().print(String.valueOf(session.getAttribute(key)));
} else if (req.getPathInfo().equals("/invalidate")) {
session.invalidate();
resp.getWriter().print("OK");
} else if (req.getPathInfo().equals("/recreate")) {
session.invalidate();
session = req.getSession();
String[] [MASK] = req.getQueryString().split("&");
String key = null;
String value = null;
for (String param : [MASK] ) {
String[] paramLine = param.split("=");
String keyParam = paramLine[0];
String valueParam = paramLine[1];
if ("key".equals(keyParam)) {
key = valueParam;
}
if ("value".equals(keyParam)) {
value = valueParam;
}
}
session.setAttribute(key, value);
resp.getWriter().print("OK");
}
}
}
| params |
/*
* 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.flink.state.api;
import org.apache.flink.api.common. [MASK] ;
import org.apache.flink.api.common.functions.OpenContext;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.metadata.CheckpointMetadata;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.state.api.functions.KeyedStateBootstrapFunction;
import org.apache.flink.state.api.runtime.SavepointLoader;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/** IT test for modifying UIDs in savepoints. */
public class SavepointWriterUidModificationITCase {
@RegisterExtension
static final MiniClusterExtension MINI_CLUSTER_RESOURCE =
new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
private static final Collection<Integer> STATE_1 = Arrays.asList(1, 2, 3);
private static final Collection<Integer> STATE_2 = Arrays.asList(4, 5, 6);
private static final ValueStateDescriptor<Integer> STATE_DESCRIPTOR =
new ValueStateDescriptor<>("number", Types.INT);
@Test
public void testAddUid(@TempDir Path tmp) throws Exception {
final String uidHash = new AbstractID().toHexString();
final String uid = "uid";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUidHash(uidHash),
bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUidHash(uidHash),
OperatorIdentifier.forUid(uid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, uid, null));
}
@Test
public void testChangeUid(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUid = "fabulous";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUid(newUid)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, newUid, null));
}
@Test
public void testChangeUidHashOnly(@TempDir Path tmp) throws Exception {
final String uid = "uid";
final String newUidHash = new AbstractID().toHexString();
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid), bootstrap(env, STATE_1)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid),
OperatorIdentifier.forUidHash(newUidHash)));
runAndValidate(newSavepoint, ValidationParameters.of(STATE_1, null, newUidHash));
}
@Test
public void testSwapUid(@TempDir Path tmp) throws Exception {
final String uid1 = "uid1";
final String uid2 = "uid2";
final String originalSavepoint =
bootstrapState(
tmp,
(env, writer) ->
writer.withOperator(
OperatorIdentifier.forUid(uid1),
bootstrap(env, STATE_1))
.withOperator(
OperatorIdentifier.forUid(uid2),
bootstrap(env, STATE_2)));
final String newSavepoint =
modifySavepoint(
tmp,
originalSavepoint,
writer ->
writer.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid1),
OperatorIdentifier.forUid(uid2))
.changeOperatorIdentifier(
OperatorIdentifier.forUid(uid2),
OperatorIdentifier.forUid(uid1)));
runAndValidate(
newSavepoint,
ValidationParameters.of(STATE_1, uid2, null),
ValidationParameters.of(STATE_2, uid1, null));
}
private static String bootstrapState(
Path tmp, BiConsumer<StreamExecutionEnvironment, SavepointWriter> mutator)
throws Exception {
final String savepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode( [MASK] .AUTOMATIC);
final SavepointWriter writer = SavepointWriter.newSavepoint(env, 128);
mutator.accept(env, writer);
writer.write(savepointPath);
env.execute("Bootstrap");
return savepointPath;
}
private static StateBootstrapTransformation<Integer> bootstrap(
StreamExecutionEnvironment env, Collection<Integer> data) {
return OperatorTransformation.bootstrapWith(env.fromData(data))
.keyBy(v -> v)
.transform(new StateBootstrapper());
}
private static String modifySavepoint(
Path tmp, String savepointPath, Consumer<SavepointWriter> mutator) throws Exception {
final String newSavepointPath =
tmp.resolve(new AbstractID().toHexString()).toAbsolutePath().toString();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode( [MASK] .AUTOMATIC);
SavepointWriter writer = SavepointWriter.fromExistingSavepoint(env, savepointPath);
mutator.accept(writer);
writer.write(newSavepointPath);
env.execute("Modifying");
return newSavepointPath;
}
private static void runAndValidate(
String savepointPath, ValidationParameters... validationParameters) throws Exception {
// validate metadata
CheckpointMetadata metadata = SavepointLoader.loadSavepointMetadata(savepointPath);
assertThat(metadata.getOperatorStates().size()).isEqualTo(validationParameters.length);
for (ValidationParameters validationParameter : validationParameters) {
if (validationParameter.getUid() != null) {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorUid().isPresent()
&& os.getOperatorUid()
.get()
.equals(
validationParameter
.getUid()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorID())
.isEqualTo(
OperatorIdentifier.forUid(validationParameter.getUid())
.getOperatorId());
} else {
Set<OperatorState> operators =
metadata.getOperatorStates().stream()
.filter(
os ->
os.getOperatorID()
.toHexString()
.equals(validationParameter.getUidHash()))
.collect(Collectors.toSet());
assertThat(operators.size()).isEqualTo(1);
assertThat(operators.iterator().next().getOperatorUid()).isEmpty();
}
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// prepare collection of state
final List<CloseableIterator<Integer>> iterators = new ArrayList<>();
for (ValidationParameters validationParameter : validationParameters) {
SingleOutputStreamOperator<Integer> stream =
env.fromData(validationParameter.getState())
.keyBy(v -> v)
.map(new StateReader());
if (validationParameter.getUid() != null) {
iterators.add(stream.uid(validationParameter.getUid()).collectAsync());
} else {
iterators.add(stream.setUidHash(validationParameter.getUidHash()).collectAsync());
}
}
// run job
StreamGraph streamGraph = env.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, false));
env.executeAsync(streamGraph);
// validate state
for (int i = 0; i < validationParameters.length; i++) {
assertThat(iterators.get(i))
.toIterable()
.containsExactlyInAnyOrderElementsOf(validationParameters[i].getState());
}
for (CloseableIterator<Integer> iterator : iterators) {
iterator.close();
}
}
private static class ValidationParameters {
private final Collection<Integer> state;
private final String uid;
private final String uidHash;
public ValidationParameters(
final Collection<Integer> state, final String uid, final String uidHash) {
this.state = state;
this.uid = uid;
this.uidHash = uidHash;
}
public Collection<Integer> getState() {
return state;
}
public String getUid() {
return uid;
}
public String getUidHash() {
return uidHash;
}
public static ValidationParameters of(
final Collection<Integer> state, final String uid, final String uidHash) {
return new ValidationParameters(state, uid, uidHash);
}
}
/** A savepoint writer function. */
public static class StateBootstrapper extends KeyedStateBootstrapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public void processElement(Integer value, Context ctx) throws Exception {
state.update(value);
}
}
/** A savepoint reader function. */
public static class StateReader extends RichMapFunction<Integer, Integer> {
private transient ValueState<Integer> state;
@Override
public void open(OpenContext openContext) {
state = getRuntimeContext().getState(STATE_DESCRIPTOR);
}
@Override
public Integer map(Integer value) throws Exception {
return state.value();
}
}
}
| RuntimeExecutionMode |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.