index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddProtocols.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.List;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Adds all built-in AWS protocols.
*/
@SmithyInternalApi
public class AddProtocols implements TypeScriptIntegration {
@Override
public List<ProtocolGenerator> getProtocolGenerators() {
return ListUtils.of(new AwsRestJson1(), new AwsJsonRpc1_0(), new AwsJsonRpc1_1(),
new AwsRestXml(), new AwsQuery(), new AwsEc2());
}
}
| 4,800 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/JsonShapeSerVisitor.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.BiFunction;
import software.amazon.smithy.aws.typescript.codegen.validation.UnaryFunctionCall;
import software.amazon.smithy.codegen.core.Symbol;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.CollectionShape;
import software.amazon.smithy.model.shapes.DocumentShape;
import software.amazon.smithy.model.shapes.MapShape;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.shapes.UnionShape;
import software.amazon.smithy.model.traits.IdempotencyTokenTrait;
import software.amazon.smithy.model.traits.JsonNameTrait;
import software.amazon.smithy.model.traits.SparseTrait;
import software.amazon.smithy.model.traits.TimestampFormatTrait;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.DocumentMemberSerVisitor;
import software.amazon.smithy.typescript.codegen.integration.DocumentShapeSerVisitor;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator.GenerationContext;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Visitor to generate serialization functions for shapes in AWS JSON protocol
* document bodies.
*
* This class handles function body generation for all types expected by the {@code
* DocumentShapeSerVisitor}. No other shape type serialization is overridden.
*
* Timestamps are serialized to {@link Format}.EPOCH_SECONDS by default.
*/
@SmithyInternalApi
final class JsonShapeSerVisitor extends DocumentShapeSerVisitor {
private static final Format TIMESTAMP_FORMAT = Format.EPOCH_SECONDS;
private final BiFunction<MemberShape, String, String> memberNameStrategy;
JsonShapeSerVisitor(GenerationContext context, boolean serdeElisionEnabled) {
this(context,
// Use the jsonName trait value if present, otherwise use the member name.
(memberShape, memberName) -> memberShape.getTrait(JsonNameTrait.class)
.map(JsonNameTrait::getValue)
.orElse(memberName),
serdeElisionEnabled);
}
JsonShapeSerVisitor(GenerationContext context, BiFunction<MemberShape, String, String> memberNameStrategy,
boolean serdeElisionEnabled) {
super(context);
this.serdeElisionEnabled = serdeElisionEnabled;
this.memberNameStrategy = memberNameStrategy;
}
private DocumentMemberSerVisitor getMemberVisitor(String dataSource) {
return new JsonMemberSerVisitor(getContext(), dataSource, TIMESTAMP_FORMAT);
}
@Override
public void serializeCollection(GenerationContext context, CollectionShape shape) {
TypeScriptWriter writer = context.getWriter();
Shape target = context.getModel().expectShape(shape.getMember().getTarget());
// Filter out null entries if we don't have the sparse trait.
String potentialFilter = "";
boolean hasSparseTrait = shape.hasTrait(SparseTrait.ID);
if (!hasSparseTrait) {
potentialFilter = ".filter((e: any) => e != null)";
}
String returnedExpression = target.accept(getMemberVisitor("entry"));
if (returnedExpression.equals("entry")) {
writer.write("return input$L;", potentialFilter);
} else {
writer.openBlock("return input$L.map(entry => {", "});", potentialFilter, () -> {
// Short circuit null values from serialization.
if (hasSparseTrait) {
writer.write("if (entry === null) { return null as any; }");
}
// Dispatch to the input value provider for any additional handling.
writer.write("return $L;", target.accept(getMemberVisitor("entry")));
});
}
}
@Override
public void serializeDocument(GenerationContext context, DocumentShape shape) {
TypeScriptWriter writer = context.getWriter();
// Documents are JSON content, so don't modify.
writer.write("return input;");
}
@Override
public void serializeMap(GenerationContext context, MapShape shape) {
TypeScriptWriter writer = context.getWriter();
Shape target = context.getModel().expectShape(shape.getValue().getTarget());
SymbolProvider symbolProvider = context.getSymbolProvider();
Symbol keySymbol = symbolProvider.toSymbol(shape.getKey());
String entryKeyType = keySymbol.toString().equals("string")
? "string"
: symbolProvider.toSymbol(shape.getKey()) + "| string";
// Get the right serialization for each entry in the map. Undefined
// inputs won't have this serializer invoked.
writer.openBlock("return Object.entries(input).reduce((acc: Record<string, any>, "
+ "[key, value]: [$1L, any]) => {", "}, {});", entryKeyType,
() -> {
writer.openBlock("if (value === null) {", "}", () -> {
// Handle the sparse trait by short-circuiting null values
// from serialization, and not including them if encountered
// when not sparse.
if (shape.hasTrait(SparseTrait.ID)) {
writer.write("acc[key] = null as any;");
}
writer.write("return acc;");
});
// Dispatch to the input value provider for any additional handling.
writer.write("acc[key] = $L;", target.accept(getMemberVisitor("value")));
writer.write("return acc;");
}
);
}
@Override
public void serializeStructure(GenerationContext context, StructureShape shape) {
TypeScriptWriter writer = context.getWriter();
writer.addImport("take", null, TypeScriptDependency.AWS_SMITHY_CLIENT);
writer.openBlock("return take(input, {", "});", () -> {
// Use a TreeMap to sort the members.
Map<String, MemberShape> members = new TreeMap<>(shape.getAllMembers());
members.forEach((memberName, memberShape) -> {
String wireName = memberNameStrategy.apply(memberShape, memberName);
boolean hasJsonName = memberShape.hasTrait(JsonNameTrait.class);
Shape target = context.getModel().expectShape(memberShape.getTarget());
String inputLocation = "input." + memberName;
// Handle @timestampFormat on members not just the targeted shape.
String valueExpression = (memberShape.hasTrait(TimestampFormatTrait.class)
? AwsProtocolUtils.getInputTimestampValueProvider(context, memberShape,
TIMESTAMP_FORMAT, "_")
: target.accept(getMemberVisitor("_")));
String valueProvider = "_ => " + valueExpression;
boolean isUnaryCall = UnaryFunctionCall.check(valueExpression);
if (hasJsonName) {
if (memberShape.hasTrait(IdempotencyTokenTrait.class)) {
writer.write("'$L': [true, _ => _ ?? generateIdempotencyToken(), `$L`],", wireName, memberName);
} else {
if (valueProvider.equals("_ => _")) {
writer.write("'$L': [,,`$L`],", wireName, memberName);
} else if (isUnaryCall) {
writer.write("'$L': [,$L,`$L`],", wireName,
UnaryFunctionCall.toRef(valueExpression), memberName);
} else {
writer.write("'$L': [,$L,`$L`],", wireName, valueProvider, memberName);
}
}
} else {
if (memberShape.hasTrait(IdempotencyTokenTrait.class)) {
writer.write("'$L': [true, _ => _ ?? generateIdempotencyToken()],", memberName);
} else {
if (valueProvider.equals("_ => _")) {
writer.write("'$1L': [],", memberName);
} else if (isUnaryCall) {
writer.write("'$1L': $2L,", memberName, UnaryFunctionCall.toRef(valueExpression));
} else {
writer.write("'$1L': $2L,", memberName, valueProvider);
}
}
}
});
});
}
@Override
public void serializeUnion(GenerationContext context, UnionShape shape) {
TypeScriptWriter writer = context.getWriter();
Model model = context.getModel();
ServiceShape serviceShape = context.getService();
// Visit over the union type, then get the right serialization for the member.
writer.openBlock("return $L.visit(input, {", "});", shape.getId().getName(serviceShape), () -> {
// Use a TreeMap to sort the members.
Map<String, MemberShape> members = new TreeMap<>(shape.getAllMembers());
members.forEach((memberName, memberShape) -> {
String locationName = memberNameStrategy.apply(memberShape, memberName);
Shape target = model.expectShape(memberShape.getTarget());
// Dispatch to the input value provider for any additional handling.
writer.write("$L: value => ({ $S: $L }),", memberName, locationName,
target.accept(getMemberVisitor("value")));
});
writer.write("_: (name, value) => ({ name: value } as any)");
});
}
}
| 4,801 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddCrossRegionCopyingPlugin.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_MIDDLEWARE;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SetUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
@SmithyInternalApi
public class AddCrossRegionCopyingPlugin implements TypeScriptIntegration {
private static final Map<String, Set<String>> PRESIGNED_URL_OPERATIONS_MAP = MapUtils.of(
"RDS", SetUtils.of(
"CopyDBClusterSnapshot",
"CreateDBCluster",
"CopyDBSnapshot",
"CreateDBInstanceReadReplica",
"StartDBInstanceAutomatedBackupsReplication"),
"DocDB", SetUtils.of("CopyDBClusterSnapshot"),
"Neptune", SetUtils.of("CopyDBClusterSnapshot", "CreateDBCluster")
);
@Override
public List<RuntimeClientPlugin> getClientPlugins() {
return PRESIGNED_URL_OPERATIONS_MAP.entrySet().stream().map((entry) -> {
String serviceId = entry.getKey();
Set<String> commands = entry.getValue();
return RuntimeClientPlugin.builder()
.withConventions(AwsDependency.RDS_MIDDLEWARE.dependency, "CrossRegionPresignedUrl", HAS_MIDDLEWARE)
.operationPredicate(
(m, s, o) -> commands.contains(o.getId().getName(s)) && testServiceId(s, serviceId))
.build();
}).collect(Collectors.toList());
}
private static boolean testServiceId(Shape serviceShape, String expectedId) {
return serviceShape.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse("").equals(expectedId);
}
}
| 4,802 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AwsRestJson1.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import software.amazon.smithy.aws.traits.protocols.RestJson1Trait;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Handles generating the aws.rest-json-1 protocol for services.
*
* {@inheritDoc}
*
* @see RestJsonProtocolGenerator
*/
@SmithyInternalApi
public final class AwsRestJson1 extends RestJsonProtocolGenerator {
@Override
protected String getDocumentContentType() {
return "application/json";
}
@Override
public ShapeId getProtocol() {
return RestJson1Trait.ID;
}
@Override
public String getName() {
return "aws.rest-json-1";
}
}
| 4,803 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddOmitRetryHeadersDependency.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_MIDDLEWARE;
import java.util.List;
import java.util.Set;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.SetUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
@SmithyInternalApi
public class AddOmitRetryHeadersDependency implements TypeScriptIntegration {
private static final Set<String> SERVICE_IDS = SetUtils.of(
"ConnectParticipant", // P43593766
"DataBrew", // P55897945
"IoT", // P39759657
"Kinesis Video Signaling"
);
@Override
public List<RuntimeClientPlugin> getClientPlugins() {
return ListUtils.of(
RuntimeClientPlugin.builder()
.withConventions(TypeScriptDependency.MIDDLEWARE_RETRY.dependency, "OmitRetryHeaders",
HAS_MIDDLEWARE)
.servicePredicate((m, s) -> {
String sdkId = s.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse("");
return SERVICE_IDS.contains(sdkId);
})
.build()
);
}
}
| 4,804 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/QueryShapeSerVisitor.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import software.amazon.smithy.aws.typescript.codegen.propertyaccess.PropertyAccessor;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.CollectionShape;
import software.amazon.smithy.model.shapes.DocumentShape;
import software.amazon.smithy.model.shapes.MapShape;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.shapes.UnionShape;
import software.amazon.smithy.model.traits.SparseTrait;
import software.amazon.smithy.model.traits.TimestampFormatTrait;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.model.traits.XmlFlattenedTrait;
import software.amazon.smithy.model.traits.XmlNameTrait;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.DocumentMemberSerVisitor;
import software.amazon.smithy.typescript.codegen.integration.DocumentShapeSerVisitor;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator.GenerationContext;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Visitor to generate serialization functions for shapes in form-urlencoded
* based document bodies.
*
* This class handles function body generation for all types expected by the {@code
* DocumentShapeSerVisitor}. No other shape type serialization is overridden.
*
* Timestamps are serialized to {@link Format}.DATE_TIME by default.
*/
@SmithyInternalApi
class QueryShapeSerVisitor extends DocumentShapeSerVisitor {
private static final Format TIMESTAMP_FORMAT = Format.DATE_TIME;
QueryShapeSerVisitor(GenerationContext context) {
super(context);
}
private QueryMemberSerVisitor getMemberVisitor(String dataSource) {
return new QueryMemberSerVisitor(getContext(), dataSource, TIMESTAMP_FORMAT);
}
@Override
protected void serializeCollection(GenerationContext context, CollectionShape shape) {
TypeScriptWriter writer = context.getWriter();
MemberShape memberShape = shape.getMember();
Shape target = context.getModel().expectShape(memberShape.getTarget());
// Use the @xmlName trait if present on the member, otherwise use "member".
String locationName = getMemberSerializedLocationName(memberShape, "member");
// Set up a location to store all of the entry pairs.
writer.write("const entries: any = {};");
// Set up a counter to increment the member entries.
writer.write("let counter = 1;");
writer.openBlock("for (let entry of input) {", "}", () -> {
writer.openBlock("if (entry === null) {", "}", () -> {
// Handle the sparse trait by short circuiting null values
// from serialization, and not including them if encountered
// when not sparse.
if (shape.hasTrait(SparseTrait.ID)) {
writer.write("entries[`$L.$${counter}`] = null as any }", locationName);
}
writer.write("continue;");
});
QueryMemberSerVisitor inputVisitor = getMemberVisitor("entry");
if (inputVisitor.visitSuppliesEntryList(target)) {
// Dispatch to the input value provider for any additional handling.
serializeUnnamedMemberEntryList(context, target, "entry", locationName + ".${counter}");
} else {
writer.write("entries[`$L.$${counter}`] = $L;", locationName, target.accept(inputVisitor));
}
writer.write("counter++;");
});
writer.write("return entries;");
}
@Override
protected void serializeDocument(GenerationContext context, DocumentShape shape) {
throw new CodegenException(String.format(
"Cannot serialize Document types in the aws.query protocol, shape: %s.", shape.getId()));
}
@Override
protected void serializeMap(GenerationContext context, MapShape shape) {
TypeScriptWriter writer = context.getWriter();
Model model = context.getModel();
String keyTypeName = "keyof typeof input";
// Filter out null entries if we don't have the sparse trait.
String potentialFilter = "";
if (!shape.hasTrait(SparseTrait.ID)) {
potentialFilter = ".filter((key) => input[key as " + keyTypeName + "] != null)";
}
// Set up a location to store all of the entry pairs.
writer.write("const entries: any = {};");
// Set up a counter to increment the member entries.
writer.write("let counter = 1;");
// Use the keys as an iteration point to dispatch to the input value providers.
writer.openBlock("Object.keys(input)$L.forEach(key => {", "});", potentialFilter, () -> {
// Prepare the key's entry.
// Use the @xmlName trait if present on the member, otherwise use "key".
MemberShape keyMember = shape.getKey();
Shape keyTarget = model.expectShape(keyMember.getTarget());
String keyName = getMemberSerializedLocationName(keyMember, "key");
writer.write("entries[`entry.$${counter}.$L`] = $L;", keyName, keyTarget.accept(getMemberVisitor("key")));
// Prepare the value's entry.
// Use the @xmlName trait if present on the member, otherwise use "value".
MemberShape valueMember = shape.getValue();
Shape valueTarget = model.expectShape(valueMember.getTarget());
String valueName = getMemberSerializedLocationName(valueMember, "value");
QueryMemberSerVisitor inputVisitor = getMemberVisitor("input[key as " + keyTypeName + "]!");
String valueLocation = "entry.${counter}." + valueName;
if (inputVisitor.visitSuppliesEntryList(valueTarget)) {
serializeUnnamedMemberEntryList(
context,
valueTarget,
"input[key as " + keyTypeName + "]!",
valueLocation
);
} else {
writer.write("entries[`$L`] = $L;", valueLocation, valueTarget.accept(inputVisitor));
}
writer.write("counter++;");
});
writer.write("return entries;");
}
private void serializeUnnamedMemberEntryList(
GenerationContext context,
Shape target,
String inputLocation,
String entryWrapper
) {
TypeScriptWriter writer = context.getWriter();
QueryMemberSerVisitor inputVisitor = getMemberVisitor(inputLocation);
// Map entries that supply entry lists need to have them joined properly.
writer.write("const memberEntries = $L;", target.accept(inputVisitor));
writer.openBlock("Object.entries(memberEntries).forEach(([key, value]) => {", "});",
() -> writer.write("entries[`$L.$${key}`] = value;", entryWrapper));
}
@Override
protected void serializeStructure(GenerationContext context, StructureShape shape) {
TypeScriptWriter writer = context.getWriter();
// Set up a location to store all of the entry pairs.
writer.write("const entries: any = {};");
// Serialize every member of the structure if present.
shape.getAllMembers().forEach((memberName, memberShape) -> {
String inputLocation = "input." + memberName;
// Handle if the member is an idempotency token that should be auto-filled.
AwsProtocolUtils.writeIdempotencyAutofill(context, memberShape, inputLocation);
writer.openBlock(
"if ($1L != null) {",
"}",
inputLocation,
() -> {
serializeNamedMember(context, memberName, memberShape, inputLocation);
}
);
});
writer.write("return entries");
}
private void serializeNamedMember(
GenerationContext context,
String memberName,
MemberShape memberShape,
String inputLocation
) {
// Grab the target shape so we can use a member serializer on it.
Shape target = context.getModel().expectShape(memberShape.getTarget());
String locationName = getMemberSerializedLocationName(memberShape, memberName);
QueryMemberSerVisitor inputVisitor = getMemberVisitor(inputLocation);
if (inputVisitor.visitSuppliesEntryList(target)) {
serializeNamedMemberEntryList(context, locationName, memberShape, target, inputVisitor, inputLocation);
} else {
serializeNamedMemberValue(context, locationName, "input." + memberName, memberShape, target);
}
}
private void serializeNamedMemberValue(
GenerationContext context,
String locationName,
String dataSource,
MemberShape memberShape,
Shape target
) {
TypeScriptWriter writer = context.getWriter();
// Handle @timestampFormat on members not just the targeted shape.
String valueProvider = memberShape.hasTrait(TimestampFormatTrait.class)
? AwsProtocolUtils.getInputTimestampValueProvider(context, memberShape,
TIMESTAMP_FORMAT, dataSource)
: target.accept(getMemberVisitor(dataSource));
writer.write("entries[$S] = $L;", locationName, valueProvider);
}
/**
* Retrieves the correct serialization location based on the member's
* xmlName trait or uses the default value.
*
* @param memberShape The member being serialized.
* @param defaultValue A default value for the location.
* @return The location where the member will be serialized.
*/
protected String getMemberSerializedLocationName(MemberShape memberShape, String defaultValue) {
// Use the @xmlName trait if present on the member, otherwise use the member name.
return memberShape.getTrait(XmlNameTrait.class)
.map(XmlNameTrait::getValue)
.orElse(defaultValue);
}
private void serializeNamedMemberEntryList(
GenerationContext context,
String locationName,
MemberShape memberShape,
Shape target,
DocumentMemberSerVisitor inputVisitor,
String inputLocation
) {
TypeScriptWriter writer = context.getWriter();
// Handle flattening for collections and maps.
boolean isFlattened = isFlattenedMember(context, memberShape);
// Set up a location to store all of the entry pairs.
writer.write("const memberEntries = $L;", target.accept(inputVisitor));
Shape targetShape = context.getModel().expectShape(memberShape.getTarget());
if (targetShape.isListShape() || targetShape.isSetShape()) {
writer.openBlock(
"if ($L?.length === 0) {",
"}",
inputLocation,
() -> {
writer.write("$L = []", PropertyAccessor.getFrom("entries", locationName));
}
);
}
// Consolidate every entry in the list.
writer.openBlock("Object.entries(memberEntries).forEach(([key, value]) => {", "});", () -> {
// Remove the last segment for any flattened entities.
if (isFlattened) {
writer.write("const loc = `$L.$${key.substring(key.indexOf('.') + 1)}`;", locationName);
} else {
writer.write("const loc = `$L.$${key}`;", locationName);
}
writer.write("entries[loc] = value;");
});
}
/**
* Tells whether the contents of the member should be flattened
* when serialized.
*
* @param context The generation context.
* @param memberShape The member being serialized.
* @return If the member's contents should be flattened when serialized.
*/
protected boolean isFlattenedMember(GenerationContext context, MemberShape memberShape) {
// The @xmlFlattened trait determines the flattening of members in aws.query.
return memberShape.hasTrait(XmlFlattenedTrait.class);
}
@Override
protected void serializeUnion(GenerationContext context, UnionShape shape) {
TypeScriptWriter writer = context.getWriter();
ServiceShape serviceShape = context.getService();
// Set up a location to store the entry pair.
writer.write("const entries: any = {};");
// Visit over the union type, then get the right serialization for the member.
writer.openBlock("$L.visit(input, {", "});", shape.getId().getName(serviceShape), () -> {
shape.getAllMembers().forEach((memberName, memberShape) -> {
writer.openBlock("$L: value => {", "},", memberName, () -> {
serializeNamedMember(context, memberName, memberShape, "value");
});
});
// Handle the unknown property.
writer.openBlock("_: (name: string, value: any) => {", "}", () -> {
writer.write("entries[name] = value;");
});
});
writer.write("return entries;");
}
}
| 4,805 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddHttpChecksumDependency.java | /*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_MIDDLEWARE;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Consumer;
import software.amazon.smithy.aws.traits.HttpChecksumTrait;
import software.amazon.smithy.codegen.core.Symbol;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.TopDownIndex;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Adds checksum dependencies if needed.
*/
@SmithyInternalApi
public class AddHttpChecksumDependency implements TypeScriptIntegration {
@Override
public void addConfigInterfaceFields(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
if (!hasHttpChecksumTrait(model, settings.getService(model))) {
return;
}
writer.addImport("Readable", "Readable", "stream");
writer.addImport("StreamHasher", "__StreamHasher", TypeScriptDependency.SMITHY_TYPES);
writer.writeDocs("A function that, given a hash constructor and a stream, calculates the \n"
+ "hash of the streamed value.\n"
+ "@internal");
writer.write("streamHasher?: __StreamHasher<Readable> | __StreamHasher<Blob>;\n");
writer.addImport("Hash", "__Hash", TypeScriptDependency.SMITHY_TYPES);
writer.addImport("HashConstructor", "__HashConstructor", TypeScriptDependency.SMITHY_TYPES);
writer.addImport("Checksum", "__Checksum", TypeScriptDependency.SMITHY_TYPES);
writer.addImport("ChecksumConstructor", "__ChecksumConstructor", TypeScriptDependency.SMITHY_TYPES);
writer.writeDocs("A constructor for a class implementing the {@link __Checksum} interface \n"
+ "that computes MD5 hashes.\n"
+ "@internal");
writer.write("md5?: __ChecksumConstructor | __HashConstructor;\n");
writer.writeDocs("A constructor for a class implementing the {@link __Checksum} interface \n"
+ "that computes SHA1 hashes.\n"
+ "@internal");
writer.write("sha1?: __ChecksumConstructor | __HashConstructor;\n");
writer.addImport("GetAwsChunkedEncodingStream", "GetAwsChunkedEncodingStream",
TypeScriptDependency.AWS_SDK_TYPES);
writer.writeDocs("A function that returns Readable Stream which follows aws-chunked encoding stream.\n"
+ "@internal");
writer.write("getAwsChunkedEncodingStream?: GetAwsChunkedEncodingStream;\n");
}
@Override
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
LanguageTarget target
) {
if (!hasHttpChecksumTrait(model, settings.getService(model))) {
return Collections.emptyMap();
}
switch (target) {
case SHARED:
return MapUtils.of(
"getAwsChunkedEncodingStream", writer -> {
writer.addDependency(TypeScriptDependency.UTIL_STREAM);
writer.addImport("getAwsChunkedEncodingStream", "getAwsChunkedEncodingStream",
TypeScriptDependency.UTIL_STREAM);
writer.write("getAwsChunkedEncodingStream");
}
);
case NODE:
return MapUtils.of(
"streamHasher", writer -> {
writer.addDependency(TypeScriptDependency.STREAM_HASHER_NODE);
writer.addImport("readableStreamHasher", "streamHasher",
TypeScriptDependency.STREAM_HASHER_NODE);
writer.write("streamHasher");
},
"md5", writer -> {
writer.addDependency(TypeScriptDependency.AWS_SDK_TYPES);
writer.addImport("HashConstructor", "__HashConstructor",
TypeScriptDependency.AWS_SDK_TYPES);
writer.addImport("ChecksumConstructor", "__ChecksumConstructor",
TypeScriptDependency.AWS_SDK_TYPES);
writer.write("Hash.bind(null, \"md5\")");
},
"sha1", writer -> {
writer.addDependency(TypeScriptDependency.AWS_SDK_TYPES);
writer.addImport("HashConstructor", "__HashConstructor",
TypeScriptDependency.AWS_SDK_TYPES);
writer.addImport("ChecksumConstructor", "__ChecksumConstructor",
TypeScriptDependency.AWS_SDK_TYPES);
writer.write("Hash.bind(null, \"sha1\")");
}
);
case BROWSER:
return MapUtils.of(
"streamHasher", writer -> {
writer.addDependency(TypeScriptDependency.STREAM_HASHER_BROWSER);
writer.addImport("blobHasher", "streamHasher",
TypeScriptDependency.STREAM_HASHER_BROWSER);
writer.write("streamHasher");
},
"md5", writer -> {
writer.addDependency(TypeScriptDependency.MD5_BROWSER);
writer.addImport("Md5", "Md5", TypeScriptDependency.MD5_BROWSER);
writer.write("Md5");
},
"sha1", writer -> {
writer.addDependency(AwsDependency.AWS_CRYPTO_SHA1_BROWSER);
writer.addImport("Sha1",
"Sha1", AwsDependency.AWS_CRYPTO_SHA1_BROWSER.packageName);
writer.write("Sha1");
}
);
default:
return Collections.emptyMap();
}
}
@Override
public List<RuntimeClientPlugin> getClientPlugins() {
return ListUtils.of(
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.FLEXIBLE_CHECKSUMS_MIDDLEWARE.dependency, "FlexibleChecksums",
HAS_MIDDLEWARE)
.additionalPluginFunctionParamsSupplier((m, s, o) -> getPluginFunctionParams(m, s, o))
.operationPredicate((m, s, o) -> hasHttpChecksumTrait(o))
.build()
);
}
private static Map<String, Object> getPluginFunctionParams(
Model model,
ServiceShape service,
OperationShape operation
) {
Map<String, Object> params = new TreeMap<String, Object>();
params.put("input", Symbol.builder().name("this.input").build());
HttpChecksumTrait httpChecksumTrait = operation.expectTrait(HttpChecksumTrait.class);
params.put("requestChecksumRequired", httpChecksumTrait.isRequestChecksumRequired());
httpChecksumTrait.getRequestAlgorithmMember().ifPresent(requestAlgorithmMember -> {
params.put("requestAlgorithmMember", requestAlgorithmMember);
});
httpChecksumTrait.getRequestValidationModeMember().ifPresent(requestValidationModeMember -> {
params.put("requestValidationModeMember", requestValidationModeMember);
params.put("responseAlgorithms", httpChecksumTrait.getResponseAlgorithms());
});
return params;
}
// return true if operation shape is decorated with `httpChecksum` trait.
private static boolean hasHttpChecksumTrait(OperationShape operation) {
return operation.hasTrait(HttpChecksumTrait.class);
}
private static boolean hasHttpChecksumTrait(
Model model,
ServiceShape service
) {
TopDownIndex topDownIndex = TopDownIndex.of(model);
Set<OperationShape> operations = topDownIndex.getContainedOperations(service);
for (OperationShape operation : operations) {
if (hasHttpChecksumTrait(operation)) {
return true;
}
}
return false;
}
}
| 4,806 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/DocumentBareBonesClientGenerator.java | /*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.stream.Collectors;
import software.amazon.smithy.codegen.core.Symbol;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.TopDownIndex;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.typescript.codegen.ApplicationProtocol;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.utils.SmithyInternalApi;
@SmithyInternalApi
final class DocumentBareBonesClientGenerator implements Runnable {
static final String CLIENT_CONFIG_SECTION = "client_config";
static final String CLIENT_PROPERTIES_SECTION = "client_properties";
static final String CLIENT_CONSTRUCTOR_SECTION = "client_constructor";
static final String CLIENT_DESTROY_SECTION = "client_destroy";
private final Model model;
private final SymbolProvider symbolProvider;
private final ServiceShape service;
private final TypeScriptWriter writer;
private final Symbol symbol;
private final String serviceName;
private final String configType;
DocumentBareBonesClientGenerator(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
this.model = model;
this.symbolProvider = symbolProvider;
this.service = settings.getService(model);
this.writer = writer;
symbol = symbolProvider.toSymbol(service);
serviceName = symbol.getName();
configType = DocumentClientUtils.getResolvedConfigTypeName(symbol.getName());
}
@Override
public void run() {
String serviceInputTypes = "ServiceInputTypes";
String serviceOutputTypes = "ServiceOutputTypes";
// Add required imports.
writer.addImport(serviceName, serviceName, "@aws-sdk/client-dynamodb");
writer.addImport(configType, configType, "@aws-sdk/client-dynamodb");
writer.addImport("Client", "__Client", TypeScriptDependency.AWS_SMITHY_CLIENT);
writer.writeDocs("@public");
writer.write("export { __Client };");
generateInputOutputImports(serviceInputTypes, serviceOutputTypes);
generateInputOutputTypeUnion(serviceInputTypes,
operationSymbol -> operationSymbol.expectProperty("inputType", Symbol.class).getName());
generateInputOutputTypeUnion(serviceOutputTypes,
operationSymbol -> operationSymbol.expectProperty("outputType", Symbol.class).getName());
writer.write("");
generateConfiguration();
writer.writeDocs(DocumentClientUtils.getClientDocs() + "\n\n@public");
writer.openBlock("export class $L extends __Client<$T, $L, $L, $L> {", "}",
DocumentClientUtils.CLIENT_NAME,
ApplicationProtocol.createDefaultHttpApplicationProtocol().getOptionsType(),
serviceInputTypes, serviceOutputTypes,
DocumentClientUtils.CLIENT_CONFIG_NAME, () -> {
generateClientProperties();
writer.write("");
generateClientConstructor();
writer.write("");
generateStaticFactoryFrom();
writer.write("");
generateDestroy();
});
}
private void generateInputOutputImports(String serviceInputTypes, String serviceOutputTypes) {
writer.addImport(serviceInputTypes, String.format("__%s", serviceInputTypes), "@aws-sdk/client-dynamodb");
writer.addImport(serviceOutputTypes, String.format("__%s", serviceOutputTypes), "@aws-sdk/client-dynamodb");
Set<OperationShape> containedOperations =
new TreeSet<>(TopDownIndex.of(model).getContainedOperations(service));
for (OperationShape operation : containedOperations) {
if (DocumentClientUtils.containsAttributeValue(model, symbolProvider, operation)) {
Symbol operationSymbol = symbolProvider.toSymbol(operation);
String name = DocumentClientUtils.getModifiedName(operationSymbol.getName());
String input = DocumentClientUtils.getModifiedName(
operationSymbol.expectProperty("inputType", Symbol.class).getName()
);
String output = DocumentClientUtils.getModifiedName(
operationSymbol.expectProperty("outputType", Symbol.class).getName()
);
String commandFileLocation = String.format("./%s/%s",
DocumentClientUtils.CLIENT_COMMANDS_FOLDER, name);
writer.addImport(input, input, commandFileLocation);
writer.addImport(output, output, commandFileLocation);
}
}
}
private void generateInputOutputTypeUnion(String typeName, Function<Symbol, String> mapper) {
writer.writeDocs("@public");
Set<OperationShape> containedOperations =
new TreeSet<>(TopDownIndex.of(model).getContainedOperations(service));
List<String> operationTypeNames = containedOperations.stream()
.filter(operation -> DocumentClientUtils.containsAttributeValue(model, symbolProvider, operation))
.map(symbolProvider::toSymbol)
.map(operation -> mapper.apply(operation))
.map(operationtypeName -> DocumentClientUtils.getModifiedName(operationtypeName))
.collect(Collectors.toList());
writer.write("export type $L = $L", typeName, String.format("__%s", typeName));
writer.indent();
for (int i = 0; i < operationTypeNames.size(); i++) {
writer.write("| $L$L", operationTypeNames.get(i), i == operationTypeNames.size() - 1 ? ";" : "");
}
writer.dedent();
writer.write("");
}
private void generateDestroy() {
writer.pushState(CLIENT_DESTROY_SECTION);
writer.openBlock("destroy(): void {", "}", () -> {
writer.write("// A no-op, since client is passed in constructor");
});
writer.popState();
}
private void generateStaticFactoryFrom() {
writer.openBlock("static from(client: $L, translateConfig?: $L) {", "}",
serviceName, DocumentClientUtils.CLIENT_TRANSLATE_CONFIG_TYPE, () -> {
writer.write("return new $L(client, translateConfig);", DocumentClientUtils.CLIENT_NAME);
});
}
private void generateClientProperties() {
writer.pushState(CLIENT_PROPERTIES_SECTION);
writer.write("readonly config: $L;\n", DocumentClientUtils.CLIENT_CONFIG_NAME);
writer.popState();
}
private void generateClientConstructor() {
writer.openBlock("protected constructor(client: $L, translateConfig?: $L){", "}",
symbol.getName(), DocumentClientUtils.CLIENT_TRANSLATE_CONFIG_TYPE, () -> {
writer.pushState(CLIENT_CONSTRUCTOR_SECTION);
writer.write("super(client.config);");
writer.write("this.config = client.config;");
writer.write("this.config.translateConfig = translateConfig;");
writer.write("this.middlewareStack = client.middlewareStack;");
writer.popState();
});
}
private void generateConfiguration() {
writer.pushState(CLIENT_CONFIG_SECTION);
String translateConfigType = DocumentClientUtils.CLIENT_TRANSLATE_CONFIG_TYPE;
writer.writeDocs("@public");
writer.openBlock("export type $L = {", "}", translateConfigType, () -> {
generateTranslateConfigOption(DocumentClientUtils.CLIENT_MARSHALL_OPTIONS);
generateTranslateConfigOption(DocumentClientUtils.CLIENT_UNMARSHALL_OPTIONS);
});
writer.write("");
writer.writeDocs("@public");
writer.openBlock("export type $L = $L & {", "};", DocumentClientUtils.CLIENT_CONFIG_NAME,
configType, () -> {
writer.write("$L?: $L;", DocumentClientUtils.CLIENT_TRANSLATE_CONFIG_KEY, translateConfigType);
});
writer.write("");
writer.popState();
}
private void generateTranslateConfigOption(String translateOption) {
writer.addImport(translateOption, translateOption, "@aws-sdk/util-dynamodb");
writer.write("${1L}?: ${1L};", translateOption);
}
}
| 4,807 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddTranscribeStreamingDependency.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Add client plugins and configs to support WebSocket streaming for Transcribe
* Streaming service.
**/
@SmithyInternalApi
public class AddTranscribeStreamingDependency implements TypeScriptIntegration {
@Override
public List<RuntimeClientPlugin> getClientPlugins() {
return ListUtils.of(
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.TRANSCRIBE_STREAMING_MIDDLEWARE.dependency,
"TranscribeStreaming", RuntimeClientPlugin.Convention.HAS_MIDDLEWARE)
.servicePredicate((m, s) -> isTranscribeStreaming(s))
.build()
);
}
@Override
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
LanguageTarget target
) {
ServiceShape service = settings.getService(model);
if (!isTranscribeStreaming(service)) {
return Collections.emptyMap();
}
Map<String, Consumer<TypeScriptWriter>> transcribeStreamingHandlerConfig = MapUtils.of(
"eventStreamPayloadHandlerProvider", writer -> {
writer.addDependency(AwsDependency.TRANSCRIBE_STREAMING_MIDDLEWARE);
writer.addImport("eventStreamPayloadHandler", "eventStreamPayloadHandler",
AwsDependency.TRANSCRIBE_STREAMING_MIDDLEWARE.packageName);
writer.write("(() => eventStreamPayloadHandler)");
});
switch (target) {
case REACT_NATIVE:
case BROWSER:
return transcribeStreamingHandlerConfig;
default:
return Collections.emptyMap();
}
}
private static boolean isTranscribeStreaming(ServiceShape service) {
String serviceId = service.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse("");
return serviceId.equals("Transcribe Streaming");
}
}
| 4,808 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/JsonShapeDeserVisitor.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.aws.typescript.codegen.propertyaccess.PropertyAccessor.getFrom;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.BiFunction;
import software.amazon.smithy.aws.typescript.codegen.validation.UnaryFunctionCall;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.CollectionShape;
import software.amazon.smithy.model.shapes.DocumentShape;
import software.amazon.smithy.model.shapes.MapShape;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.NumberShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.shapes.UnionShape;
import software.amazon.smithy.model.traits.JsonNameTrait;
import software.amazon.smithy.model.traits.MediaTypeTrait;
import software.amazon.smithy.model.traits.SparseTrait;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.typescript.codegen.CodegenUtils;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings.ArtifactType;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.DocumentMemberDeserVisitor;
import software.amazon.smithy.typescript.codegen.integration.DocumentShapeDeserVisitor;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator.GenerationContext;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Visitor to generate deserialization functions for shapes in AWS JSON protocol
* document bodies.
*
* No standard visitation methods are overridden; function body generation for all
* expected deserializers is handled by this class.
*
* Timestamps are deserialized from {@link Format}.EPOCH_SECONDS by default.
*/
@SmithyInternalApi
final class JsonShapeDeserVisitor extends DocumentShapeDeserVisitor {
private final BiFunction<MemberShape, String, String> memberNameStrategy;
JsonShapeDeserVisitor(GenerationContext context, boolean serdeElisionEnabled) {
this(context,
// Use the jsonName trait value if present, otherwise use the member name.
(memberShape, memberName) -> memberShape.getTrait(JsonNameTrait.class)
.map(JsonNameTrait::getValue)
.orElse(memberName),
serdeElisionEnabled);
}
JsonShapeDeserVisitor(GenerationContext context, BiFunction<MemberShape, String, String> memberNameStrategy,
boolean serdeElisionEnabled) {
super(context);
this.serdeElisionEnabled = serdeElisionEnabled;
this.memberNameStrategy = memberNameStrategy;
}
private DocumentMemberDeserVisitor getMemberVisitor(MemberShape memberShape, String dataSource) {
return new JsonMemberDeserVisitor(getContext(), memberShape, dataSource, Format.EPOCH_SECONDS);
}
@Override
protected void deserializeCollection(GenerationContext context, CollectionShape shape) {
TypeScriptWriter writer = context.getWriter();
Shape target = context.getModel().expectShape(shape.getMember().getTarget());
ArtifactType artifactType = context.getSettings().getArtifactType();
// Filter out null entries if we don't have the sparse trait.
String potentialFilter = "";
if (!shape.hasTrait(SparseTrait.ID) && !artifactType.equals(ArtifactType.SSDK)) {
potentialFilter = ".filter((e: any) => e != null)";
}
final String filterExpression = potentialFilter;
String returnExpression = target.accept(getMemberVisitor(shape.getMember(), "entry"));
if (returnExpression.equals("entry") && !artifactType.equals(ArtifactType.SSDK)) {
writer.write("const retVal = (output || [])$L", filterExpression);
} else {
writer.openBlock("const retVal = (output || [])$L.map((entry: any) => {", "});",
filterExpression, () -> {
// Short circuit null values from serialization.
if (filterExpression.isEmpty()) {
writer.openBlock("if (entry === null) {", "}", () -> {
// In the SSDK we want to be very strict about not accepting nulls in non-sparse
// lists.
if (!shape.hasTrait(SparseTrait.ID) && artifactType.equals(ArtifactType.SSDK)) {
writer.write(
"throw new TypeError('All elements of the non-sparse list $S must be non-null.');",
shape.getId());
} else {
writer.write("return null as any;");
}
});
}
// Dispatch to the output value provider for any additional handling.
writer.write("return $L$L;",
target.accept(getMemberVisitor(shape.getMember(), "entry")),
usesExpect(target) ? " as any" : "");
}
);
}
if (shape.isSetShape() && artifactType.equals(ArtifactType.SSDK)) {
writer.addDependency(TypeScriptDependency.SERVER_COMMON);
writer.addImport("findDuplicates", "__findDuplicates", "@aws-smithy/server-common");
writer.openBlock("if (__findDuplicates(retVal).length > 0) {", "}", () -> {
writer.write("throw new TypeError('All elements of the set $S must be unique.');",
shape.getId());
});
}
writer.write("return retVal;");
}
@Override
protected void deserializeDocument(GenerationContext context, DocumentShape shape) {
TypeScriptWriter writer = context.getWriter();
// Documents are JSON content, so don't modify.
writer.write("return output;");
}
@Override
protected void deserializeMap(GenerationContext context, MapShape shape) {
TypeScriptWriter writer = context.getWriter();
Shape target = context.getModel().expectShape(shape.getValue().getTarget());
SymbolProvider symbolProvider = context.getSymbolProvider();
// Get the right serialization for each entry in the map. Undefined
// outputs won't have this deserializer invoked.
writer.openBlock("return Object.entries(output).reduce((acc: $T, [key, value]: [string, any]) => {",
"",
symbolProvider.toSymbol(shape),
() -> {
writer.openBlock("if (value === null) {", "}", () -> {
// Handle the sparse trait by short-circuiting null values
// from deserialization, and not including them if encountered
// when not sparse.
if (shape.hasTrait(SparseTrait.ID)) {
writer.write("acc[key as $T] = null as any;", symbolProvider.toSymbol(shape.getKey()));
}
writer.write("return acc;");
});
// Dispatch to the output value provider for any additional handling.
writer.write("acc[key as $T] = $L$L",
symbolProvider.toSymbol(shape.getKey()),
target.accept(getMemberVisitor(shape.getValue(), "value")),
usesExpect(target) ? " as any;" : ";"
);
writer.write("return acc;");
}
);
writer.writeInline("}, {} as $T);", symbolProvider.toSymbol(shape));
}
@Override
protected void deserializeStructure(GenerationContext context, StructureShape shape) {
TypeScriptWriter writer = context.getWriter();
// Prepare the document contents structure.
// Use a TreeMap to sort the members.
Map<String, MemberShape> members = new TreeMap<>(shape.getAllMembers());
writer.addImport("take", null, TypeScriptDependency.AWS_SMITHY_CLIENT);
writer.openBlock("return take(output, {", "}) as any;", () -> {
// Set all the members to undefined to meet type constraints.
members.forEach((memberName, memberShape) -> {
String wireName = memberNameStrategy.apply(memberShape, memberName);
boolean hasJsonName = memberShape.hasTrait(JsonNameTrait.class);
Shape target = context.getModel().expectShape(memberShape.getTarget());
String propertyAccess = getFrom("output", wireName);
String value = target.accept(getMemberVisitor(memberShape, "_"));
if (hasJsonName) {
if (usesExpect(target)) {
if (UnaryFunctionCall.check(value)) {
writer.write("'$L': [,$L,`$L`],", memberName, UnaryFunctionCall.toRef(value), wireName);
} else {
writer.write("'$L': [,$L,`$L`],", memberName, "_ => " + value, wireName);
}
} else {
String valueExpression = target.accept(getMemberVisitor(memberShape, propertyAccess));
if (valueExpression.equals(propertyAccess)) {
writer.write("'$L': [,,`$L`],", memberName, wireName);
} else {
String functionExpression = value;
boolean isUnaryCall = UnaryFunctionCall.check(functionExpression);
if (isUnaryCall) {
writer.write("'$L': [,$L,`$L`],",
memberName,
UnaryFunctionCall.toRef(functionExpression),
wireName
);
} else {
writer.write("'$L': [, (_: any) => $L,`$L`],",
memberName,
functionExpression,
wireName
);
}
}
}
} else {
if (usesExpect(target)) {
if (UnaryFunctionCall.check(value)) {
writer.write("'$L': $L,", memberName, UnaryFunctionCall.toRef(value));
} else {
writer.write("'$L': $L,", memberName, "_ => " + value);
}
} else {
String valueExpression = target.accept(getMemberVisitor(memberShape, propertyAccess));
if (valueExpression.equals(propertyAccess)) {
writer.write("'$1L': [],", memberName);
} else {
String functionExpression = value;
boolean isUnaryCall = UnaryFunctionCall.check(functionExpression);
if (isUnaryCall) {
writer.write("'$1L': $2L,",
memberName,
UnaryFunctionCall.toRef(functionExpression)
);
} else {
writer.write("'$1L': (_: any) => $2L,",
memberName,
functionExpression
);
}
}
}
}
});
});
}
private boolean usesExpect(Shape shape) {
if (shape.isStringShape()) {
if (shape.hasTrait(MediaTypeTrait.class)) {
return !CodegenUtils.isJsonMediaType(shape.expectTrait(MediaTypeTrait.class).getValue());
}
return true;
}
return shape.isBooleanShape() || shape instanceof NumberShape;
}
@Override
protected void deserializeUnion(GenerationContext context, UnionShape shape) {
TypeScriptWriter writer = context.getWriter();
Model model = context.getModel();
// Check for any known union members and return when we find one.
Map<String, MemberShape> members = new TreeMap<>(shape.getAllMembers());
members.forEach((memberName, memberShape) -> {
Shape target = model.expectShape(memberShape.getTarget());
String locationName = memberNameStrategy.apply(memberShape, memberName);
String memberValue = target.accept(getMemberVisitor(memberShape, getFrom("output", locationName)));
if (usesExpect(target)) {
// Booleans and numbers will call expectBoolean/expectNumber which will handle
// null/undefined properly.
writer.openBlock("if ($L !== undefined) {", "}", memberValue, () -> {
writer.write("return { $L: $L as any }", memberName, memberValue);
});
} else {
writer.openBlock(
"if ($1L != null) {", "}",
getFrom("output", locationName),
() -> writer.openBlock(
"return {", "};",
() -> {
// Dispatch to the output value provider for any additional handling.
writer.write("$L: $L", memberName, memberValue);
}
)
);
}
});
// Or write to the unknown member the element in the output.
writer.write("return { $$unknown: Object.entries(output)[0] };");
}
}
| 4,809 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddSqsDependency.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_MIDDLEWARE;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Adds SQS customization.
*/
@SmithyInternalApi
public class AddSqsDependency implements TypeScriptIntegration {
@Override
public List<RuntimeClientPlugin> getClientPlugins() {
return ListUtils.of(
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.SQS_MIDDLEWARE.dependency, "SendMessage",
HAS_MIDDLEWARE)
.operationPredicate((m, s, o) -> o.getId().getName(s).equals("SendMessage") && isSqs(s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.SQS_MIDDLEWARE.dependency, "SendMessageBatch",
HAS_MIDDLEWARE)
.operationPredicate((m, s, o) -> o.getId().getName(s).equals("SendMessageBatch") && isSqs(s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.SQS_MIDDLEWARE.dependency, "ReceiveMessage",
HAS_MIDDLEWARE)
.operationPredicate((m, s, o) -> o.getId().getName(s).equals("ReceiveMessage") && isSqs(s))
.build()
);
}
@Override
public void addConfigInterfaceFields(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
if (!isSqs(settings.getService(model))) {
return;
}
writer.addImport("Hash", "__Hash", TypeScriptDependency.SMITHY_TYPES);
writer.addImport("HashConstructor", "__HashConstructor", TypeScriptDependency.SMITHY_TYPES);
writer.addImport("Checksum", "__Checksum", TypeScriptDependency.SMITHY_TYPES);
writer.addImport("ChecksumConstructor", "__ChecksumConstructor", TypeScriptDependency.SMITHY_TYPES);
writer.writeDocs("A constructor for a class implementing the {@link __Checksum} interface \n"
+ "that computes MD5 hashes.\n"
+ "@internal");
writer.write("md5?: __ChecksumConstructor | __HashConstructor;\n");
}
@Override
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
LanguageTarget target
) {
if (!isSqs(settings.getService(model))) {
return Collections.emptyMap();
}
switch (target) {
case NODE:
return MapUtils.of("md5", writer -> {
writer.addDependency(TypeScriptDependency.AWS_SDK_TYPES);
writer.addImport("HashConstructor", "__HashConstructor",
TypeScriptDependency.SMITHY_TYPES);
writer.addImport("ChecksumConstructor", "__ChecksumConstructor",
TypeScriptDependency.SMITHY_TYPES);
writer.write("Hash.bind(null, \"md5\")");
});
case BROWSER:
return MapUtils.of("md5", writer -> {
writer.addDependency(TypeScriptDependency.MD5_BROWSER);
writer.addImport("Md5", "Md5", TypeScriptDependency.MD5_BROWSER);
writer.write("Md5");
});
default:
return Collections.emptyMap();
}
}
private static boolean isSqs(ServiceShape service) {
return service.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse("").equals("SQS");
}
}
| 4,810 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddNimbleCustomizations.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.Map;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.model.shapes.ShapeType;
import software.amazon.smithy.model.transform.ModelTransformer;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Add Nimble customization.
*/
@SmithyInternalApi
public class AddNimbleCustomizations implements TypeScriptIntegration {
@Override
public Model preprocessModel(Model model, TypeScriptSettings settings) {
ServiceShape service = settings.getService(model);
String serviceId = service.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse("");
if (!serviceId.equals("nimble")) {
return model;
}
Map<ShapeId, ShapeType> overWriteTypeMap = MapUtils.of(
ShapeId.from("com.amazonaws.nimble#StudioComponentConfiguration"), ShapeType.STRUCTURE);
return ModelTransformer.create().changeShapeType(model, overWriteTypeMap);
}
}
| 4,811 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/JsonMemberSerVisitor.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import software.amazon.smithy.aws.traits.protocols.AwsQueryCompatibleTrait;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.model.shapes.BigDecimalShape;
import software.amazon.smithy.model.shapes.BigIntegerShape;
import software.amazon.smithy.model.shapes.BooleanShape;
import software.amazon.smithy.model.shapes.DoubleShape;
import software.amazon.smithy.model.shapes.FloatShape;
import software.amazon.smithy.model.shapes.IntegerShape;
import software.amazon.smithy.model.shapes.LongShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShortShape;
import software.amazon.smithy.model.shapes.StringShape;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.DocumentMemberSerVisitor;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator.GenerationContext;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Overrides the default implementation of BigDecimal and BigInteger shape
* serialization to throw when encountered in AWS REST-JSON based protocols.
*
* TODO: Work out support for BigDecimal and BigInteger, natively or through a library.
*/
@SmithyInternalApi
final class JsonMemberSerVisitor extends DocumentMemberSerVisitor {
private final boolean isAwsQueryCompat;
/**
* @inheritDoc
*/
JsonMemberSerVisitor(GenerationContext context, String dataSource, Format defaultTimestampFormat) {
super(context, dataSource, defaultTimestampFormat);
TypeScriptWriter writer = context.getWriter();
writer.addImport("_json", null, TypeScriptDependency.AWS_SMITHY_CLIENT);
this.isAwsQueryCompat = context.getService().hasTrait(AwsQueryCompatibleTrait.class);
this.serdeElisionEnabled = !this.isAwsQueryCompat && !context.getSettings().generateServerSdk();
if (isAwsQueryCompat) {
writer.addImport("_toStr", null, AwsDependency.AWS_SDK_CORE);
writer.addImport("_toNum", null, AwsDependency.AWS_SDK_CORE);
writer.addImport("_toBool", null, AwsDependency.AWS_SDK_CORE);
}
}
@Override
public String bigDecimalShape(BigDecimalShape shape) {
// Fail instead of losing precision through Number.
return unsupportedShape(shape);
}
@Override
public String bigIntegerShape(BigIntegerShape shape) {
// Fail instead of losing precision through Number.
return unsupportedShape(shape);
}
@Override
public String shortShape(ShortShape shape) {
String base = super.shortShape(shape);
if (isAwsQueryCompat) {
return "_toNum(" + base + ")";
}
return base;
}
@Override
public String integerShape(IntegerShape shape) {
String base = super.integerShape(shape);
if (isAwsQueryCompat) {
return "_toNum(" + base + ")";
}
return base;
}
@Override
public String longShape(LongShape shape) {
String base = super.longShape(shape);
if (isAwsQueryCompat) {
return "_toNum(" + base + ")";
}
return base;
}
@Override
public String floatShape(FloatShape shape) {
String base = super.floatShape(shape);
if (isAwsQueryCompat) {
return "_toNum(" + base + ")";
}
return base;
}
@Override
public String doubleShape(DoubleShape shape) {
String base = super.doubleShape(shape);
if (isAwsQueryCompat) {
return "_toNum(" + base + ")";
}
return base;
}
@Override
public String booleanShape(BooleanShape shape) {
String base = super.booleanShape(shape);
if (isAwsQueryCompat) {
return "_toBool(" + base + ")";
}
return base;
}
@Override
public String stringShape(StringShape shape) {
String base = super.stringShape(shape);
if (isAwsQueryCompat) {
return "_toStr(" + base + ")";
}
return base;
}
private String unsupportedShape(Shape shape) {
throw new CodegenException(String.format("Cannot serialize shape type %s on protocol, shape: %s.",
shape.getType(), shape.getId()));
}
}
| 4,812 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/StripNewEnumNames.java | /*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.node.Node;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.model.shapes.StringShape;
import software.amazon.smithy.model.traits.EnumDefinition;
import software.amazon.smithy.model.traits.EnumTrait;
import software.amazon.smithy.model.traits.Trait;
import software.amazon.smithy.model.transform.ModelTransformer;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.IoUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Strips enum names from enums that GA'd without them.
*
* A number of enums had names back-filled after GA. Since the type generated would change,
* this is backwards-incompatible. This integration ensures that clients generated
* preserve backwards-compatibility by stripping names from enums that were known to have
* launched without them.
*/
@SmithyInternalApi
public final class StripNewEnumNames implements TypeScriptIntegration {
private final Set<ShapeId> enumsToStrip;
public StripNewEnumNames() {
// Load the list of enums
Node json = Node.parse(IoUtils.readUtf8Url(getClass().getResource("enums-to-strip.json")));
Set<ShapeId> toStrip = new HashSet<>();
json.asArrayNode().ifPresent(array -> array.forEach(node -> {
node.asStringNode().ifPresent(stringNode -> {
toStrip.add(ShapeId.from(stringNode.getValue()));
});
}));
enumsToStrip = Collections.unmodifiableSet(toStrip);
}
@Override
public Model preprocessModel(Model model, TypeScriptSettings settings) {
Set<Shape> shapesToUpdate = model.shapes(StringShape.class)
.filter(shape -> enumsToStrip.contains(shape.getId()))
.flatMap(shape -> Trait.flatMapStream(shape, EnumTrait.class))
// Replace the existing enum trait with an updated version
.map(pair -> pair.getKey().toBuilder().addTrait(stripNames(pair.getValue())).build())
.collect(Collectors.toSet());
return ModelTransformer.create().replaceShapes(model, shapesToUpdate);
}
private EnumTrait stripNames(EnumTrait trait) {
// Use toBuilder to ensure that any other information (e.g. source location) is preserved.
EnumTrait.Builder builder = trait.toBuilder().clearEnums();
for (EnumDefinition definition : trait.getValues()) {
// Setting the name to null effectively removes it
builder.addEnum(definition.toBuilder().name(null).build());
}
return builder.build();
}
}
| 4,813 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddBodyChecksumGeneratorDependency.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SetUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Adds blobReader dependency if needed.
*/
@SmithyInternalApi
public class AddBodyChecksumGeneratorDependency implements TypeScriptIntegration {
private static final Set<String> SERVICE_IDS = SetUtils.of("Glacier");
@Override
public void addConfigInterfaceFields(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
if (!needsBodyChecksumGeneratorDep(settings.getService(model))) {
return;
}
writer.addImport("HttpRequest", "__HttpRequest", TypeScriptDependency.SMITHY_TYPES);
writer.writeDocs("Function that returns body checksums.\n"
+ "@internal");
writer.write("bodyChecksumGenerator?: (request: __HttpRequest, "
+ "options: { sha256: __ChecksumConstructor | __HashConstructor; "
+ "utf8Decoder: __Decoder }) => Promise<[string, string]>;\n");
}
@Override
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
LanguageTarget target
) {
if (!needsBodyChecksumGeneratorDep(settings.getService(model))) {
return Collections.emptyMap();
}
switch (target) {
case NODE:
return MapUtils.of("bodyChecksumGenerator", writer -> {
writer.addDependency(AwsDependency.BODY_CHECKSUM_GENERATOR_NODE);
writer.addImport("bodyChecksumGenerator", "bodyChecksumGenerator",
AwsDependency.BODY_CHECKSUM_GENERATOR_NODE);
writer.write("bodyChecksumGenerator");
});
case BROWSER:
return MapUtils.of("bodyChecksumGenerator", writer -> {
writer.addDependency(AwsDependency.BODY_CHECKSUM_GENERATOR_BROWSER);
writer.addImport("bodyChecksumGenerator", "bodyChecksumGenerator",
AwsDependency.BODY_CHECKSUM_GENERATOR_BROWSER);
writer.write("bodyChecksumGenerator");
});
default:
return Collections.emptyMap();
}
}
private static boolean needsBodyChecksumGeneratorDep(ServiceShape service) {
String serviceId = service.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse("");
return SERVICE_IDS.contains(serviceId);
}
}
| 4,814 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddWebsocketPlugin.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.EventStreamIndex;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SetUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Add client plugins and configs to support WebSocket streaming. Services like Transcribe Streaming requires extra
* customization.
**/
@SmithyInternalApi
public class AddWebsocketPlugin implements TypeScriptIntegration {
@Override
public List<RuntimeClientPlugin> getClientPlugins() {
return ListUtils.of(
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_WEBSOCKET.dependency,
"WebSocket", RuntimeClientPlugin.Convention.HAS_MIDDLEWARE)
.additionalPluginFunctionParamsSupplier((m, s, o) -> getPluginFunctionParams(m, s, o))
.operationPredicate((m, s, o) -> isWebsocketSupported(s) && hasEventStreamRequest(m, o))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_WEBSOCKET.dependency, "WebSocket",
RuntimeClientPlugin.Convention.HAS_CONFIG)
.servicePredicate((m, s) -> isWebsocketSupported(s))
.build()
);
}
@Override
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
LanguageTarget target
) {
ServiceShape service = settings.getService(model);
if (!isWebsocketSupported(service)) {
return Collections.emptyMap();
}
switch (target) {
case BROWSER:
return MapUtils.of(
"eventStreamPayloadHandlerProvider", writer -> {
writer.addDependency(AwsDependency.MIDDLEWARE_WEBSOCKET);
writer.addImport("eventStreamPayloadHandlerProvider", "eventStreamPayloadHandlerProvider",
AwsDependency.MIDDLEWARE_WEBSOCKET.packageName);
writer.write("eventStreamPayloadHandlerProvider");
},
"requestHandler", writer -> {
writer.addImport("FetchHttpHandler", "HttpRequestHandler",
TypeScriptDependency.AWS_SDK_FETCH_HTTP_HANDLER.packageName);
writer.addDependency(TypeScriptDependency.AWS_SDK_FETCH_HTTP_HANDLER);
writer.addImport("WebSocketFetchHandler", "WebSocketRequestHandler",
AwsDependency.MIDDLEWARE_WEBSOCKET.packageName);
writer.addDependency(AwsDependency.MIDDLEWARE_WEBSOCKET);
writer.write("new WebSocketRequestHandler(defaultConfigProvider, "
+ "new HttpRequestHandler(defaultConfigProvider))");
});
default:
return Collections.emptyMap();
}
}
private static boolean isWebsocketSupported(ServiceShape service) {
Set<String> websocketServices = SetUtils.of("Transcribe Streaming", "RekognitionStreaming");
String serviceId = service.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse("");
return websocketServices.contains(serviceId);
}
private static boolean hasEventStreamRequest(Model model, OperationShape operation) {
EventStreamIndex eventStreamIndex = EventStreamIndex.of(model);
return eventStreamIndex.getInputInfo(operation).isPresent();
}
private static Map<String, Object> getPluginFunctionParams(
Model model,
ServiceShape service,
OperationShape operation
) {
String serviceId = service.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse("");
if (serviceId.equals("Transcribe Streaming")) {
return MapUtils.of("headerPrefix", "x-amzn-transcribe-");
} else if (serviceId.equals("RekognitionStreaming")) {
return MapUtils.of("headerPrefix", "x-amz-rekognition-streaming-liveness-");
} else {
throw new CodegenException("Missing endpoint prefix for Websocket plugin of service " + serviceId);
}
}
}
| 4,815 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddHttp2Dependency.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import software.amazon.smithy.aws.traits.protocols.AwsProtocolTrait;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
@SmithyInternalApi
public class AddHttp2Dependency implements TypeScriptIntegration {
@Override
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
LanguageTarget target) {
if (!isHttp2Applicable(settings.getService(model))) {
return Collections.emptyMap();
}
switch (target) {
case NODE:
return MapUtils.of("requestHandler", writer -> {
writer.addDependency(TypeScriptDependency.AWS_SDK_NODE_HTTP_HANDLER);
writer.addImport("NodeHttp2Handler", "RequestHandler",
TypeScriptDependency.AWS_SDK_NODE_HTTP_HANDLER);
writer.openBlock("new RequestHandler(async () => ({", "}))", () -> {
writer.write("...await defaultConfigProvider(),");
// TODO: remove this when root cause of #3809 is found
writer.write("disableConcurrentStreams: true");
});
});
default:
return Collections.emptyMap();
}
}
private static boolean isHttp2Applicable(ServiceShape service) {
List<String> eventStreamFlag = service.getTrait(AwsProtocolTrait.class)
.map(AwsProtocolTrait::getEventStreamHttp).orElse(ListUtils.of());
return eventStreamFlag.contains("h2");
}
}
| 4,816 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddUserAgentDependency.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isAwsService;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Add client plubins and configs to support injecting user agent.
*/
@SmithyInternalApi
public class AddUserAgentDependency implements TypeScriptIntegration {
@Override
public List<RuntimeClientPlugin> getClientPlugins() {
return ListUtils.of(
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_USER_AGENT.dependency, "UserAgent").build());
}
@Override
public void addConfigInterfaceFields(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
writer.addImport("Provider", "Provider", TypeScriptDependency.SMITHY_TYPES);
writer.addImport("UserAgent", "__UserAgent", TypeScriptDependency.SMITHY_TYPES);
writer.writeDocs("The provider populating default tracking information to be sent with `user-agent`, "
+ "`x-amz-user-agent` header\n@internal");
writer.write("defaultUserAgentProvider?: Provider<__UserAgent>;\n");
}
@Override
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
LanguageTarget target
) {
switch (target) {
case NODE:
return MapUtils.of(
"defaultUserAgentProvider", writer -> {
writer.addDependency(AwsDependency.AWS_SDK_UTIL_USER_AGENT_NODE.dependency);
writer.addImport("defaultUserAgent", "defaultUserAgent",
AwsDependency.AWS_SDK_UTIL_USER_AGENT_NODE.packageName);
writer.addIgnoredDefaultImport("packageInfo", "./package.json",
"package.json will be imported from dist folders");
writeDefaultUserAgentProvider(writer, settings, model);
}
);
case BROWSER:
return MapUtils.of(
"defaultUserAgentProvider", writer -> {
writer.addDependency(AwsDependency.AWS_SDK_UTIL_USER_AGENT_BROWSER.dependency);
writer.addImport("defaultUserAgent", "defaultUserAgent",
AwsDependency.AWS_SDK_UTIL_USER_AGENT_BROWSER.packageName);
writer.addIgnoredDefaultImport("packageInfo", "./package.json",
"package.json will be imported from dist folders");
writeDefaultUserAgentProvider(writer, settings, model);
}
);
default:
return Collections.emptyMap();
}
}
private void writeDefaultUserAgentProvider(TypeScriptWriter writer, TypeScriptSettings settings, Model model) {
writer.write("defaultUserAgent({"
// serviceId is optional in defaultUserAgent. serviceId exists only for AWS services
+ (isAwsService(settings, model) ? "serviceId: clientSharedValues.serviceId, " : "")
+ "clientVersion: packageInfo.version})");
}
}
| 4,817 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AwsTraitsUtils.java | /*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.aws.traits.auth.SigV4Trait;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.traits.HttpBearerAuthTrait;
import software.amazon.smithy.rulesengine.traits.EndpointRuleSetTrait;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Utility methods related to AWS traits.
*/
@SmithyInternalApi
public final class AwsTraitsUtils {
private AwsTraitsUtils() {}
static boolean isAwsService(TypeScriptSettings settings, Model model) {
return isAwsService(settings.getService(model));
}
public static boolean isAwsService(ServiceShape serviceShape) {
return serviceShape.hasTrait(ServiceTrait.class);
}
static boolean isSigV4Service(TypeScriptSettings settings, Model model) {
return isSigV4Service(settings.getService(model));
}
public static boolean isSigV4Service(ServiceShape serviceShape) {
return serviceShape.hasTrait(SigV4Trait.class);
}
static boolean isEndpointsV2Service(ServiceShape serviceShape) {
return serviceShape.hasTrait(EndpointRuleSetTrait.class);
}
static boolean isHttpBearerAuthService(ServiceShape serviceShape) {
return serviceShape.hasTrait(HttpBearerAuthTrait.class);
}
}
| 4,818 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddEndpointDiscoveryPlugin.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import software.amazon.smithy.aws.traits.clientendpointdiscovery.ClientDiscoveredEndpointTrait;
import software.amazon.smithy.aws.traits.clientendpointdiscovery.ClientEndpointDiscoveryIdTrait;
import software.amazon.smithy.aws.traits.clientendpointdiscovery.ClientEndpointDiscoveryTrait;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.codegen.core.Symbol;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.OperationIndex;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Adds runtime plugins which handle endpoint discovery logic.
*/
@SmithyInternalApi
public class AddEndpointDiscoveryPlugin implements TypeScriptIntegration {
@Override
public void addConfigInterfaceFields(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
ServiceShape service = settings.getService(model);
if (hasClientEndpointDiscovery(service)) {
// Add import for endpoint discovery command here, as getClientPlugins doesn't have access to writer.
addEndpointDiscoveryCommandImport(model, symbolProvider, service, writer);
writer.addImport("Provider", "__Provider", TypeScriptDependency.SMITHY_TYPES);
writer.writeDocs("The provider which populates default for endpointDiscoveryEnabled configuration,"
+ " if it's\nnot passed during client creation.\n@internal")
.write("endpointDiscoveryEnabledProvider?: __Provider<boolean | undefined>;\n");
}
}
@Override
public List<RuntimeClientPlugin> getClientPlugins() {
return ListUtils.of(
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_ENDPOINT_DISCOVERY.dependency,
"EndpointDiscovery", RuntimeClientPlugin.Convention.HAS_CONFIG)
.additionalResolveFunctionParamsSupplier((m, s, o) -> new HashMap<String, Object>() {{
put("endpointDiscoveryCommandCtor",
Symbol.builder().name(getClientDiscoveryCommand(s)).build());
}})
.servicePredicate((m, s) -> hasClientEndpointDiscovery(s))
.build(),
// ToDo: Pass the map of identifiers to the EndpointDiscovery plugin.
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_ENDPOINT_DISCOVERY.dependency,
"EndpointDiscovery", RuntimeClientPlugin.Convention.HAS_MIDDLEWARE)
.additionalPluginFunctionParamsSupplier((m, s, o) -> getPluginFunctionParams(m, s, o))
.operationPredicate((m, s, o) ->
isClientDiscoveredEndpointRequired(s, o) || isClientDiscoveredEndpointOptional(s, o)
).build()
);
}
@Override
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
LanguageTarget target
) {
ServiceShape service = settings.getService(model);
if (!hasClientEndpointDiscovery(service)) {
return Collections.emptyMap();
}
switch (target) {
case BROWSER:
return MapUtils.of(
"endpointDiscoveryEnabledProvider", writer -> {
writer.write("(() => Promise.resolve(undefined))");
}
);
case NODE:
return MapUtils.of(
"endpointDiscoveryEnabledProvider", writer -> {
writer.addDependency(AwsDependency.MIDDLEWARE_ENDPOINT_DISCOVERY);
writer.addImport("NODE_ENDPOINT_DISCOVERY_CONFIG_OPTIONS",
"NODE_ENDPOINT_DISCOVERY_CONFIG_OPTIONS",
AwsDependency.MIDDLEWARE_ENDPOINT_DISCOVERY.packageName);
writer.write("loadNodeConfig(NODE_ENDPOINT_DISCOVERY_CONFIG_OPTIONS)");
}
);
default:
return Collections.emptyMap();
}
}
private void addEndpointDiscoveryCommandImport(
Model model,
SymbolProvider symbolProvider,
ServiceShape service,
TypeScriptWriter writer
) {
if (!hasClientEndpointDiscovery(service)) {
throw new CodegenException(
"EndpointDiscovery command import called for service without endpoint discovery"
);
}
ShapeId operationShapeId = service.getTrait(ClientEndpointDiscoveryTrait.class).orElse(null).getOperation();
OperationShape operation = model.expectShape(operationShapeId, OperationShape.class);
writer.addUseImports(symbolProvider.toSymbol(operation));
}
private static boolean hasClientEndpointDiscovery(ServiceShape service) {
if (service.hasTrait(ClientEndpointDiscoveryTrait.class)) {
return true;
}
return false;
}
private static boolean isClientDiscoveredEndpointRequired(ServiceShape service, OperationShape operation) {
if (hasClientEndpointDiscovery(service) && operation.hasTrait(ClientDiscoveredEndpointTrait.class)) {
return operation.getTrait(ClientDiscoveredEndpointTrait.class).orElse(null).isRequired();
}
return false;
}
private static boolean isClientDiscoveredEndpointOptional(ServiceShape service, OperationShape operation) {
if (!hasClientEndpointDiscovery(service) && operation.hasTrait(ClientDiscoveredEndpointTrait.class)) {
return !operation.getTrait(ClientDiscoveredEndpointTrait.class).orElse(null).isRequired();
}
return false;
}
private static String getClientDiscoveryCommand(ServiceShape service) {
if (!hasClientEndpointDiscovery(service)) {
throw new CodegenException(
"EndpointDiscovery command discovery attempt for service without endpoint discovery"
);
}
return service.getTrait(ClientEndpointDiscoveryTrait.class).orElse(null).getOperation().getName() + "Command";
}
private static Map<String, Object> getPluginFunctionParams(
Model model,
ServiceShape serviceShape,
OperationShape operationShape
) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("clientStack", Symbol.builder().name("clientStack").build());
params.put("options", Symbol.builder().name("options").build());
params.put("isDiscoveredEndpointRequired", isClientDiscoveredEndpointRequired(
serviceShape, operationShape));
OperationIndex operationIndex = OperationIndex.of(model);
List membersWithClientEndpointDiscoveryId = getMembersWithClientEndpointDiscoveryId(
operationIndex.getInput(operationShape)
);
if (!membersWithClientEndpointDiscoveryId.isEmpty()) {
params.put("identifiers", getClientEndpointDiscoveryIdentifiers(membersWithClientEndpointDiscoveryId));
}
return params;
}
private static String getClientEndpointDiscoveryIdentifiers(
List<MemberShape> membersWithClientEndpointDiscoveryId
) {
return membersWithClientEndpointDiscoveryId.stream()
.map(member -> member.getMemberName() + ": input." + member.getMemberName())
.collect(Collectors.joining(", ", "{", "}"));
}
private static List<MemberShape> getMembersWithClientEndpointDiscoveryId(
Optional<StructureShape> optionalShape
) {
List<MemberShape> membersWithClientEndpointDiscoveryId = new ArrayList<>();
if (optionalShape.isPresent()) {
StructureShape structureShape = optionalShape.get();
for (MemberShape member : structureShape.getAllMembers().values()) {
if (member.getTrait(ClientEndpointDiscoveryIdTrait.class).isPresent()) {
membersWithClientEndpointDiscoveryId.add(member);
}
}
}
return membersWithClientEndpointDiscoveryId;
}
}
| 4,819 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/DocumentClientPaginationGenerator.java | /*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.nio.file.Paths;
import java.util.Optional;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.codegen.core.Symbol;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.PaginatedIndex;
import software.amazon.smithy.model.knowledge.PaginationInfo;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.utils.SmithyInternalApi;
@SmithyInternalApi
final class DocumentClientPaginationGenerator implements Runnable {
static final String PAGINATION_FOLDER = "pagination";
private final TypeScriptWriter writer;
private final PaginationInfo paginatedInfo;
private final String operationTypeName;
private final String inputTypeName;
private final String outputTypeName;
private final String operationName;
private final String methodName;
private final String paginationType;
DocumentClientPaginationGenerator(
Model model,
ServiceShape service,
OperationShape operation,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
this.writer = writer;
Symbol operationSymbol = symbolProvider.toSymbol(operation);
Symbol inputSymbol = symbolProvider.toSymbol(operation).expectProperty("inputType", Symbol.class);
Symbol outputSymbol = symbolProvider.toSymbol(operation).expectProperty("outputType", Symbol.class);
this.operationTypeName = DocumentClientUtils.getModifiedName(operationSymbol.getName());
this.inputTypeName = DocumentClientUtils.getModifiedName(inputSymbol.getName());
this.outputTypeName = DocumentClientUtils.getModifiedName(outputSymbol.getName());
// e.g. listObjects
this.operationName = operationTypeName.replace("Command", "");
this.methodName = Character.toLowerCase(operationName.charAt(0)) + operationName.substring(1);
this.paginationType = DocumentClientUtils.CLIENT_FULL_NAME + "PaginationConfiguration";
PaginatedIndex paginatedIndex = PaginatedIndex.of(model);
Optional<PaginationInfo> paginationInfo = paginatedIndex.getPaginationInfo(service, operation);
this.paginatedInfo = paginationInfo.orElseThrow(() -> {
return new CodegenException("Expected Paginator to have pagination information.");
});
}
@Override
public void run() {
// Import Service Types
String commandFileLocation = Paths.get(".", DocumentClientUtils.CLIENT_COMMANDS_FOLDER,
DocumentClientUtils.getModifiedName(operationTypeName)).toString();
writer.addImport(operationTypeName, operationTypeName, commandFileLocation);
writer.addImport(inputTypeName, inputTypeName, commandFileLocation);
writer.addImport(outputTypeName, outputTypeName, commandFileLocation);
writer.addImport(
DocumentClientUtils.CLIENT_NAME,
DocumentClientUtils.CLIENT_NAME,
Paths.get(".", DocumentClientUtils.CLIENT_NAME).toString());
writer.addImport(
DocumentClientUtils.CLIENT_FULL_NAME,
DocumentClientUtils.CLIENT_FULL_NAME,
Paths.get(".", DocumentClientUtils.CLIENT_FULL_NAME).toString());
// Import Pagination types
writer.addImport("Paginator", "Paginator", TypeScriptDependency.SMITHY_TYPES);
writer.addImport(paginationType, paginationType,
Paths.get(".", getInterfaceFilelocation().replace(".ts", "")).toString());
writer.writeDocs("@public");
writer.write("export { Paginator }");
writeCommandRequest();
writeMethodRequest();
writePager();
}
static String getOutputFilelocation(OperationShape operation) {
return String.format("%s%s/%s.ts", DocumentClientUtils.DOC_CLIENT_PREFIX,
DocumentClientPaginationGenerator.PAGINATION_FOLDER,
DocumentClientUtils.getModifiedName(operation.getId().getName()) + "Paginator");
}
static String getInterfaceFilelocation() {
return String.format("%s%s/%s.ts", DocumentClientUtils.DOC_CLIENT_PREFIX,
DocumentClientPaginationGenerator.PAGINATION_FOLDER, "Interfaces");
}
static void generateServicePaginationInterfaces(TypeScriptWriter writer) {
writer.addImport("PaginationConfiguration", "PaginationConfiguration", TypeScriptDependency.SMITHY_TYPES);
writer.addImport(
DocumentClientUtils.CLIENT_NAME,
DocumentClientUtils.CLIENT_NAME,
Paths.get(".", DocumentClientUtils.CLIENT_NAME).toString());
writer.addImport(
DocumentClientUtils.CLIENT_FULL_NAME,
DocumentClientUtils.CLIENT_FULL_NAME,
Paths.get(".", DocumentClientUtils.CLIENT_FULL_NAME).toString());
writer.writeDocs("@public");
writer.write("export { PaginationConfiguration };");
writer.write("");
writer.writeDocs("@public");
writer.openBlock("export interface $LPaginationConfiguration extends PaginationConfiguration {",
"}", DocumentClientUtils.CLIENT_FULL_NAME, () -> {
writer.write("client: $L | $L;", DocumentClientUtils.CLIENT_FULL_NAME, DocumentClientUtils.CLIENT_NAME);
});
}
private String destructurePath(String path) {
return "." + path.replace(".", "!.");
}
private void writePager() {
String inputTokenName = paginatedInfo.getPaginatedTrait().getInputToken().get();
String outputTokenName = paginatedInfo.getPaginatedTrait().getOutputToken().get();
writer.writeDocs("@public\n\n"
+ String.format("@param %s - {@link %s}%n", inputTypeName, inputTypeName)
+ String.format("@returns {@link %s}%n", outputTypeName)
);
writer.openBlock(
"export async function* paginate$L(config: $L, input: $L, ...additionalArguments: any): Paginator<$L>{",
"}", operationName, paginationType, inputTypeName, outputTypeName, () -> {
String destructuredInputTokenName = destructurePath(inputTokenName);
writer.write("// ToDo: replace with actual type instead of typeof input$L", destructuredInputTokenName);
writer.write("let token: typeof input$L | undefined = config.startingToken || undefined;",
destructuredInputTokenName);
writer.write("let hasNext = true;");
writer.write("let page: $L;", outputTypeName);
writer.openBlock("while (hasNext) {", "}", () -> {
writer.write("input$L = token;", destructuredInputTokenName);
if (paginatedInfo.getPageSizeMember().isPresent()) {
String pageSize = paginatedInfo.getPageSizeMember().get().getMemberName();
writer.write("input[$S] = config.pageSize;", pageSize);
}
writer.openBlock("if (config.client instanceof $L) {", "}", DocumentClientUtils.CLIENT_FULL_NAME,
() -> {
writer.write("page = await makePagedRequest(config.client, input, ...additionalArguments);");
}
);
writer.openBlock("else if (config.client instanceof $L) {", "}", DocumentClientUtils.CLIENT_NAME,
() -> {
writer.write(
"page = await makePagedClientRequest(config.client, input, ...additionalArguments);");
}
);
writer.openBlock("else {", "}", () -> {
writer.write("throw new Error(\"Invalid client, expected $L | $L\");",
DocumentClientUtils.CLIENT_FULL_NAME, DocumentClientUtils.CLIENT_NAME);
});
writer.write("yield page;");
writer.write("token = page$L;", destructurePath(outputTokenName));
writer.write("hasNext = !!(token);");
});
writer.write("// @ts-ignore");
writer.write("return undefined;");
});
}
/**
* Paginated command that calls client.method({...}) under the hood. This is meant for server side environments and
* exposes the entire service.
*/
private void writeMethodRequest() {
writer.writeDocs("@internal");
writer.openBlock(
"const makePagedRequest = async (client: $L, input: $L, ...args: any): Promise<$L> => {",
"}", DocumentClientUtils.CLIENT_FULL_NAME, inputTypeName,
outputTypeName, () -> {
writer.write("// @ts-ignore");
writer.write("return await client.$L(input, ...args);", methodName);
});
}
/**
* Paginated command that calls CommandClient().send({...}) under the hood. This is meant for client side (browser)
* environments and does not generally expose the entire service.
*/
private void writeCommandRequest() {
writer.writeDocs("@internal");
writer.openBlock(
"const makePagedClientRequest = async (client: $L, input: $L, ...args: any): Promise<$L> => {",
"}", DocumentClientUtils.CLIENT_NAME, inputTypeName,
outputTypeName, () -> {
writer.write("// @ts-ignore");
writer.write("return await client.send(new $L(input), ...args);", operationTypeName);
});
}
}
| 4,820 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/DocumentClientCommandGenerator.java | /*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.codegen.core.Symbol;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.OperationIndex;
import software.amazon.smithy.model.shapes.CollectionShape;
import software.amazon.smithy.model.shapes.MapShape;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.traits.IdempotencyTokenTrait;
import software.amazon.smithy.typescript.codegen.ApplicationProtocol;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.utils.SmithyInternalApi;
@SmithyInternalApi
final class DocumentClientCommandGenerator implements Runnable {
static final String COMMAND_PROPERTIES_SECTION = "command_properties";
static final String COMMAND_BODY_EXTRA_SECTION = "command_body_extra";
static final String COMMAND_CONSTRUCTOR_SECTION = "command_constructor";
static final String COMMAND_INPUT_KEYNODES = "inputKeyNodes";
static final String COMMAND_OUTPUT_KEYNODES = "outputKeyNodes";
private final Model model;
private final OperationShape operation;
private final SymbolProvider symbolProvider;
private final TypeScriptWriter writer;
private final Symbol symbol;
private final OperationIndex operationIndex;
private final String originalInputTypeName;
private final String inputTypeName;
private final List<MemberShape> inputMembersWithAttr;
private final String originalOutputTypeName;
private final String outputTypeName;
private final List<MemberShape> outputMembersWithAttr;
private final String clientCommandClassName;
private final String clientCommandLocalName;
DocumentClientCommandGenerator(
TypeScriptSettings settings,
Model model,
OperationShape operation,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
this.model = model;
settings.getService(model);
this.operation = operation;
this.symbolProvider = symbolProvider;
this.writer = writer;
symbol = symbolProvider.toSymbol(operation);
operationIndex = OperationIndex.of(model);
String inputType = symbol.expectProperty("inputType", Symbol.class).getName();
originalInputTypeName = inputType;
inputTypeName = DocumentClientUtils.getModifiedName(
inputType
);
inputMembersWithAttr = getStructureMembersWithAttr(operationIndex.getInput(operation));
String outputType = symbol.expectProperty("outputType", Symbol.class).getName();
originalOutputTypeName = outputType;
outputTypeName = DocumentClientUtils.getModifiedName(
outputType
);
outputMembersWithAttr = getStructureMembersWithAttr(operationIndex.getOutput(operation));
clientCommandClassName = symbol.getName();
clientCommandLocalName = "__" + clientCommandClassName;
}
@Override
public void run() {
String servicePath = Paths.get(".", DocumentClientUtils.CLIENT_NAME).toString();
String configType = DocumentClientUtils.CLIENT_CONFIG_NAME;
// Add required imports.
writer.addImport(configType, configType, servicePath);
writer.addImport(
"DynamoDBDocumentClientCommand",
"DynamoDBDocumentClientCommand",
"./baseCommand/DynamoDBDocumentClientCommand"
);
writer.addImport("Command", "$Command", TypeScriptDependency.AWS_SMITHY_CLIENT);
writer.writeDocs("@public");
writer.write("export { DynamoDBDocumentClientCommand, $$Command };");
generateInputAndOutputTypes();
String ioTypes = String.join(", ", new String[]{
inputTypeName,
outputTypeName,
"__" + originalInputTypeName,
"__" + originalOutputTypeName
});
String name = DocumentClientUtils.getModifiedName(symbol.getName());
writer.writeDocs(DocumentClientUtils.getCommandDocs(symbol.getName())
+ "\n\n@public"
);
writer.openBlock(
"export class $L extends DynamoDBDocumentClientCommand<" + ioTypes + ", $L> {",
"}",
name,
configType,
() -> {
// Section for adding custom command properties.
writer.pushState(COMMAND_PROPERTIES_SECTION);
writer.openBlock("protected readonly $L = {", "};", COMMAND_INPUT_KEYNODES, () -> {
writeKeyNodes(inputMembersWithAttr);
});
writer.openBlock("protected readonly $L = {", "};", COMMAND_OUTPUT_KEYNODES, () -> {
writeKeyNodes(outputMembersWithAttr);
});
writer.popState();
writer.write("");
writer.write("protected readonly clientCommand: $L;", clientCommandLocalName);
writer.write(
"public readonly middlewareStack: MiddlewareStack<$L>;",
inputTypeName + " | __" + originalInputTypeName
+ ", \n" + outputTypeName + " | __" + originalOutputTypeName
);
writer.write("");
generateCommandConstructor();
writer.write("");
generateCommandMiddlewareResolver(configType);
// Hook for adding more methods to the command.
writer.pushState(COMMAND_BODY_EXTRA_SECTION).popState();
}
);
}
private void generateCommandConstructor() {
writer.openBlock("constructor(readonly input: $L) {", "}", inputTypeName, () -> {
// The constructor can be intercepted and changed.
writer.pushState(COMMAND_CONSTRUCTOR_SECTION)
.write("super();")
.write("this.clientCommand = new $L(this.input as any);", clientCommandLocalName)
.write("this.middlewareStack = this.clientCommand.middlewareStack;")
.popState();
});
}
private void generateCommandMiddlewareResolver(String configType) {
writer.writeDocs("@internal");
String serviceInputTypes = "ServiceInputTypes";
String serviceOutputTypes = "ServiceOutputTypes";
String handler = "Handler";
String middlewareStack = "MiddlewareStack";
String servicePath = Paths.get(".", DocumentClientUtils.CLIENT_NAME).toString();
writer.addImport(serviceInputTypes, serviceInputTypes, servicePath);
writer.addImport(serviceOutputTypes, serviceOutputTypes, servicePath);
writer.addImport(handler, handler, TypeScriptDependency.SMITHY_TYPES);
writer.addImport(middlewareStack, middlewareStack, TypeScriptDependency.SMITHY_TYPES);
writer.write("resolveMiddleware(")
.indent()
.write("clientStack: $L<$L, $L>,", middlewareStack, serviceInputTypes, serviceOutputTypes)
.write("configuration: $L,", configType)
.write("options?: $T", ApplicationProtocol.createDefaultHttpApplicationProtocol().getOptionsType())
.dedent();
writer.openBlock("): $L<$L, $L> {", "}", handler, inputTypeName, outputTypeName, () -> {
writer.addImport(clientCommandClassName, clientCommandLocalName, "@aws-sdk/client-dynamodb");
String commandVarName = "this.clientCommand";
// marshall middlewares
writer.openBlock("this.addMarshallingMiddleware(", ");", () -> {
writer.write("configuration");
});
writer.write("const stack = clientStack.concat(this.middlewareStack as typeof clientStack);");
String handlerVarName = "handler";
writer.write("const $L = $L.resolveMiddleware(stack, configuration, options);",
handlerVarName, commandVarName);
writer.write("");
if (outputMembersWithAttr.isEmpty()) {
writer.write("return $L;", handlerVarName);
} else {
writer.write("return async () => handler($L)", commandVarName);
}
});
}
private void writeKeyNodes(List<MemberShape> membersWithAttr) {
for (MemberShape member: membersWithAttr) {
writer.openBlock("'$L': ", ",", symbolProvider.toMemberName(member), () -> {
writeKeyNode(member);
});
}
}
private void writeKeyNode(MemberShape member) {
Shape memberTarget = model.expectShape(member.getTarget());
if (memberTarget instanceof CollectionShape) {
MemberShape collectionMember = ((CollectionShape) memberTarget).getMember();
Shape collectionMemberTarget = model.expectShape(collectionMember.getTarget());
if (collectionMemberTarget.isUnionShape()
&& symbolProvider.toSymbol(collectionMemberTarget).getName().equals("AttributeValue")) {
writer.addImport("ALL_MEMBERS", null, "./commands/utils");
writer.write("ALL_MEMBERS // set/list of AttributeValue");
return;
}
writer.openBlock("{", "}", () -> {
writer.write("'*':");
writeKeyNode(collectionMember);
});
} else if (memberTarget.isUnionShape()) {
if (symbolProvider.toSymbol(memberTarget).getName().equals("AttributeValue")) {
writer.addImport("SELF", null, "./commands/utils");
writer.write("SELF");
return;
} else {
// An AttributeValue inside Union is not present as of Q1 2021, and is less
// likely to appear in future. Writing Omit for it is not straightforward, skipping.
throw new CodegenException(String.format(
"AttributeValue inside Union is not supported, attempted for %s", memberTarget.getType()
));
}
} else if (memberTarget.isMapShape()) {
MemberShape mapMember = ((MapShape) memberTarget).getValue();
Shape mapMemberTarget = model.expectShape(mapMember.getTarget());
if (mapMemberTarget.isUnionShape()
&& symbolProvider.toSymbol(mapMemberTarget).getName().equals("AttributeValue")) {
writer.addImport("ALL_VALUES", null, "./commands/utils");
writer.write("ALL_VALUES // map with AttributeValue");
return;
} else {
writer.openBlock("{", "}", () -> {
writer.write("'*':");
writeKeyNode(mapMember);
});
}
} else if (memberTarget.isStructureShape()) {
writeStructureKeyNode((StructureShape) memberTarget);
}
}
private void writeStructureKeyNode(StructureShape structureTarget) {
List<MemberShape> membersWithAttr = getStructureMembersWithAttr(Optional.of(structureTarget));
writer.openBlock("{", "}", () -> {
for (MemberShape member: membersWithAttr) {
writer.openBlock("'$L': ", ",", symbolProvider.toMemberName(member), () -> {
writeKeyNode(member);
});
}
});
}
private void generateInputAndOutputTypes() {
writer.write("");
writeType(inputTypeName, originalInputTypeName, operationIndex.getInput(operation), inputMembersWithAttr);
writer.write("");
writeType(outputTypeName, originalOutputTypeName, operationIndex.getOutput(operation), outputMembersWithAttr);
writer.write("");
}
private List<MemberShape> getStructureMembersWithAttr(Optional<StructureShape> optionalShape) {
List<MemberShape> membersWithAttr = new ArrayList<>();
if (DocumentClientUtils.containsAttributeValue(model, symbolProvider, optionalShape)) {
StructureShape shape = optionalShape.get();
for (MemberShape member : shape.getAllMembers().values()) {
if (DocumentClientUtils.containsAttributeValue(model, symbolProvider, member, new HashSet<String>())) {
membersWithAttr.add(member);
}
}
}
return membersWithAttr;
}
private void writeType(
String typeName,
String originalTypeName,
Optional<StructureShape> optionalShape,
List<MemberShape> membersWithAttr
) {
writer.writeDocs("@public");
if (optionalShape.isPresent()) {
writer.addImport(originalTypeName, "__" + originalTypeName, "@aws-sdk/client-dynamodb");
if (membersWithAttr.isEmpty()) {
writer.write("export type $L = __$L;", typeName, originalTypeName);
} else {
String memberUnionToOmit = membersWithAttr.stream()
.map(member -> "'" + symbolProvider.toMemberName(member) + "'")
.collect(Collectors.joining(" | "));
writer.openBlock("export type $L = Omit<__$L, $L> & {", "};", typeName,
originalTypeName, memberUnionToOmit, () -> {
for (MemberShape member: membersWithAttr) {
writeStructureMemberOmitType(member);
}
}
);
}
} else {
// If the input is non-existent, then use an empty object.
writer.write("export type $L = {}", typeName);
}
}
private void writeStructureOmitType(StructureShape structureTarget) {
List<MemberShape> membersWithAttr = getStructureMembersWithAttr(Optional.of(structureTarget));
String memberUnionToOmit = membersWithAttr.stream()
.map(memberWithAttr -> "'" + symbolProvider.toMemberName(memberWithAttr) + "'")
.collect(Collectors.joining(" | "));
String typeNameToOmit = symbolProvider.toSymbol(structureTarget).getName();
writer.addImport(typeNameToOmit, typeNameToOmit, "@aws-sdk/client-dynamodb");
writer.openBlock("Omit<$L, $L> & {", "}", typeNameToOmit,
memberUnionToOmit, () -> {
for (MemberShape memberWithAttr: membersWithAttr) {
writeStructureMemberOmitType(memberWithAttr);
}
});
}
private void writeStructureMemberOmitType(MemberShape member) {
String optionalSuffix = isRequiredMember(member) ? "" : "?";
writer.openBlock("${L}${L}: ", ";", symbolProvider.toMemberName(member),
optionalSuffix, () -> {
writeMemberOmitType(member);
});
}
private void writeMemberOmitType(MemberShape member) {
Shape memberTarget = model.expectShape(member.getTarget());
if (memberTarget.isStructureShape()) {
writeStructureOmitType((StructureShape) memberTarget);
} else if (memberTarget.isUnionShape()) {
if (symbolProvider.toSymbol(memberTarget).getName().equals("AttributeValue")) {
writeNativeAttributeValue();
} else {
// An AttributeValue inside Union is not present as of Q1 2021, and is less
// likely to appear in future. Writing Omit for it is not straightforward, skipping.
throw new CodegenException(String.format(
"AttributeValue inside Union is not supported, attempted for %s", memberTarget.getType()
));
}
} else if (memberTarget.isMapShape()) {
MemberShape mapMember = ((MapShape) memberTarget).getValue();
writer.openBlock("Record<string, ", ">", () -> {
writeMemberOmitType(mapMember);
});
} else if (memberTarget instanceof CollectionShape) {
MemberShape collectionMember = ((CollectionShape) memberTarget).getMember();
writer.openBlock("(", ")[]", () -> {
writeMemberOmitType(collectionMember);
});
}
String typeSuffix = isRequiredMember(member) ? " | undefined" : "";
writer.write("${L}", typeSuffix);
}
private void writeNativeAttributeValue() {
String nativeAttributeValue = "NativeAttributeValue";
writer.addImport(nativeAttributeValue, nativeAttributeValue, "@aws-sdk/util-dynamodb");
writer.write(nativeAttributeValue);
}
/**
* Identifies if a member should be required on the generated interface.
*
* @param member The member being generated for.
* @return If the interface member should be treated as required.
*
* @see <a href="https://smithy.io/2.0/spec/behavior-traits.html#smithy-api-idempotencytoken-trait">Smithy idempotencyToken trait.</a>
*/
private boolean isRequiredMember(MemberShape member) {
return member.isRequired() && !member.hasTrait(IdempotencyTokenTrait.class);
}
}
| 4,821 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/EndpointGenerator.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.aws.traits.auth.SigV4Trait;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.model.node.ArrayNode;
import software.amazon.smithy.model.node.Node;
import software.amazon.smithy.model.node.ObjectNode;
import software.amazon.smithy.model.node.StringNode;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.utils.IoUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Writes out a file that resolves endpoints using endpoints.json, but the
* created resolver resolves endpoints for a single service.
*/
@SmithyInternalApi
final class EndpointGenerator implements Runnable {
private static final int VERSION = 3;
private final TypeScriptWriter writer;
private final ObjectNode endpointData;
private final ServiceTrait serviceTrait;
private final String endpointPrefix;
private final String baseSigningService;
private final Map<String, Partition> partitions = new TreeMap<>();
private final Map<String, ObjectNode> endpoints = new TreeMap<>();
EndpointGenerator(ServiceShape service, TypeScriptWriter writer) {
this.writer = writer;
serviceTrait = service.getTrait(ServiceTrait.class)
.orElseThrow(() -> new CodegenException("No service trait found on " + service.getId()));
endpointPrefix = serviceTrait.getEndpointPrefix();
baseSigningService = service.getTrait(SigV4Trait.class).map(SigV4Trait::getName)
.orElse(serviceTrait.getArnNamespace());
endpointData = Node.parse(IoUtils.readUtf8Resource(getClass(), "endpoints.json")).expectObjectNode();
validateVersion();
loadPartitions();
loadServiceEndpoints();
}
private void validateVersion() {
int version = endpointData.expectNumberMember("version").getValue().intValue();
if (version != VERSION) {
throw new CodegenException("Invalid endpoints.json version. Expected version 3, found " + version);
}
}
private void loadPartitions() {
List<ObjectNode> partitionObjects = endpointData
.expectArrayMember("partitions")
.getElementsAs(Node::expectObjectNode);
for (ObjectNode partition : partitionObjects) {
String partitionName = partition.expectStringMember("partition").getValue();
partitions.put(partitionName, new Partition(partition, partitionName));
}
}
private void loadServiceEndpoints() {
for (Partition partition : partitions.values()) {
String dnsSuffix = partition.dnsSuffix;
ObjectNode serviceData = partition.getService();
ObjectNode endpointMap = serviceData.getObjectMember("endpoints").orElse(Node.objectNode());
for (Map.Entry<String, Node> entry : endpointMap.getStringMap().entrySet()) {
ObjectNode config = entry.getValue().expectObjectNode();
if (!config.containsMember("deprecated")
&& (config.containsMember("hostname") || config.containsMember("variants"))) {
String region = entry.getKey();
String hostname = config.getStringMemberOrDefault("hostname", partition.hostnameTemplate);
String resolvedHostname = getResolvedHostname(hostname, endpointPrefix, region);
ArrayNode variants = getServiceVariants(
config.getArrayMember("variants").orElse(ArrayNode.fromNodes()),
resolvedHostname,
dnsSuffix);
if (config.containsMember("hostname")) {
// Populate default variant only if endpoint entry contains hostname
String defaultHostname = getResolvedHostnameWithDnsSuffix(resolvedHostname, dnsSuffix);
ArrayNode defaultVariant = ArrayNode.fromNodes(getDefaultVariant(defaultHostname));
variants = defaultVariant.merge(variants);
}
endpoints.put(region,
config
.withMember("hostname", resolvedHostname)
.withMember("variants", variants));
}
}
}
}
private ArrayNode getServiceVariants(ArrayNode variants, String defaultHostname, String defaultDnsSuffix) {
List<Node> serviceVariants = new ArrayList<Node>();
variants.forEach(variant -> {
ObjectNode variantNode = variant.expectObjectNode();
if (!variantNode.containsMember("hostname") && !variantNode.containsMember("dnsSuffix")) {
// Skip the empty variant which just contains tags.
return;
}
String hostname = variantNode.getStringMemberOrDefault("hostname", defaultHostname);
String dnsSuffix = variantNode.getStringMemberOrDefault("dnsSuffix", defaultDnsSuffix);
String resolvedHostname = getResolvedHostnameWithDnsSuffix(
getResolvedHostname(hostname, endpointPrefix),
dnsSuffix
);
serviceVariants.add(variantNode.withMember("hostname", resolvedHostname).withoutMember("dnsSuffix"));
});
return ArrayNode.fromNodes(serviceVariants);
}
@Override
public void run() {
writeRegionHash();
writePartitionHash();
writeEndpointProviderFunction();
}
private void writeRegionHash() {
writer.addImport("RegionHash", "RegionHash", TypeScriptDependency.CONFIG_RESOLVER);
writer.openBlock("const regionHash: RegionHash = {", "};", () -> {
for (Map.Entry<String, ObjectNode> entry : endpoints.entrySet()) {
writeEndpointSpecificResolver(entry.getKey(), entry.getValue());
}
});
writer.write("");
}
private void writePartitionHash() {
writer.addImport("PartitionHash", "PartitionHash", TypeScriptDependency.CONFIG_RESOLVER);
writer.openBlock("const partitionHash: PartitionHash = {", "};", () -> {
partitions.values().forEach(partition -> {
writer.openBlock("$S: {", "},", partition.identifier, () -> {
writer.openBlock("regions: [", "],", () -> {
for (String region : partition.getAllRegions()) {
writer.write("$S,", region);
}
});
writer.write("regionRegex: $S,", partition.regionRegex);
writer.write("variants: $L,", ArrayNode.prettyPrintJson(partition.variants));
partition.getPartitionEndpoint().ifPresent(
endpoint -> writer.write("endpoint: $S,", endpoint));
});
});
});
writer.write("");
}
private void writeEndpointProviderFunction() {
writer.addImport("RegionInfoProvider", "RegionInfoProvider", TypeScriptDependency.AWS_SDK_TYPES);
writer.addImport("RegionInfoProviderOptions", "RegionInfoProviderOptions",
TypeScriptDependency.AWS_SDK_TYPES);
writer.addImport("getRegionInfo", "getRegionInfo", TypeScriptDependency.CONFIG_RESOLVER);
writer.openBlock("export const defaultRegionInfoProvider: RegionInfoProvider = async (\n"
+ " region: string,\n"
+ " options?: RegionInfoProviderOptions\n"
+ ") => ", ";", () -> {
writer.openBlock("getRegionInfo(region, {", "})", () -> {
writer.write("...options,");
writer.write("signingService: $S,", baseSigningService);
writer.write("regionHash,");
writer.write("partitionHash,");
});
});
}
private void writeEndpointSpecificResolver(String region, ObjectNode resolved) {
writer.openBlock("$S: {", "},", region, () -> {
ArrayNode variants = resolved.expectArrayMember("variants");
writer.write("variants: $L,", ArrayNode.prettyPrintJson(variants));
resolved.getObjectMember("credentialScope").ifPresent(scope -> {
scope.getStringMember("region").ifPresent(signingRegion -> {
writer.write("signingRegion: $S,", signingRegion);
});
scope.getStringMember("service").ifPresent(signingService -> {
writer.write("signingService: $S,", signingService);
});
});
});
}
private ObjectNode getDefaultVariant(String hostname) {
return ObjectNode
.fromStringMap(Collections.singletonMap("hostname", hostname))
.withMember("tags", ArrayNode.fromStrings(Collections.emptyList()));
}
private String getResolvedHostname(String hostnameTemplate, String service) {
return getResolvedHostname(hostnameTemplate, service, "{region}");
}
private String getResolvedHostname(String hostnameTemplate, String service, String region) {
return hostnameTemplate
.replace("{service}", service)
.replace("{region}", region);
}
private String getResolvedHostnameWithDnsSuffix(String hostnameTemplate, String dnsSuffix) {
return hostnameTemplate.replace("{dnsSuffix}", dnsSuffix);
}
private final class Partition {
final ArrayNode variants;
final String dnsSuffix;
final String identifier;
final String regionRegex;
final String hostnameTemplate;
private final ObjectNode config;
private Partition(ObjectNode config, String partition) {
this.config = config;
// Resolve the partition defaults + the service defaults.
ObjectNode partitionDefaults = config.expectObjectMember("defaults");
ObjectNode serviceDefaults = getService().getObjectMember("defaults").orElse(Node.objectNode());
ObjectNode defaults = partitionDefaults.merge(serviceDefaults);
dnsSuffix = config.expectStringMember("dnsSuffix").getValue();
identifier = partition;
regionRegex = config.expectStringMember("regionRegex").getValue();
// Resolve the template to use for this service in this partition.
String hostname = defaults.expectStringMember("hostname").getValue();
hostnameTemplate = getResolvedHostname(hostname, endpointPrefix);
ArrayNode mergedVariants = getMergedVariants(
partitionDefaults.getArrayMember("variants").orElse(Node.arrayNode()),
serviceDefaults.getArrayMember("variants").orElse(Node.arrayNode())
);
variants = getVariants(mergedVariants);
}
ObjectNode getService() {
ObjectNode services = config.getObjectMember("services").orElse(Node.objectNode());
return services.getObjectMember(endpointPrefix).orElse(Node.objectNode());
}
Set<String> getAllRegions() {
Set<String> regions = new TreeSet<String>();
regions.addAll(
config.getObjectMember("regions")
.orElse(Node.objectNode()).getStringMap().keySet()
);
regions.addAll(
getService().getObjectMember("endpoints")
.orElse(Node.objectNode()).getStringMap().keySet()
);
return regions;
}
private ArrayNode getVariants(ArrayNode mergedVariants) {
List<Node> allVariants = new ArrayList<Node>();
allVariants.add(getDefaultVariant(getResolvedHostnameWithDnsSuffix(hostnameTemplate, this.dnsSuffix)));
mergedVariants.forEach(mergedVariant -> {
ObjectNode variantNode = mergedVariant.expectObjectNode();
String hostname = variantNode.expectStringMember("hostname").getValue();
String dnsSuffix = variantNode.getStringMemberOrDefault("dnsSuffix", this.dnsSuffix);
String resolvedHostname = getResolvedHostnameWithDnsSuffix(
getResolvedHostname(hostname, endpointPrefix),
dnsSuffix
);
allVariants.add(variantNode.withMember("hostname", resolvedHostname).withoutMember("dnsSuffix"));
});
return ArrayNode.fromNodes(allVariants);
}
private ArrayNode getMergedVariants(ArrayNode partitionVariants, ArrayNode serviceVariants) {
List<Node> mergedVariants = new ArrayList<Node>();
partitionVariants.forEach(partitionVariant -> {
ObjectNode partitionVariantNode = partitionVariant.expectObjectNode();
ArrayNode tags = partitionVariantNode.expectArrayMember("tags");
Node equivalentServiceVariantNode = serviceVariants.getElements().stream()
.filter(serviceVariantNode -> tags.equals(
serviceVariantNode.expectObjectNode().expectArrayMember("tags")))
.findFirst()
.orElse(null);
mergedVariants.add((equivalentServiceVariantNode == null)
? partitionVariantNode : equivalentServiceVariantNode);
});
return ArrayNode.fromNodes(mergedVariants);
}
Optional<String> getPartitionEndpoint() {
ObjectNode service = getService();
// Note: regionalized services always use regionalized endpoints.
return service.getBooleanMemberOrDefault("isRegionalized", true)
? Optional.empty()
: service.getStringMember("partitionEndpoint").map(StringNode::getValue);
}
}
}
| 4,822 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddEventBridgePlugin.java | /*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.Collections;
import java.util.Map;
import java.util.function.Consumer;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Adds customizations for EventBridge service.
*/
@SmithyInternalApi
public final class AddEventBridgePlugin implements TypeScriptIntegration {
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(TypeScriptSettings settings, Model model,
SymbolProvider symbolProvider, LanguageTarget target) {
if (!testServiceId(settings.getService(model))) {
return Collections.emptyMap();
}
if (settings.getExperimentalIdentityAndAuth()) {
return Collections.emptyMap();
}
// feat(experimentalIdentityAndAuth): control branch for EventBridge runtime config
switch (target) {
case SHARED:
return MapUtils.of("signerConstructor", writer -> {
writer.addDependency(AwsDependency.SIGNATURE_V4_MULTIREGION)
.addImport("SignatureV4MultiRegion", "SignatureV4MultiRegion",
AwsDependency.SIGNATURE_V4_MULTIREGION.packageName)
.write("SignatureV4MultiRegion");
});
default:
return Collections.emptyMap();
}
}
private static boolean testServiceId(Shape serviceShape) {
return serviceShape.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse("").equals("EventBridge");
}
}
| 4,823 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/JsonMemberDeserVisitor.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import software.amazon.smithy.aws.typescript.codegen.visitor.MemberDeserVisitor;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.model.shapes.BigDecimalShape;
import software.amazon.smithy.model.shapes.BigIntegerShape;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.UnionShape;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator.GenerationContext;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Overrides the default implementation of BigDecimal and BigInteger shape
* deserialization to throw when encountered in AWS REST JSON based protocols.
*/
@SmithyInternalApi
final class JsonMemberDeserVisitor extends MemberDeserVisitor {
private final MemberShape memberShape;
private final String dataSource;
/**
* @inheritDoc
*/
JsonMemberDeserVisitor(GenerationContext context,
MemberShape memberShape,
String dataSource,
Format defaultTimestampFormat) {
super(context, dataSource, defaultTimestampFormat);
this.dataSource = dataSource;
this.context = context;
this.memberShape = memberShape;
context.getWriter().addImport("_json", null, TypeScriptDependency.AWS_SMITHY_CLIENT);
this.serdeElisionEnabled = !context.getSettings().generateServerSdk();
}
JsonMemberDeserVisitor(GenerationContext context,
String dataSource,
Format defaultTimestampFormat) {
this(context, null, dataSource, defaultTimestampFormat);
}
@Override
public String bigDecimalShape(BigDecimalShape shape) {
// Fail instead of losing precision through Number.
return unsupportedShape(shape);
}
@Override
public String bigIntegerShape(BigIntegerShape shape) {
// Fail instead of losing precision through Number.
return unsupportedShape(shape);
}
@Override
public String unionShape(UnionShape shape) {
context.getWriter().addDependency(AwsDependency.AWS_SDK_CORE);
context.getWriter().addImport("awsExpectUnion", "__expectUnion", AwsDependency.AWS_SDK_CORE);
return getDelegateDeserializer(shape, "__expectUnion(" + dataSource + ")");
}
@Override
protected MemberShape getMemberShape() {
return memberShape;
}
@Override
protected boolean requiresNumericEpochSecondsInPayload() {
return true;
}
private String unsupportedShape(Shape shape) {
throw new CodegenException(String.format("Cannot deserialize shape type %s on protocol, shape: %s.",
shape.getType(), shape.getId()));
}
}
| 4,824 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/DocumentClientUtils.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.OperationIndex;
import software.amazon.smithy.model.shapes.CollectionShape;
import software.amazon.smithy.model.shapes.MapShape;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.shapes.UnionShape;
import software.amazon.smithy.utils.SmithyInternalApi;
@SmithyInternalApi
final class DocumentClientUtils {
static final String CLIENT_NAME = "DynamoDBDocumentClient";
static final String CLIENT_FULL_NAME = "DynamoDBDocument";
static final String CLIENT_CONFIG_NAME = getResolvedConfigTypeName(CLIENT_NAME);
static final String CLIENT_COMMANDS_FOLDER = "commands";
static final String CLIENT_UTILS_FILE = "utils";
static final String DOC_CLIENT_PREFIX = "doc-client-";
static final String CLIENT_TRANSLATE_CONFIG_KEY = "translateConfig";
static final String CLIENT_TRANSLATE_CONFIG_TYPE = "TranslateConfig";
static final String CLIENT_MARSHALL_OPTIONS = "marshallOptions";
static final String CLIENT_UNMARSHALL_OPTIONS = "unmarshallOptions";
private DocumentClientUtils() {}
static String getResolvedConfigTypeName(String symbolName) {
return symbolName + "ResolvedConfig";
}
static String getModifiedName(String name) {
return name.replace("Items", "").replace("Item", "");
}
static boolean containsAttributeValue(
Model model,
SymbolProvider symbolProvider,
OperationShape operation
) {
OperationIndex operationIndex = OperationIndex.of(model);
if (containsAttributeValue(model, symbolProvider, operationIndex.getInput(operation))
|| containsAttributeValue(model, symbolProvider, operationIndex.getOutput(operation))) {
return true;
}
return false;
}
static boolean containsAttributeValue(
Model model,
SymbolProvider symbolProvider,
Optional<StructureShape> optionalShape
) {
if (optionalShape.isPresent()) {
StructureShape structureShape = optionalShape.get();
for (MemberShape member : structureShape.getAllMembers().values()) {
if (containsAttributeValue(model, symbolProvider, member, new HashSet<String>())) {
return true;
}
}
}
return false;
}
static boolean containsAttributeValue(
Model model,
SymbolProvider symbolProvider,
MemberShape member,
Set<String> parents
) {
Shape memberTarget = model.expectShape(member.getTarget());
if (memberTarget.isStructureShape()) {
if (!parents.contains(symbolProvider.toMemberName(member))) {
parents.add(symbolProvider.toMemberName(member));
Collection<MemberShape> structureMemberList = ((StructureShape) memberTarget).getAllMembers().values();
for (MemberShape structureMember : structureMemberList) {
if (!parents.contains(symbolProvider.toMemberName(structureMember))
&& containsAttributeValue(model, symbolProvider, structureMember, parents)) {
return true;
}
}
}
} else if (memberTarget.isUnionShape()) {
if (symbolProvider.toSymbol(memberTarget).getName().equals("AttributeValue")) {
return true;
} else if (!parents.contains(symbolProvider.toMemberName(member))) {
parents.add(symbolProvider.toMemberName(member));
Collection<MemberShape> unionMemberList = ((UnionShape) memberTarget).getAllMembers().values();
for (MemberShape unionMember : unionMemberList) {
if (!parents.contains(symbolProvider.toMemberName(unionMember))
&& containsAttributeValue(model, symbolProvider, unionMember, parents)) {
return true;
}
}
}
} else if (memberTarget.isMapShape()) {
MemberShape mapMember = ((MapShape) memberTarget).getValue();
if (containsAttributeValue(model, symbolProvider, mapMember, parents)) {
return true;
}
} else if (memberTarget instanceof CollectionShape) {
MemberShape collectionMember = ((CollectionShape) memberTarget).getMember();
if (containsAttributeValue(model, symbolProvider, collectionMember, parents)) {
return true;
}
}
return false;
}
static String getCommandDocs(String operationName) {
return "Accepts native JavaScript types instead of `AttributeValue`s, and calls\n"
+ operationName + " operation from "
+ "{@link @aws-sdk/client-dynamodb#"
+ operationName
+ "}.\n\n"
+ "JavaScript objects passed in as parameters are marshalled into `AttributeValue` shapes \n"
+ "required by Amazon DynamoDB. Responses from DynamoDB are unmarshalled into plain JavaScript objects.";
}
static String getClientDocs() {
return "The document client simplifies working with items in Amazon DynamoDB by\n"
+ "abstracting away the notion of attribute values. This abstraction annotates native\n"
+ "JavaScript types supplied as input parameters, as well as converts annotated\n"
+ "response data to native JavaScript types.\n\n"
+ "## Marshalling Input and Unmarshalling Response Data\n\n"
+ "The document client affords developers the use of native JavaScript types\n"
+ "instead of `AttributeValue`s to simplify the JavaScript development\n"
+ "experience with Amazon DynamoDB. JavaScript objects passed in as parameters\n"
+ "are marshalled into `AttributeValue` shapes required by Amazon DynamoDB.\n"
+ "Responses from DynamoDB are unmarshalled into plain JavaScript objects\n"
+ "by the `DocumentClient`. The `DocumentClient` does not accept\n"
+ "`AttributeValue`s in favor of native JavaScript types.\n\n"
+ "| JavaScript Type | DynamoDB AttributeValue |\n"
+ "| :-------------------------------: | ----------------------- |\n"
+ "| String | S |\n"
+ "| Number / BigInt | N |\n"
+ "| Boolean | BOOL |\n"
+ "| null | NULL |\n"
+ "| Array | L |\n"
+ "| Object | M |\n"
+ "| Set\\<Uint8Array, Blob, ...\\> | BS |\n"
+ "| Set\\<Number, BigInt\\> | NS |\n"
+ "| Set\\<String\\> | SS |\n"
+ "| Uint8Array, Buffer, File, Blob... | B |\n"
+ "\n### Example\n\n"
+ "Here is an example list which is sent to DynamoDB client in an operation:\n\n"
+ "```json\n"
+ "{ \"L\": [{ \"NULL\": true }, { \"BOOL\": false }, { \"N\": 1 }, { \"S\": \"two\" }] }\n"
+ "```\n"
+ "\nThe DynamoDB document client abstracts the attribute values as follows in\n"
+ "both input and output:\n\n"
+ "```json\n"
+ "[null, false, 1, \"two\"]\n"
+ "```\n\n"
+ "@see {@link https://www.npmjs.com/package/@aws-sdk/client-dynamodb | @aws-sdk/client-dynamodb}";
}
}
| 4,825 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AwsJsonRpc1_1.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import software.amazon.smithy.aws.traits.protocols.AwsJson1_1Trait;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Handles generating the aws.json-1.1 protocol for services.
*
* @inheritDoc
*
* @see JsonRpcProtocolGenerator
*/
@SmithyInternalApi
final class AwsJsonRpc1_1 extends JsonRpcProtocolGenerator {
@Override
protected String getDocumentContentType() {
return "application/x-amz-json-1.1";
}
@Override
public ShapeId getProtocol() {
return AwsJson1_1Trait.ID;
}
@Override
public String getName() {
return "aws.json-1.1";
}
}
| 4,826 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddBuiltinPlugins.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isAwsService;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isEndpointsV2Service;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isSigV4Service;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_CONFIG;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_MIDDLEWARE;
import java.util.List;
import java.util.Set;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.OperationIndex;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.SetUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Adds all built-in runtime client plugins to clients.
*/
@SmithyInternalApi
public class AddBuiltinPlugins implements TypeScriptIntegration {
private static final Set<String> ROUTE_53_ID_MEMBERS = SetUtils.of("DelegationSetId", "HostedZoneId", "Id");
@Override
public List<RuntimeClientPlugin> getClientPlugins() {
// Note that order is significant because configurations might
// rely on previously resolved values.
return ListUtils.of(
RuntimeClientPlugin.builder()
.withConventions(TypeScriptDependency.CONFIG_RESOLVER.dependency, "Region", HAS_CONFIG)
.servicePredicate((m, s) -> isAwsService(s) || isSigV4Service(s))
.build(),
// Only one of Endpoints or CustomEndpoints should be used
RuntimeClientPlugin.builder()
.withConventions(
TypeScriptDependency.CONFIG_RESOLVER.dependency, "Endpoints", HAS_CONFIG)
.servicePredicate((m, s) -> isAwsService(s) && !isEndpointsV2Service(s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(
TypeScriptDependency.CONFIG_RESOLVER.dependency, "CustomEndpoints", HAS_CONFIG)
.servicePredicate((m, s) -> !isAwsService(s) && !isEndpointsV2Service(s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(
TypeScriptDependency.MIDDLEWARE_ENDPOINTS_V2.dependency, "Endpoint", HAS_CONFIG)
.servicePredicate((m, s) -> isAwsService(s) && isEndpointsV2Service(s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(TypeScriptDependency.MIDDLEWARE_RETRY.dependency, "Retry")
.build(),
RuntimeClientPlugin.builder()
.withConventions(TypeScriptDependency.MIDDLEWARE_CONTENT_LENGTH.dependency, "ContentLength",
HAS_MIDDLEWARE)
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.ACCEPT_HEADER.dependency, "AcceptHeader",
HAS_MIDDLEWARE)
.servicePredicate((m, s) -> testServiceId(s, "API Gateway"))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.GLACIER_MIDDLEWARE.dependency,
"Glacier", HAS_MIDDLEWARE)
.servicePredicate((m, s) -> testServiceId(s, "Glacier"))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.EC2_MIDDLEWARE.dependency,
"CopySnapshotPresignedUrl", HAS_MIDDLEWARE)
.operationPredicate((m, s, o) -> o.getId().getName(s).equals("CopySnapshot")
&& testServiceId(s, "EC2"))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MACHINELEARNING_MIDDLEWARE.dependency, "PredictEndpoint",
HAS_MIDDLEWARE)
.operationPredicate((m, s, o) -> o.getId().getName(s).equals("Predict")
&& testServiceId(s, "Machine Learning"))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.ROUTE53_MIDDLEWARE.dependency,
"ChangeResourceRecordSets", HAS_MIDDLEWARE)
.operationPredicate((m, s, o) -> o.getId().getName(s).equals("ChangeResourceRecordSets")
&& testServiceId(s, "Route 53"))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.ROUTE53_MIDDLEWARE.dependency, "IdNormalizer",
HAS_MIDDLEWARE)
.operationPredicate((m, s, o) -> testInputContainsMember(m, o, ROUTE_53_ID_MEMBERS)
&& testServiceId(s, "Route 53"))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_HOST_HEADER.dependency, "HostHeader")
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_LOGGER.dependency, "Logger", HAS_MIDDLEWARE)
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.RECURSION_DETECTION_MIDDLEWARE.dependency,
"RecursionDetection", HAS_MIDDLEWARE)
.build()
);
}
private static boolean testInputContainsMember(
Model model,
OperationShape operationShape,
Set<String> expectedMemberNames
) {
OperationIndex operationIndex = OperationIndex.of(model);
return operationIndex.getInput(operationShape)
.filter(input -> input.getMemberNames().stream().anyMatch(expectedMemberNames::contains))
.isPresent();
}
private static boolean testServiceId(Shape serviceShape, String expectedId) {
return serviceShape.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse("").equals(expectedId);
}
}
| 4,827 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddAwsRuntimeConfig.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isAwsService;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isSigV4Service;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.logging.Logger;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.aws.typescript.codegen.extensions.AwsRegionExtensionConfiguration;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.extensions.ExtensionConfigurationInterface;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* AWS clients need to know the service name for collecting metrics, the
* region name used to resolve endpoints, and whether to use Dualstack and
* Fips endpoints. For non AWS clients that use AWS Auth, region name is
* used as signing region.
*
* <p>This plugin adds the following config interface fields:
*
* <ul>
* <li>serviceId: Unique name to identify the AWS service.</li>
* <li>region: The AWS region to which this client will send requests</li>
* <li>useDualstackEndpoint: Enables IPv6/IPv4 dualstack endpoint.</li>
* <li>useFipsEndpoint: Enables FIPS compatible endpoints.</li>
* </ul>
*
* <p>This plugin adds the following Node runtime specific values:
*
* <ul>
* <li>serviceId: Unique name to identify the AWS service.</li>
* <li>region: Uses the default region provider that checks things like
* environment variables and the AWS config file.</li>
* <li>useDualstackEndpoint: Uses default useDualstackEndpoint provider.</li>
* <li>useFipsEndpoint: Uses default useFipsEndpoint provider.</li>
* </ul>
*
* <p>This plugin adds the following Browser runtime specific values:
*
* <ul>
* <li>serviceId: Unique name to identify the AWS service.</li>
* <li>region: Throws an exception since a region must
* be explicitly provided in the browser (environment variables and
* the shared config can't be resolved from the browser).</li>
* <li>useDualstackEndpoint: Sets to false.</li>
* <li>useFipsEndpoint: Sets to false.</li>
* </ul>
*/
@SmithyInternalApi
public final class AddAwsRuntimeConfig implements TypeScriptIntegration {
private static final Logger LOGGER = Logger.getLogger(AddAwsRuntimeConfig.class.getName());
@Override
public void addConfigInterfaceFields(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
if (isAwsService(settings, model)) {
writer.writeDocs("Unique service identifier.\n@internal")
.write("serviceId?: string;\n");
writer.writeDocs("Enables IPv6/IPv4 dualstack endpoint.")
.write("useDualstackEndpoint?: boolean | __Provider<boolean>;\n");
writer.writeDocs("Enables FIPS compatible endpoints.")
.write("useFipsEndpoint?: boolean | __Provider<boolean>;\n");
}
if (settings.getExperimentalIdentityAndAuth()) {
return;
}
// feat(experimentalIdentityAndAuth): control branch for AWS config interface fields
if (isSigV4Service(settings, model)) {
writer.writeDocs(isAwsService(settings, model)
? "The AWS region to which this client will send requests"
: "The AWS region to use as signing region for AWS Auth")
.write("region?: string | __Provider<string>;\n");
}
}
@Override
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
LanguageTarget target
) {
ServiceShape service = settings.getService(model);
Map<String, Consumer<TypeScriptWriter>> runtimeConfigs = new HashMap();
if (target.equals(LanguageTarget.SHARED)) {
String serviceId = service.getTrait(ServiceTrait.class)
.map(ServiceTrait::getSdkId)
.orElse(null);
if (serviceId != null) {
runtimeConfigs.put("serviceId", writer -> {
writer.write("$S", serviceId);
});
} else {
LOGGER.info("Cannot generate a service ID for the client because no aws.api#Service "
+ "trait was found on " + service.getId());
}
}
runtimeConfigs.putAll(getDefaultConfig(target, settings, model));
runtimeConfigs.putAll(getEndpointConfigWriters(target, settings, model));
return runtimeConfigs;
}
@Override
public List<ExtensionConfigurationInterface> getExtensionConfigurationInterfaces() {
return List.of(new AwsRegionExtensionConfiguration());
}
@Override
public void prepareCustomizations(
TypeScriptWriter writer,
LanguageTarget target,
TypeScriptSettings settings,
Model model
) {
if (target.equals(LanguageTarget.NODE)) {
writer.addDependency(AwsDependency.AWS_SDK_CORE);
writer.addImport("emitWarningIfUnsupportedVersion", "awsCheckVersion", AwsDependency.AWS_SDK_CORE);
writer.write("awsCheckVersion(process.version);");
}
}
private Map<String, Consumer<TypeScriptWriter>> getDefaultConfig(
LanguageTarget target,
TypeScriptSettings settings,
Model model
) {
if (!isSigV4Service(settings, model)) {
return Collections.emptyMap();
}
if (settings.getExperimentalIdentityAndAuth()) {
return Collections.emptyMap();
}
// feat(experimentalIdentityAndAuth): control branch for AWS runtime config
switch (target) {
case BROWSER:
return MapUtils.of("region", writer -> {
writer.addDependency(TypeScriptDependency.INVALID_DEPENDENCY);
writer.addImport("invalidProvider", "invalidProvider",
TypeScriptDependency.INVALID_DEPENDENCY);
writer.write("invalidProvider(\"Region is missing\")");
});
case NODE:
return MapUtils.of("region", writer -> {
writer.addDependency(TypeScriptDependency.NODE_CONFIG_PROVIDER);
writer.addImport("loadConfig", "loadNodeConfig",
TypeScriptDependency.NODE_CONFIG_PROVIDER);
writer.addDependency(TypeScriptDependency.CONFIG_RESOLVER);
writer.addImport("NODE_REGION_CONFIG_OPTIONS", "NODE_REGION_CONFIG_OPTIONS",
TypeScriptDependency.CONFIG_RESOLVER);
writer.addImport("NODE_REGION_CONFIG_FILE_OPTIONS", "NODE_REGION_CONFIG_FILE_OPTIONS",
TypeScriptDependency.CONFIG_RESOLVER);
writer.write(
"loadNodeConfig(NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS)");
});
default:
return Collections.emptyMap();
}
}
private Map<String, Consumer<TypeScriptWriter>> getEndpointConfigWriters(
LanguageTarget target,
TypeScriptSettings settings,
Model model
) {
if (!isAwsService(settings, model)) {
return Collections.emptyMap();
}
switch (target) {
case BROWSER:
return MapUtils.of(
"useDualstackEndpoint", writer -> {
writer.addDependency(TypeScriptDependency.CONFIG_RESOLVER);
writer.addImport("DEFAULT_USE_DUALSTACK_ENDPOINT", "DEFAULT_USE_DUALSTACK_ENDPOINT",
TypeScriptDependency.CONFIG_RESOLVER);
writer.write("(() => Promise.resolve(DEFAULT_USE_DUALSTACK_ENDPOINT))");
},
"useFipsEndpoint", writer -> {
writer.addDependency(TypeScriptDependency.CONFIG_RESOLVER);
writer.addImport("DEFAULT_USE_FIPS_ENDPOINT", "DEFAULT_USE_FIPS_ENDPOINT",
TypeScriptDependency.CONFIG_RESOLVER);
writer.write("(() => Promise.resolve(DEFAULT_USE_FIPS_ENDPOINT))");
}
);
case NODE:
return MapUtils.of(
"useDualstackEndpoint", writer -> {
writer.addDependency(TypeScriptDependency.NODE_CONFIG_PROVIDER);
writer.addImport("loadConfig", "loadNodeConfig",
TypeScriptDependency.NODE_CONFIG_PROVIDER);
writer.addDependency(TypeScriptDependency.CONFIG_RESOLVER);
writer.addImport("NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS",
"NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS",
TypeScriptDependency.CONFIG_RESOLVER);
writer.write("loadNodeConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS)");
},
"useFipsEndpoint", writer -> {
writer.addDependency(TypeScriptDependency.NODE_CONFIG_PROVIDER);
writer.addImport("loadConfig", "loadNodeConfig",
TypeScriptDependency.NODE_CONFIG_PROVIDER);
writer.addDependency(TypeScriptDependency.CONFIG_RESOLVER);
writer.addImport("NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS",
"NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS",
TypeScriptDependency.CONFIG_RESOLVER);
writer.write("loadNodeConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS)");
}
);
default:
return Collections.emptyMap();
}
}
}
| 4,828 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddEventStreamHandlingDependency.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_CONFIG;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_MIDDLEWARE;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.EventStreamIndex;
import software.amazon.smithy.model.knowledge.TopDownIndex;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Adds runtime client plugins that handle the eventstream flow in request,
* including eventstream payload signing.
*/
@SmithyInternalApi
public class AddEventStreamHandlingDependency implements TypeScriptIntegration {
@Override
public List<RuntimeClientPlugin> getClientPlugins() {
return ListUtils.of(
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_EVENTSTREAM.dependency,
"EventStream", HAS_CONFIG)
.servicePredicate(AddEventStreamHandlingDependency::hasEventStreamInput)
.settingsPredicate((m, s, settings) -> !settings.getExperimentalIdentityAndAuth())
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_EVENTSTREAM.dependency,
"EventStream", HAS_MIDDLEWARE)
.operationPredicate(AddEventStreamHandlingDependency::hasEventStreamInput)
.settingsPredicate((m, s, settings) -> !settings.getExperimentalIdentityAndAuth())
.build()
);
}
@Override
public void addConfigInterfaceFields(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
if (settings.getExperimentalIdentityAndAuth()) {
return;
}
// feat(experimentalIdentityAndAuth): control branch for event stream handler interface fields
if (hasEventStreamInput(model, settings.getService(model))) {
writer.addImport("EventStreamPayloadHandlerProvider", "__EventStreamPayloadHandlerProvider",
TypeScriptDependency.AWS_SDK_TYPES);
writer.writeDocs("The function that provides necessary utilities for handling request event stream.\n"
+ "@internal");
writer.write("eventStreamPayloadHandlerProvider?: __EventStreamPayloadHandlerProvider;\n");
}
}
@Override
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
LanguageTarget target
) {
ServiceShape service = settings.getService(model);
if (!hasEventStreamInput(model, service)) {
return Collections.emptyMap();
}
if (settings.getExperimentalIdentityAndAuth()) {
return Collections.emptyMap();
}
// feat(experimentalIdentityAndAuth): control branch for event stream handler runtime config
switch (target) {
case NODE:
return MapUtils.of("eventStreamPayloadHandlerProvider", writer -> {
writer.addDependency(AwsDependency.AWS_SDK_EVENTSTREAM_HANDLER_NODE);
writer.addImport("eventStreamPayloadHandlerProvider", "eventStreamPayloadHandlerProvider",
AwsDependency.AWS_SDK_EVENTSTREAM_HANDLER_NODE);
writer.write("eventStreamPayloadHandlerProvider");
});
case BROWSER:
/**
* Browser doesn't support streaming requests as of Aug 2022.
* Each service client needs to support eventstream request in browser individually.
* Services like TranscribeStreaming and Rekognition supports it via WebSocket.
* See the websocket customization in AddWebsocketPlugin.
*/
return MapUtils.of("eventStreamPayloadHandlerProvider", writer -> {
writer.addDependency(TypeScriptDependency.INVALID_DEPENDENCY);
writer.addImport("invalidFunction", "invalidFunction",
TypeScriptDependency.INVALID_DEPENDENCY);
writer.openBlock("(() => ({", "}))", () -> {
writer.write("handle: invalidFunction(\"event stream request is not supported in browser.\"),");
});
});
case REACT_NATIVE:
/**
* ReactNative doesn't support streaming requests as of March 2020.
* Here we don't supply invalidFunction. Each service client needs to support eventstream request
* in RN has to implement a customization providing its own eventStreamSignerProvider
*/
return MapUtils.of("eventStreamPayloadHandlerProvider", writer -> {
writer.addDependency(TypeScriptDependency.INVALID_DEPENDENCY);
writer.addImport("invalidFunction", "invalidFunction",
TypeScriptDependency.INVALID_DEPENDENCY);
writer.openBlock("(() => ({", "}))", () -> {
writer.write("handle: invalidFunction(\"event stream request "
+ "is not supported in ReactNative.\"),");
});
});
default:
return Collections.emptyMap();
}
}
private static boolean hasEventStreamInput(Model model, ServiceShape service) {
TopDownIndex topDownIndex = TopDownIndex.of(model);
Set<OperationShape> operations = topDownIndex.getContainedOperations(service);
EventStreamIndex eventStreamIndex = EventStreamIndex.of(model);
for (OperationShape operation : operations) {
if (eventStreamIndex.getInputInfo(operation).isPresent()) {
return true;
}
}
return false;
}
private static boolean hasEventStreamInput(Model model, ServiceShape service, OperationShape operation) {
EventStreamIndex eventStreamIndex = EventStreamIndex.of(model);
return eventStreamIndex.getInputInfo(operation).isPresent();
}
}
| 4,829 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/XmlShapeSerVisitor.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.CollectionShape;
import software.amazon.smithy.model.shapes.DocumentShape;
import software.amazon.smithy.model.shapes.MapShape;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.shapes.UnionShape;
import software.amazon.smithy.model.traits.SparseTrait;
import software.amazon.smithy.model.traits.TimestampFormatTrait;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.model.traits.XmlAttributeTrait;
import software.amazon.smithy.model.traits.XmlFlattenedTrait;
import software.amazon.smithy.model.traits.XmlNameTrait;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.DocumentMemberSerVisitor;
import software.amazon.smithy.typescript.codegen.integration.DocumentShapeSerVisitor;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator.GenerationContext;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Visitor to generate serialization functions for shapes in XML-document
* based document bodies.
*
* This class handles function body generation for all types expected by the {@code
* DocumentShapeSerVisitor}. No other shape type serialization is overridden.
*
* Timestamps are serialized to {@link Format}.DATE_TIME by default.
*
* @see <a href="https://smithy.io/2.0/spec/protocol-traits.html#xml-bindings">Smithy XML traits.</a>
*/
@SmithyInternalApi
final class XmlShapeSerVisitor extends DocumentShapeSerVisitor {
private static final Format TIMESTAMP_FORMAT = Format.DATE_TIME;
XmlShapeSerVisitor(GenerationContext context) {
super(context);
}
private XmlMemberSerVisitor getMemberVisitor(String dataSource) {
return new XmlMemberSerVisitor(getContext(), dataSource, TIMESTAMP_FORMAT);
}
@Override
protected void serializeCollection(GenerationContext context, CollectionShape shape) {
TypeScriptWriter writer = context.getWriter();
MemberShape memberShape = shape.getMember();
Shape target = context.getModel().expectShape(memberShape.getTarget());
writer.addImport("XmlNode", "__XmlNode", "@aws-sdk/xml-builder");
// Use the @xmlName trait if present on the member, otherwise use "member".
String locationName = memberShape.getTrait(XmlNameTrait.class)
.map(XmlNameTrait::getValue)
.orElse("member");
// Filter out null entries if we don't have the sparse trait.
String potentialFilter = "";
boolean hasSparseTrait = shape.hasTrait(SparseTrait.ID);
if (!hasSparseTrait) {
potentialFilter = ".filter((e: any) => e != null)";
}
writer.openBlock("return input$L.map(entry => {", "});", potentialFilter, () -> {
// Short circuit null values from serialization.
if (hasSparseTrait) {
writer.write("if (entry === null) { return null as any; }");
}
// Dispatch to the input value provider for any additional handling.
writer.write("const node = $L;", target.accept(getMemberVisitor("entry")));
// Handle proper unwrapping of target nodes.
if (serializationReturnsArray(target)) {
writer.openBlock("return node.reduce((acc: __XmlNode, workingNode: any) => {", "}", () -> {
// Add @xmlNamespace value of the target member.
AwsProtocolUtils.writeXmlNamespace(context, memberShape, "workingNode");
writer.write("return acc.addChildNode(workingNode);");
});
writer.write(", new __XmlNode($S));", locationName);
} else {
// Add @xmlNamespace value of the target member.
AwsProtocolUtils.writeXmlNamespace(context, memberShape, "node");
writer.write("return node.withName($S);", locationName);
}
});
}
@Override
protected void serializeDocument(GenerationContext context, DocumentShape shape) {
throw new CodegenException(String.format(
"Cannot serialize Document types on AWS XML protocols, shape: %s.", shape.getId()));
}
@Override
protected void serializeMap(GenerationContext context, MapShape shape) {
TypeScriptWriter writer = context.getWriter();
Model model = context.getModel();
writer.addImport("XmlNode", "__XmlNode", "@aws-sdk/xml-builder");
String keyTypeName = "keyof typeof input";
// Filter out null entries if we don't have the sparse trait.
String potentialFilter = "";
if (!shape.hasTrait(SparseTrait.ID)) {
potentialFilter = ".filter((key) => input[key as " + keyTypeName + "] != null)";
}
// Use the keys as an iteration point to dispatch to the input value providers.
writer.openBlock("return Object.keys(input)$L.map(key => {", "});", potentialFilter, () -> {
// Prepare a containing node for each entry's k/v pair.
writer.write("const entryNode = new __XmlNode(\"entry\");");
// Prepare the key's node.
// Use the @xmlName trait if present on the member, otherwise use "key".
MemberShape keyMember = shape.getKey();
Shape keyTarget = model.expectShape(keyMember.getTarget());
String keyName = keyMember.getTrait(XmlNameTrait.class)
.map(XmlNameTrait::getValue)
.orElse("key");
writer.write("const keyNode = $L.withName($S);", keyTarget.accept(getMemberVisitor("key")), keyName);
// Add @xmlNamespace value of the key member.
AwsProtocolUtils.writeXmlNamespace(context, keyMember, "keyNode");
writer.write("entryNode.addChildNode(keyNode);");
// Prepare the value's node.
// Use the @xmlName trait if present on the member, otherwise use "value".
MemberShape valueMember = shape.getValue();
Shape valueTarget = model.expectShape(valueMember.getTarget());
String valueName = valueMember.getTrait(XmlNameTrait.class)
.map(XmlNameTrait::getValue)
.orElse("value");
// Handle the sparse trait by short circuiting null values
// from serialization, and not including them if encountered
// when not sparse.
writer.write("var node;");
if (shape.hasTrait(SparseTrait.ID)) {
writer.openBlock("if (value === null) {", "} else {", () ->
writer.write("node = __XmlNode.of($S, null);", valueName));
writer.indent();
}
// Dispatch to the input value provider for any additional handling.
writer.write("node = $L;", valueTarget.accept(getMemberVisitor("input[key as " + keyTypeName + "]!")));
if (shape.hasTrait(SparseTrait.ID)) {
writer.dedent();
writer.write("}");
}
// Handle proper unwrapping of target nodes.
if (serializationReturnsArray(valueTarget)) {
writer.openBlock("entryNode.addChildNode(", ");", () -> {
writer.openBlock("node.reduce((acc: __XmlNode, workingNode: any) => {", "}", () -> {
// Add @xmlNamespace value of the value member.
AwsProtocolUtils.writeXmlNamespace(context, valueMember, "workingNode");
writer.write("return acc.addChildNode(workingNode);");
});
writer.write(", new __XmlNode($S))", valueName);
});
} else {
// Add @xmlNamespace value of the target member.
AwsProtocolUtils.writeXmlNamespace(context, valueMember, "node");
writer.write("entryNode.addChildNode(node.withName($S));", valueName);
}
writer.write("return entryNode;");
});
}
@Override
protected void serializeStructure(GenerationContext context, StructureShape shape) {
TypeScriptWriter writer = context.getWriter();
ServiceShape serviceShape = context.getService();
writer.addImport("XmlNode", "__XmlNode", "@aws-sdk/xml-builder");
// Handle the @xmlName trait for the structure itself.
String nodeName = shape.getTrait(XmlNameTrait.class)
.map(XmlNameTrait::getValue)
.orElse(shape.getId().getName(serviceShape));
// Create the structure's node.
writer.write("const bodyNode = new __XmlNode($S);", nodeName);
// Serialize every member of the structure if present.
Map<String, MemberShape> members = shape.getAllMembers();
members.forEach((memberName, memberShape) -> {
String inputLocation = "input." + memberName;
// Handle if the member is an idempotency token that should be auto-filled.
AwsProtocolUtils.writeIdempotencyAutofill(context, memberShape, inputLocation);
writer.openBlock("if ($1L != null) {", "}", inputLocation, () -> {
serializeNamedMember(context, memberName, memberShape, () -> inputLocation);
});
});
writer.write("return bodyNode;");
}
void serializeNamedMember(
GenerationContext context,
String memberName,
MemberShape memberShape,
Supplier<String> inputLocation
) {
TypeScriptWriter writer = context.getWriter();
// Use the @xmlName trait if present on the member, otherwise use the member name.
String locationName = memberShape.getTrait(XmlNameTrait.class)
.map(XmlNameTrait::getValue)
.orElse(memberName);
// Handle @xmlAttribute simple members.
if (memberShape.hasTrait(XmlAttributeTrait.class)) {
writer.write("bodyNode.addAttribute($S, $L);", locationName, inputLocation.get());
} else {
// Grab the target shape so we can use a member serializer on it.
Shape target = context.getModel().expectShape(memberShape.getTarget());
XmlMemberSerVisitor inputVisitor = getMemberVisitor(inputLocation.get());
// Collected members must be handled with flattening and renaming.
if (serializationReturnsArray(target)) {
serializeNamedMemberFromArray(context, locationName, memberShape, target, inputVisitor);
} else {
// Handle @timestampFormat on members not just the targeted shape.
String valueProvider;
if (memberShape.hasTrait(TimestampFormatTrait.class) || target.hasTrait(TimestampFormatTrait.class)) {
Optional<TimestampFormatTrait> timestampFormat = memberShape.getTrait(TimestampFormatTrait.class);
if (timestampFormat.isEmpty()) {
timestampFormat = target.getTrait(TimestampFormatTrait.class);
}
valueProvider = inputVisitor.getAsXmlText(target,
AwsProtocolUtils.getInputTimestampValueProvider(context, memberShape,
timestampFormat.get().getFormat(), inputLocation.get()) + ".toString()");
} else {
valueProvider = target.accept(inputVisitor);
}
// Standard members are added as children after updating their names.
writer.write("const node = $L.withName($S);", valueProvider, locationName);
// Add @xmlNamespace value of the target member.
AwsProtocolUtils.writeXmlNamespace(context, memberShape, "node");
writer.write("bodyNode.addChildNode(node);");
}
}
}
private void serializeNamedMemberFromArray(
GenerationContext context,
String locationName,
MemberShape memberShape,
Shape target,
DocumentMemberSerVisitor inputVisitor
) {
TypeScriptWriter writer = context.getWriter();
// Handle @xmlFlattened for collections and maps.
boolean isFlattened = memberShape.hasTrait(XmlFlattenedTrait.class);
// Get all the nodes that are going to be serialized.
writer.write("const nodes = $L;", target.accept(inputVisitor));
// Prepare a containing node to hold the nodes if not flattened.
if (!isFlattened) {
writer.write("const containerNode = new __XmlNode($S);", locationName);
// Add @xmlNamespace value of the target member.
AwsProtocolUtils.writeXmlNamespace(context, memberShape, "containerNode");
}
// Add every node to the target node.
writer.openBlock("nodes.map((node: any) => {", "});", () -> {
// Adjust to add sub nodes to the right target based on flattening.
String targetNode = isFlattened ? "bodyNode" : "containerNode";
if (isFlattened) {
writer.write("node = node.withName($S);", locationName);
}
writer.write("$L.addChildNode(node);", targetNode);
});
// For non-flattened collected nodes, we have to add the containing node.
if (!isFlattened) {
writer.write("bodyNode.addChildNode(containerNode);");
}
}
private boolean serializationReturnsArray(Shape shape) {
return (shape instanceof CollectionShape) || (shape instanceof MapShape);
}
@Override
protected void serializeUnion(GenerationContext context, UnionShape shape) {
TypeScriptWriter writer = context.getWriter();
ServiceShape serviceShape = context.getService();
writer.addImport("XmlNode", "__XmlNode", "@aws-sdk/xml-builder");
writer.addImport("XmlText", "__XmlText", "@aws-sdk/xml-builder");
// Handle the @xmlName trait for the union itself.
String nodeName = shape.getTrait(XmlNameTrait.class)
.map(XmlNameTrait::getValue)
.orElse(shape.getId().getName(serviceShape));
// Create the union's node.
writer.write("const bodyNode = new __XmlNode($S);", nodeName);
// Visit over the union type, then get the right serialization for the member.
writer.openBlock("$L.visit(input, {", "});", shape.getId().getName(serviceShape), () -> {
Map<String, MemberShape> members = shape.getAllMembers();
members.forEach((memberName, memberShape) -> {
writer.openBlock("$L: value => {", "},", memberName, () -> {
serializeNamedMember(context, memberName, memberShape, () -> "value");
});
});
// Handle the unknown property.
writer.openBlock("_: (name: string, value: any) => {", "}", () -> {
// Throw an exception if we're trying to serialize something that we wouldn't know how to.
writer.openBlock("if (!(value instanceof __XmlNode || value instanceof __XmlText)) {", "}", () -> {
writer.write("throw new Error(\"Unable to serialize unknown union members in XML.\");");
});
// Set the node explicitly for potentially correct cases.
writer.write("bodyNode.addChildNode(new __XmlNode(name).addChildNode(value));");
});
});
writer.write("return bodyNode;");
}
}
| 4,830 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AwsEc2.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.Set;
import software.amazon.smithy.aws.traits.protocols.Ec2QueryTrait;
import software.amazon.smithy.codegen.core.SymbolReference;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.HttpRpcProtocolGenerator;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Handles generating the aws.ec2 protocol for services. It handles reading and
* writing from document bodies, including generating any functions needed for
* performing serde.
*
* This builds on the foundations of the {@link HttpRpcProtocolGenerator} to handle
* standard components of the HTTP requests and responses.
*
* @see Ec2ShapeSerVisitor
* @see XmlShapeDeserVisitor
* @see QueryMemberSerVisitor
* @see XmlMemberDeserVisitor
* @see AwsProtocolUtils
* @see <a href="https://smithy.io/2.0/spec/protocol-traits.html#xml-bindings">Smithy XML traits.</a>
* @see <a href="https://smithy.io/2.0/aws/protocols/aws-ec2-query-protocol.html#aws-protocols-ec2queryname-trait">Smithy EC2 Query Name trait.</a>
*/
@SmithyInternalApi
final class AwsEc2 extends HttpRpcProtocolGenerator {
AwsEc2() {
super(true);
}
@Override
protected String getOperationPath(GenerationContext context, OperationShape operationShape) {
return "/";
}
@Override
public ShapeId getProtocol() {
return Ec2QueryTrait.ID;
}
@Override
public String getName() {
return "aws.ec2";
}
@Override
protected String getDocumentContentType() {
return "application/x-www-form-urlencoded";
}
@Override
protected void generateDocumentBodyShapeSerializers(GenerationContext context, Set<Shape> shapes) {
AwsProtocolUtils.generateDocumentBodyShapeSerde(context, shapes, new Ec2ShapeSerVisitor(context));
}
@Override
protected void generateDocumentBodyShapeDeserializers(GenerationContext context, Set<Shape> shapes) {
AwsProtocolUtils.generateDocumentBodyShapeSerde(context, shapes, new XmlShapeDeserVisitor(context));
}
@Override
public void generateSharedComponents(GenerationContext context) {
super.generateSharedComponents(context);
AwsProtocolUtils.generateXmlParseBody(context);
AwsProtocolUtils.generateXmlParseErrorBody(context);
AwsProtocolUtils.generateBuildFormUrlencodedString(context);
AwsProtocolUtils.addItempotencyAutofillImport(context);
TypeScriptWriter writer = context.getWriter();
// Generate a function that handles the complex rules around deserializing
// an error code from an xml error body.
SymbolReference responseType = getApplicationProtocol().getResponseType();
writer.openBlock("const loadEc2ErrorCode = (\n"
+ " output: $T,\n"
+ " data: any\n"
+ "): string | undefined => {", "};", responseType, () -> {
// Attempt to fetch the error code from the specific location.
String errorCodeCheckLocation = getErrorBodyLocation(context, "data") + "?.Code";
String errorCodeAccessLocation = getErrorBodyLocation(context, "data") + ".Code";
writer.openBlock("if ($L !== undefined) {", "}", errorCodeCheckLocation, () -> {
writer.write("return $L;", errorCodeAccessLocation);
});
// Default a 404 status code to the NotFound code.
writer.openBlock("if (output.statusCode == 404) {", "}", () -> writer.write("return 'NotFound';"));
});
writer.write("");
}
@Override
protected String getErrorBodyLocation(GenerationContext context, String outputLocation) {
return outputLocation + ".Errors.Error";
}
@Override
protected void writeRequestHeaders(GenerationContext context, OperationShape operation) {
TypeScriptWriter writer = context.getWriter();
if (AwsProtocolUtils.includeUnsignedPayloadSigV4Header(operation)) {
writer.openBlock("const headers: __HeaderBag = { ", " }", () -> {
AwsProtocolUtils.generateUnsignedPayloadSigV4Header(context, operation);
writer.write("...SHARED_HEADERS");
});
} else {
writer.write("const headers: __HeaderBag = SHARED_HEADERS;");
}
}
@Override
protected void serializeInputDocument(
GenerationContext context,
OperationShape operation,
StructureShape inputStructure
) {
TypeScriptWriter writer = context.getWriter();
// Set the form encoded string.
writer.openBlock("body = buildFormUrlencodedString({", "});", () -> {
// Gather all the explicit input entries.
writer.write("...$L,",
inputStructure.accept(new QueryMemberSerVisitor(context, "input", Format.DATE_TIME)));
// Set the protocol required values.
ServiceShape serviceShape = context.getService();
writer.write("Action: $S,", operation.getId().getName(serviceShape));
writer.write("Version: $S,", serviceShape.getVersion());
});
}
@Override
protected boolean writeUndefinedInputBody(GenerationContext context, OperationShape operation) {
return AwsProtocolUtils.generateUndefinedQueryInputBody(context, operation);
}
@Override
protected void writeErrorCodeParser(GenerationContext context) {
TypeScriptWriter writer = context.getWriter();
// Outsource error code parsing since it's complex for this protocol.
writer.write("const errorCode = loadEc2ErrorCode(output, parsedOutput.body);");
}
@Override
protected void deserializeOutputDocument(
GenerationContext context,
OperationShape operation,
StructureShape outputStructure
) {
TypeScriptWriter writer = context.getWriter();
writer.write("contents = $L;",
outputStructure.accept(new XmlMemberDeserVisitor(context, "data", Format.DATE_TIME)));
}
@Override
public void generateProtocolTests(GenerationContext context) {
AwsProtocolUtils.generateProtocolTests(this, context);
}
}
| 4,831 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/XmlShapeDeserVisitor.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.CollectionShape;
import software.amazon.smithy.model.shapes.DocumentShape;
import software.amazon.smithy.model.shapes.MapShape;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.shapes.UnionShape;
import software.amazon.smithy.model.traits.MediaTypeTrait;
import software.amazon.smithy.model.traits.SparseTrait;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.model.traits.XmlFlattenedTrait;
import software.amazon.smithy.model.traits.XmlNameTrait;
import software.amazon.smithy.typescript.codegen.CodegenUtils;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.DocumentMemberDeserVisitor;
import software.amazon.smithy.typescript.codegen.integration.DocumentShapeDeserVisitor;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator.GenerationContext;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Visitor to generate deserialization functions for shapes in XML-document
* based document bodies.
*
* No standard visitation methods are overridden; function body generation for
* all
* expected deserializers is handled by this class.
*
* Timestamps are deserialized from {@link Format}.DATE_TIME by default.
*
* @see <a href="https://smithy.io/2.0/spec/protocol-traits.html#xml-bindings">Smithy XML
* traits.</a>
*/
@SmithyInternalApi
final class XmlShapeDeserVisitor extends DocumentShapeDeserVisitor {
XmlShapeDeserVisitor(GenerationContext context) {
super(context);
}
private DocumentMemberDeserVisitor getMemberVisitor(MemberShape memberShape, String dataSource) {
return new XmlMemberDeserVisitor(getContext(), memberShape, dataSource, Format.DATE_TIME);
}
@Override
protected void deserializeCollection(GenerationContext context, CollectionShape shape) {
TypeScriptWriter writer = context.getWriter();
Shape target = context.getModel().expectShape(shape.getMember().getTarget());
// Filter out null entries if we don't have the sparse trait.
String potentialFilter = "";
boolean hasSparseTrait = shape.hasTrait(SparseTrait.ID);
if (!hasSparseTrait) {
potentialFilter = ".filter((e: any) => e != null)";
}
// Dispatch to the output value provider for any additional handling.
writer.openBlock("return (output || [])$L.map((entry: any) => {", "});", potentialFilter, () -> {
// Short circuit null values from deserialization.
if (hasSparseTrait) {
writer.write("if (entry === null) { return null as any; }");
}
String dataSource = getUnnamedTargetWrapper(context, target, "entry");
writer.write("return $L$L;", target.accept(getMemberVisitor(shape.getMember(), dataSource)),
usesExpect(target) ? " as any" : "");
});
}
private String getUnnamedTargetWrapper(GenerationContext context, Shape target, String dataSource) {
if (!deserializationReturnsArray(target)) {
return dataSource;
}
TypeScriptWriter writer = context.getWriter();
writer.addImport("getArrayIfSingleItem", "__getArrayIfSingleItem", TypeScriptDependency.AWS_SMITHY_CLIENT);
// The XML parser will set one K:V for a member that could
// return multiple entries but only has one.
// Update the target element if we target another level of collection.
String targetLocation = getUnnamedAggregateTargetLocation(context.getModel(), target);
return String.format("__getArrayIfSingleItem(%s[\"%s\"])", dataSource, targetLocation);
}
private boolean deserializationReturnsArray(Shape shape) {
return (shape instanceof CollectionShape) || (shape instanceof MapShape);
}
@Override
protected void deserializeDocument(GenerationContext context, DocumentShape shape) {
throw new CodegenException(String.format("Cannot deserialize Document types on AWS XML protocols, shape: %s.",
shape.getId()));
}
@Override
protected void deserializeMap(GenerationContext context, MapShape shape) {
TypeScriptWriter writer = context.getWriter();
Shape target = context.getModel().expectShape(shape.getValue().getTarget());
String keyLocation = shape.getKey().getTrait(XmlNameTrait.class).map(XmlNameTrait::getValue).orElse("key");
String valueLocation = shape.getValue().getTrait(XmlNameTrait.class).map(XmlNameTrait::getValue)
.orElse("value");
// Get the right serialization for each entry in the map. Undefined
// outputs won't have this deserializer invoked.
writer.openBlock("return output.reduce((acc: any, pair: any) => {", "}, {});", () -> {
String dataSource = getUnnamedTargetWrapper(context, target, "pair[\"" + valueLocation + "\"]");
writer.openBlock("if ($L === null) {", "}", dataSource, () -> {
// Handle the sparse trait by short-circuiting null values
// from deserialization, and not including them if encountered
// when not sparse.
if (shape.hasTrait(SparseTrait.ID)) {
writer.write("acc[pair[$S]] = null as any;");
}
writer.write("return acc;");
});
// Dispatch to the output value provider for any additional handling.
writer.write("acc[pair[$S]] = $L$L",
keyLocation,
target.accept(getMemberVisitor(shape.getValue(), dataSource)),
usesExpect(target) ? " as any;" : ";");
writer.write("return acc;");
});
}
@Override
protected void deserializeStructure(GenerationContext context, StructureShape shape) {
TypeScriptWriter writer = context.getWriter();
writer.write("let contents: any = {};");
shape.getAllMembers().forEach((memberName, memberShape) -> {
// Grab the target shape so we can use a member deserializer on it.
Shape target = context.getModel().expectShape(memberShape.getTarget());
deserializeNamedMember(context, memberName, memberShape, "output", (dataSource, visitor) -> {
writer.write("contents.$L = $L;", memberName, target.accept(visitor));
});
});
writer.write("return contents;");
}
/**
* Generates an if statement for deserializing an output member, validating its
* presence at the correct location, handling collections and flattening, and
* dispatching to the supplied function to generate the body of the if
* statement.
*
* @param context The generation context.
* @param memberName The name of the member being deserialized.
* @param memberShape The shape of the member being deserialized.
* @param inputLocation The parent input location of the member being
* deserialized.
* @param statementBodyGenerator A function that generates the proper
* deserialization
* after member presence is validated.
*/
void deserializeNamedMember(
GenerationContext context,
String memberName,
MemberShape memberShape,
String inputLocation,
BiConsumer<String, DocumentMemberDeserVisitor> statementBodyGenerator) {
TypeScriptWriter writer = context.getWriter();
Model model = context.getModel();
// Use the @xmlName trait if present on the member, otherwise use the member
// name.
String locationName = memberShape.getTrait(XmlNameTrait.class)
.map(XmlNameTrait::getValue)
.orElse(memberName);
// Grab the target shape so we can use a member deserializer on it.
Shape target = context.getModel().expectShape(memberShape.getTarget());
// Handle @xmlFlattened for collections and maps.
boolean isFlattened = memberShape.hasTrait(XmlFlattenedTrait.class);
// Handle targets that return multiple entities per member.
boolean deserializationReturnsArray = deserializationReturnsArray(target);
// Build a string based on the traits that represents the location.
// Note we don't need to handle @xmlAttribute here because the parser flattens
// attributes in to the main structure.
StringBuilder sourceBuilder = new StringBuilder(inputLocation).append("['").append(locationName).append("']");
// Track any locations we need to validate on our way to the final element.
List<String> locationsToValidate = new ArrayList<>();
// Go in to a specialized element for unflattened aggregates.
if (deserializationReturnsArray && !isFlattened) {
// Make sure we validate the wrapping element is set.
locationsToValidate.add(sourceBuilder.toString());
// Update the target element.
String targetLocation = getUnnamedAggregateTargetLocation(model, target);
sourceBuilder.append("['").append(targetLocation).append("']");
}
boolean canMemberParsed = handleEmptyTags(writer, target, inputLocation, locationName, memberName);
// Handle the response property.
String source = sourceBuilder.toString();
// Validate the resulting target element is set.
locationsToValidate.add(source);
// Build a string of the elements to validate before deserializing.
String validationStatement = locationsToValidate.stream()
.map(location -> location + " !== undefined")
.collect(Collectors.joining(" && "));
String ifOrElseIfStatement = canMemberParsed ? "else if" : "if";
writer.openBlock("$L ($L) {", "}", ifOrElseIfStatement, validationStatement, () -> {
String dataSource = getNamedTargetWrapper(context, target, source);
statementBodyGenerator.accept(dataSource, getMemberVisitor(memberShape, dataSource));
});
}
private String getNamedTargetWrapper(GenerationContext context, Shape target, String dataSource) {
if (!deserializationReturnsArray(target)) {
return dataSource;
}
TypeScriptWriter writer = context.getWriter();
writer.addImport("getArrayIfSingleItem", "__getArrayIfSingleItem", TypeScriptDependency.AWS_SMITHY_CLIENT);
// The XML parser will set one K:V for a member that could
// return multiple entries but only has one.
return String.format("__getArrayIfSingleItem(%s)", dataSource);
}
private String getUnnamedAggregateTargetLocation(Model model, Shape shape) {
if (shape.isMapShape()) {
return "entry";
}
// Any other aggregate shape is an instance of a CollectionShape.
return ((CollectionShape) shape).getMember().getMemberTrait(model, XmlNameTrait.class)
.map(XmlNameTrait::getValue)
.orElse("member");
}
// Handle self-closed xml parsed as an empty string. For Map, List, and
// Union, the deserializer should return empty value for empty Xml tags
// before parsing the subordinary members.
// It returns true if target can be returned earlier in case of empty tags.
private boolean handleEmptyTags(
TypeScriptWriter writer,
Shape target,
String inputLocation,
String locationName,
String memberName) {
if (target instanceof MapShape || target instanceof CollectionShape || target instanceof UnionShape) {
writer.openBlock("if ($L.$L === \"\") {", "}", inputLocation, locationName, () -> {
if (target instanceof MapShape) {
writer.write("contents.$L = {};", memberName);
} else if (target instanceof CollectionShape) {
writer.write("contents.$L = [];", memberName);
} else if (target instanceof UnionShape) {
writer.write("// Pass empty tags.");
}
});
return true;
} else {
return false;
}
}
@Override
protected void deserializeUnion(GenerationContext context, UnionShape shape) {
TypeScriptWriter writer = context.getWriter();
// Check for any known union members and return when we find one.
Map<String, MemberShape> members = shape.getAllMembers();
members.forEach((memberName, memberShape) -> {
// Grab the target shape so we can use a member deserializer on it.
Shape target = context.getModel().expectShape(memberShape.getTarget());
deserializeNamedMember(context, memberName, memberShape, "output", (dataSource, visitor) -> {
writer.openBlock("return {", "};", () -> {
// Dispatch to the output value provider for any additional handling.
writer.write("$L: $L$L", memberName, target.accept(visitor), usesExpect(target) ? " as any" : "");
});
});
});
// Or write output element to the unknown member.
writer.write("return { $$unknown: Object.entries(output)[0] };");
}
private boolean usesExpect(Shape shape) {
if (shape.isStringShape()) {
if (shape.hasTrait(MediaTypeTrait.class)) {
return !CodegenUtils.isJsonMediaType(shape.expectTrait(MediaTypeTrait.class).getValue());
}
return true;
}
return false;
}
}
| 4,832 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/QueryMemberSerVisitor.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.model.shapes.BigDecimalShape;
import software.amazon.smithy.model.shapes.BigIntegerShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.typescript.codegen.integration.DocumentMemberSerVisitor;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator.GenerationContext;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Overrides the default implementation of BigDecimal and BigInteger shape
* serialization to throw when encountered in the aws.query protocol.
*
* TODO: Work out support for BigDecimal and BigInteger, natively or through a library.
*/
@SmithyInternalApi
final class QueryMemberSerVisitor extends DocumentMemberSerVisitor {
QueryMemberSerVisitor(GenerationContext context, String dataSource, Format defaultTimestampFormat) {
super(context, dataSource, defaultTimestampFormat);
}
boolean visitSuppliesEntryList(Shape shape) {
return shape.isStructureShape() || shape.isUnionShape()
|| shape.isMapShape() || shape.isListShape() || shape.isSetShape();
}
@Override
public String bigDecimalShape(BigDecimalShape shape) {
// Fail instead of losing precision through Number.
return unsupportedShape(shape);
}
@Override
public String bigIntegerShape(BigIntegerShape shape) {
// Fail instead of losing precision through Number.
return unsupportedShape(shape);
}
private String unsupportedShape(Shape shape) {
throw new CodegenException(String.format("Cannot serialize shape type %s on protocol, shape: %s.",
shape.getType(), shape.getId()));
}
}
| 4,833 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AwsEndpointGeneratorIntegration.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isAwsService;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isEndpointsV2Service;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.rulesengine.traits.EndpointRuleSetTrait;
import software.amazon.smithy.typescript.codegen.CodegenUtils;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptCodegenContext;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Generates an endpoint resolver from endpoints.json.
*/
@SmithyInternalApi
public final class AwsEndpointGeneratorIntegration implements TypeScriptIntegration {
@Override
public void customize(TypeScriptCodegenContext codegenContext) {
TypeScriptSettings settings = codegenContext.settings();
Model model = codegenContext.model();
SymbolProvider symbolProvider = codegenContext.symbolProvider();
BiConsumer<String, Consumer<TypeScriptWriter>> writerFactory = codegenContext.writerDelegator()::useFileWriter;
writeAdditionalFiles(settings, model, symbolProvider, writerFactory);
}
private void writeAdditionalFiles(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
BiConsumer<String, Consumer<TypeScriptWriter>> writerFactory
) {
if (settings.generateClient()
&& isAwsService(settings, model)
&& settings.getService(model).hasTrait(EndpointRuleSetTrait.class)) {
writerFactory.accept(Paths.get(CodegenUtils.SOURCE_FOLDER, "index.ts").toString(), writer -> {
writer.addDependency(AwsDependency.UTIL_ENDPOINTS);
writer.write("import $S", AwsDependency.UTIL_ENDPOINTS.packageName);
});
}
if (!settings.generateClient()
|| !isAwsService(settings, model)
|| settings.getService(model).hasTrait(EndpointRuleSetTrait.class)) {
return;
}
writerFactory.accept(Paths.get(CodegenUtils.SOURCE_FOLDER, "endpoints.ts").toString(), writer -> {
new EndpointGenerator(settings.getService(model), writer).run();
});
}
@Override
public void addConfigInterfaceFields(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
if (!settings.generateClient() || !isAwsService(settings, model)) {
return;
}
ServiceShape service = settings.getService(model);
if (isEndpointsV2Service(service)) {
new ArrayList<String>() {
{
add("ClientInputEndpointParameters");
add("ClientResolvedEndpointParameters");
add("resolveClientEndpointParameters");
add("EndpointParameters");
}
}.forEach(name -> writer.addImport(
name,
null,
Paths.get(".", CodegenUtils.SOURCE_FOLDER, "endpoint/EndpointParameters").toString()
));
writer.addImport("EndpointV2", "__EndpointV2", TypeScriptDependency.SMITHY_TYPES);
} else {
writer.addImport("RegionInfoProvider", null, TypeScriptDependency.SMITHY_TYPES);
writer.writeDocs("Fetch related hostname, signing name or signing region with given region.\n"
+ "@internal");
writer.write("regionInfoProvider?: RegionInfoProvider;\n");
}
}
@Override
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
LanguageTarget target
) {
if (!settings.generateClient() || !isAwsService(settings, model)) {
return Collections.emptyMap();
}
if (settings.getService(model).hasTrait(EndpointRuleSetTrait.class)) {
if (target == LanguageTarget.SHARED) {
return MapUtils.of("endpointProvider", writer -> {
writer.addImport("defaultEndpointResolver", null,
Paths.get(".", CodegenUtils.SOURCE_FOLDER, "endpoint/endpointResolver").toString());
writer.write("defaultEndpointResolver");
});
}
} else {
if (target == LanguageTarget.SHARED) {
return MapUtils.of("regionInfoProvider", writer -> {
writer.addImport("defaultRegionInfoProvider", "defaultRegionInfoProvider",
Paths.get(".", CodegenUtils.SOURCE_FOLDER, "endpoints").toString());
writer.write("defaultRegionInfoProvider");
});
}
}
return Collections.emptyMap();
}
}
| 4,834 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AwsJsonRpc1_0.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen;
import software.amazon.smithy.aws.traits.protocols.AwsJson1_0Trait;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Handles generating the aws.json-1.0 protocol for services.
*
* @inheritDoc
*
* @see JsonRpcProtocolGenerator
*/
@SmithyInternalApi
final class AwsJsonRpc1_0 extends JsonRpcProtocolGenerator {
@Override
protected String getDocumentContentType() {
return "application/x-amz-json-1.0";
}
@Override
public ShapeId getProtocol() {
return AwsJson1_0Trait.ID;
}
@Override
public String getName() {
return "aws.json-1.0";
}
}
| 4,835 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/auth/http | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/auth/http/integration/AwsCustomizeHttpBearerTokenAuthPlugin.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package software.amazon.smithy.aws.typescript.codegen.auth.http.integration;
import java.util.List;
import software.amazon.smithy.aws.typescript.codegen.AwsDependency;
import software.amazon.smithy.model.traits.HttpBearerAuthTrait;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.auth.http.HttpAuthScheme;
import software.amazon.smithy.typescript.codegen.auth.http.SupportedHttpAuthSchemesIndex;
import software.amazon.smithy.typescript.codegen.auth.http.integration.AddHttpBearerAuthPlugin;
import software.amazon.smithy.typescript.codegen.auth.http.integration.HttpAuthTypeScriptIntegration;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Customize @httpBearerAuth for AWS SDKs.
*
* This is the experimental behavior for `experimentalIdentityAndAuth`.
*/
@SmithyInternalApi
public final class AwsCustomizeHttpBearerTokenAuthPlugin implements HttpAuthTypeScriptIntegration {
/**
* Integration should only be used if `experimentalIdentityAndAuth` flag is true.
*/
@Override
public boolean matchesSettings(TypeScriptSettings settings) {
return settings.getExperimentalIdentityAndAuth();
}
/**
* Run after default AddHttpBearerAuthPlugin.
*/
@Override
public List<String> runAfter() {
return List.of(AddHttpBearerAuthPlugin.class.getCanonicalName());
}
@Override
public void customizeSupportedHttpAuthSchemes(SupportedHttpAuthSchemesIndex supportedHttpAuthSchemesIndex) {
HttpAuthScheme authScheme = supportedHttpAuthSchemesIndex.getHttpAuthScheme(HttpBearerAuthTrait.ID).toBuilder()
// Current behavior of unconfigured `token` is to throw an error.
// This may need to be customized if a service is released with multiple auth schemes.
.putDefaultIdentityProvider(LanguageTarget.BROWSER, w ->
w.write("async () => { throw new Error(\"`token` is missing\"); }"))
// Use `@aws-sdk/token-providers` as the default identity provider chain for Node.js
.putDefaultIdentityProvider(LanguageTarget.NODE, w -> {
w.addDependency(AwsDependency.TOKEN_PROVIDERS);
w.addImport("nodeProvider", null, AwsDependency.TOKEN_PROVIDERS);
w.write("async (idProps) => await nodeProvider(idProps?.__config || {})(idProps)");
})
// Add __config as an identityProperty for backward compatibility of the `nodeProvider` default provider
.propertiesExtractor(s -> w -> w.write("""
(__config, context) => ({
/**
* @internal
*/
identityProperties: {
__config,
},
}),"""))
.build();
supportedHttpAuthSchemesIndex.putHttpAuthScheme(authScheme.getSchemeId(), authScheme);
}
}
| 4,836 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/auth/http | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/auth/http/integration/AddAwsDefaultSigningName.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package software.amazon.smithy.aws.typescript.codegen.auth.http.integration;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isAwsService;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isSigV4Service;
import java.util.logging.Logger;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.aws.traits.auth.SigV4Trait;
import software.amazon.smithy.aws.typescript.codegen.AddAwsAuthPlugin;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Configure clients with Default AWS Signing Name.
*
* This is the experimental behavior for `experimentalIdentityAndAuth`.
*/
@SmithyInternalApi
public final class AddAwsDefaultSigningName implements TypeScriptIntegration {
private static final Logger LOGGER = Logger.getLogger(AddAwsAuthPlugin.class.getName());
/**
* Integration should only be used if `experimentalIdentityAndAuth` flag is true.
*/
@Override
public boolean matchesSettings(TypeScriptSettings settings) {
return settings.getExperimentalIdentityAndAuth();
}
@Override
public void addConfigInterfaceFields(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
ServiceShape service = settings.getService(model);
// Do nothing if service doesn't use sigv4 and is not an AWS service
if (!isSigV4Service(service) && !isAwsService(service)) {
return;
}
// Write config field if service uses sigv4 and is not an AWS service
if (isSigV4Service(service) && !isAwsService(service)) {
writer
.writeDocs("The service name to use as the signing service for AWS Auth\n@internal")
.write("signingName?: string;\n");
}
// Set default name setting for service based on: SigV4 first, then the AWS Service trait
try {
settings.setDefaultSigningName(
service.getTrait(SigV4Trait.class)
.map(SigV4Trait::getName)
.orElseGet(() -> service.expectTrait(ServiceTrait.class).getArnNamespace())
);
} catch (Exception e) {
LOGGER.warning("Unable to set service default signing name. A SigV4 or Service trait is needed.");
}
}
}
| 4,837 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/auth/http | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/auth/http/integration/AwsCustomizeSigv4AuthPlugin.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package software.amazon.smithy.aws.typescript.codegen.auth.http.integration;
import java.util.List;
import software.amazon.smithy.aws.traits.auth.SigV4Trait;
import software.amazon.smithy.aws.typescript.codegen.AwsDependency;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.auth.http.HttpAuthScheme;
import software.amazon.smithy.typescript.codegen.auth.http.SupportedHttpAuthSchemesIndex;
import software.amazon.smithy.typescript.codegen.auth.http.integration.AddSigV4AuthPlugin;
import software.amazon.smithy.typescript.codegen.auth.http.integration.HttpAuthTypeScriptIntegration;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Customize @aws.auth#sigv4 for AWS SDKs.
*
* This is the experimental behavior for `experimentalIdentityAndAuth`.
*/
@SmithyInternalApi
public class AwsCustomizeSigv4AuthPlugin implements HttpAuthTypeScriptIntegration {
/**
* Integration should only be used if `experimentalIdentityAndAuth` flag is true.
*/
@Override
public boolean matchesSettings(TypeScriptSettings settings) {
return settings.getExperimentalIdentityAndAuth();
}
/**
* Run after default AddSigV4AuthPlugin.
*/
@Override
public List<String> runAfter() {
return List.of(AddSigV4AuthPlugin.class.getCanonicalName());
}
@Override
public void customizeSupportedHttpAuthSchemes(SupportedHttpAuthSchemesIndex supportedHttpAuthSchemesIndex) {
HttpAuthScheme authScheme = supportedHttpAuthSchemesIndex.getHttpAuthScheme(SigV4Trait.ID).toBuilder()
// Current behavior of unconfigured `credentials` is to throw an error.
// This may need to be customized if a service is released with multiple auth schemes.
.putDefaultIdentityProvider(LanguageTarget.BROWSER, w ->
w.write("async () => { throw new Error(\"`credentials` is missing\"); }"))
// Use `@aws-sdk/credential-provider-node` with `@aws-sdk/client-sts` as the
// default identity provider chain for Node.js
.putDefaultIdentityProvider(LanguageTarget.NODE, w -> {
w.addDependency(AwsDependency.STS_CLIENT);
w.addImport("decorateDefaultCredentialProvider", null, AwsDependency.STS_CLIENT);
w.addDependency(AwsDependency.CREDENTIAL_PROVIDER_NODE);
w.addImport("defaultProvider", "credentialDefaultProvider",
AwsDependency.CREDENTIAL_PROVIDER_NODE);
w.write("""
async (idProps) => await \
decorateDefaultCredentialProvider(credentialDefaultProvider)(idProps?.__config || {})()""");
})
// Add __config as an identityProperty for backward compatibility of `credentialDefaultProvider`
.propertiesExtractor(s -> w -> w.write("""
(__config, context) => ({
/**
* @internal
*/
identityProperties: {
__config,
},
}),"""))
.build();
supportedHttpAuthSchemesIndex.putHttpAuthScheme(authScheme.getSchemeId(), authScheme);
}
}
| 4,838 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/propertyaccess/PropertyAccessor.java | /*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen.propertyaccess;
import java.util.regex.Pattern;
public final class PropertyAccessor {
/**
* Starts with alpha or underscore, and contains only alphanumeric and underscores.
*/
public static final Pattern VALID_JAVASCRIPT_PROPERTY_NAME = Pattern.compile("^(?![0-9])[a-zA-Z0-9$_]+$");
private PropertyAccessor() {}
/**
* @param propertyName - property being accessed.
* @return brackets wrapping the name if it's not a valid JavaScript property name.
*/
public static String getPropertyAccessor(String propertyName) {
if (VALID_JAVASCRIPT_PROPERTY_NAME.matcher(propertyName).matches()) {
return "." + propertyName;
}
if (propertyName.contains("\"")) {
// This doesn't handle cases of the special characters being pre-escaped in the propertyName,
// but that case does not currently need to be addressed.
return "[`" + propertyName + "`]";
}
return "[\"" + propertyName + "\"]";
}
/**
* @param variable - object host.
* @param propertyName - property being accessed.
* @return e.g. someObject.prop or someObject['property name'] or reluctantly someObject[`bad"property"name`].
*/
public static String getFrom(String variable, String propertyName) {
return variable + getPropertyAccessor(propertyName);
}
}
| 4,839 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/extensions/AwsRegionExtensionConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.aws.typescript.codegen.extensions;
import software.amazon.smithy.aws.typescript.codegen.AwsDependency;
import software.amazon.smithy.typescript.codegen.Dependency;
import software.amazon.smithy.typescript.codegen.extensions.ExtensionConfigurationInterface;
import software.amazon.smithy.utils.Pair;
public class AwsRegionExtensionConfiguration implements ExtensionConfigurationInterface {
@Override
public Pair<String, Dependency> name() {
return Pair.of("AwsRegionExtensionConfiguration", AwsDependency.TYPES);
}
@Override
public Pair<String, Dependency> getExtensionConfigurationFn() {
return Pair.of("getAwsRegionExtensionConfiguration", AwsDependency.REGION_CONFIG_RESOLVER);
}
@Override
public Pair<String, Dependency> resolveRuntimeConfigFn() {
return Pair.of("resolveAwsRegionExtensionConfiguration", AwsDependency.REGION_CONFIG_RESOLVER);
}
}
| 4,840 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/visitor/MemberDeserVisitor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package software.amazon.smithy.aws.typescript.codegen.visitor;
import software.amazon.smithy.codegen.core.Symbol;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.traits.TimestampFormatTrait;
import software.amazon.smithy.typescript.codegen.integration.DocumentMemberDeserVisitor;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator.GenerationContext;
import software.amazon.smithy.typescript.codegen.knowledge.SerdeElisionIndex;
public class MemberDeserVisitor extends DocumentMemberDeserVisitor {
protected GenerationContext context;
protected SerdeElisionIndex serdeElisionIndex;
public MemberDeserVisitor(
GenerationContext context,
String dataSource,
TimestampFormatTrait.Format defaultTimestampFormat
) {
super(context, dataSource, defaultTimestampFormat);
this.serdeElisionIndex = SerdeElisionIndex.of(context.getModel());
this.context = context;
}
protected String getDelegateDeserializer(Shape shape, String customDataSource) {
// Use the shape for the function name.
Symbol symbol = context.getSymbolProvider().toSymbol(shape);
if (serdeElisionEnabled && serdeElisionIndex.mayElide(shape)) {
return "_json(" + customDataSource + ")";
}
return ProtocolGenerator.getDeserFunctionShortName(symbol)
+ "(" + customDataSource + ", context)";
}
}
| 4,841 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/validation/UnaryFunctionCall.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package software.amazon.smithy.aws.typescript.codegen.validation;
import java.util.regex.Pattern;
/**
* For handling expressions that may be unary function calls.
*/
public final class UnaryFunctionCall {
private static final Pattern CHECK_PATTERN = Pattern.compile("^(?!new ).+\\(((?!,).)*\\)$");
private static final Pattern TO_REF_PATTERN = Pattern.compile("(.*)\\(.*\\)$");
private UnaryFunctionCall() {
// Private
}
/**
* @param expression - to be examined.
* @return whether the expression is a single-depth function call with a single parameter.
*/
public static boolean check(String expression) {
if (expression.equals("_")) {
// not a call per se, but this indicates a pass-through function.
return true;
}
return maxCallDepth(expression) == 1 && CHECK_PATTERN.matcher(expression).matches();
}
/**
* @param callExpression the call expression to be converted. Check that
* the expression is a unary call first.
* @return the unary function call converted to a function reference.
*/
public static String toRef(String callExpression) {
return TO_REF_PATTERN.matcher(callExpression).replaceAll("$1");
}
/**
* Estimates the call depth of a function call expression.
*
* @param expression A function call expression (e.g., "call() == 1", "call(call()) == 2", etc).
*/
private static int maxCallDepth(String expression) {
int depth = 0;
int maxDepth = 0;
for (int i = 0; i < expression.length(); ++i) {
char c = expression.charAt(i);
if (c == '(') {
depth += 1;
if (depth > maxDepth) {
maxDepth = depth;
}
continue;
}
if (c == ')') {
depth -= 1;
}
}
return maxDepth;
}
}
| 4,842 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/BigEventTest.java | package software.amazon.event.ruler;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class BigEventTest {
@Test
public void WHEN_eventHasBigArrayAndLegacyFinderIsUsed_THEN_itWillCompleteSuccessfully_insteadOfCrashingOOM() throws Exception {
// when there are large number of array elements either in the rule and/or event, it used to lead to explosion in
// steps. A fix in Task.seenSteps collection takes a shortcut. This test is to check we won't regress
// and uses a modified version of event and rule to avoid early optimization
final Machine cut = new Machine();
String rule = GenericMachineTest.readData("bigEventRule.json");
cut.addRule("test", rule);
String event = GenericMachineTest.readData("bigEvent.json");
long start;
long latency;
List<String> list;
// pre-warm the machine
for(int i = 0; i < 5; i++) {
cut.rulesForJSONEvent(event);
}
// Below is the example of the output:
// matched rule name :[test]
// use rulesForJSONEvent API, matching takes : 71 ms
// matched rule name :[test]
// use rulesForEvent API, matching takes : 1552 ms
start = System.currentTimeMillis();
list = cut.rulesForJSONEvent(event);
System.out.println("matched rule name :" + list.toString());
latency = System.currentTimeMillis() - start;
System.out.println("use rulesForJSONEvent API, matching takes : " + latency + " ms");
assertTrue(!list.isEmpty() && latency < 500);
start = System.currentTimeMillis();
list = cut.rulesForEvent(event);
System.out.println("matched rule name :" + list.toString());
latency = System.currentTimeMillis() - start;
System.out.println("use rulesForEvent API, matching takes : " + latency + " ms");
assertTrue(!list.isEmpty() && latency < 4000);
}
}
| 4,843 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/ComparableNumberTest.java | package software.amazon.event.ruler;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ComparableNumberTest {
@Test
public void WHEN_BytesAreProvided_THEN_HexCharsAreReturned() {
for (int input = 0; input < 256; input++) {
char[] result = ComparableNumber.byteToHexChars((byte) input);
char[] expectedResult = String.format("%02x", input).toUpperCase(Locale.ROOT).toCharArray();
Assert.assertArrayEquals("byte to hex should match", expectedResult, result);
}
}
@Test
public void WHEN_WildlyVaryingNumberFormsAreProvided_THEN_TheGeneratedStringsAreSortable() {
double[] data = {
-Constants.FIVE_BILLION, -4_999_999_999.99999, -4_999_999_999.99998, -4_999_999_999.99997,
-999999999.99999, -999999999.99, -10000, -122.413496524705309, -0.000002,
0, 0.000001, 3.8, 3.9, 11, 12, 122.415028278886751, 2.5e4, 999999999.999998, 999999999.999999,
4_999_999_999.99997, 4_999_999_999.99998, 4_999_999_999.99999, Constants.FIVE_BILLION
};
for (int i = 1; i < data.length; i++) { // -122.415028278886751
String s0 = ComparableNumber.generate(data[i-1]);
String s1 = ComparableNumber.generate(data[i]);
System.out.println("i=" + i + " s0:"+s0+" s1:"+s1 );
assertTrue(s0.compareTo(s1) < 0);
}
}
@Test
public void tinyNumberTest() throws Exception {
// ComparableNumber for 1.0e-6 is 1000000000000001
// ComparableNumber for 4.0e-6 is 1000000000000004
String closedRule = "{\n" +
" \"a\": [ { \"numeric\": [ \">=\", 2.0e-6, \"<=\", 4.0e-6 ] } ]\n" +
"}";
String openRule = "{\n" +
" \"a\": [ { \"numeric\": [ \">\", 2.0e-6, \"<\", 4.0e-6 ] } ]\n" +
"}";
String template = "{\n" +
" \"a\": VAL\n" +
"}\n";
Machine m = new Machine();
m.addRule("r", closedRule);
for (double d = 0; d < 9.0e-6; d += 1.0e-6) {
String event = template.replace("VAL", Double.toString(d));
List<String> r = m.rulesForJSONEvent(event);
if (d >= 2.0e-6 && d <= 4.0e-6) {
assertEquals("Should match: " + d, 1, m.rulesForJSONEvent(event).size());
} else {
assertEquals("Should not match: " + d, 0, m.rulesForJSONEvent(event).size());
}
}
m = new Machine();
m.addRule("r", openRule);
for (double d = 0; d < 9.0e-6; d += 1.0e-6) {
String event = template.replace("VAL", Double.toString(d));
List<String> r = m.rulesForJSONEvent(event);
if (d > 2.0e-6 && d < 4.0e-6) {
assertEquals("Should match: " + d, 1, m.rulesForJSONEvent(event).size());
} else {
assertEquals("Should not match: " + d, 0, m.rulesForJSONEvent(event).size());
}
}
}
/**
* refer to https://www.epochconverter.com/ for eligible timestamp
* data1:
* Epoch timestamp: 1628958408
* Date and time (GMT): Saturday, August 14, 2021 4:26:48 PM
* data2:
* Epoch timestamp: 1629044808
* Date and time (GMT): Sunday, August 15, 2021 4:26:48 PM
*/
@Test
public void epocTimestampRangeTest() throws Exception {
final Map<String, String> rules = new HashMap<String, String>() {{
put("lessThan",
"{\n" +
" \"timestamp\": [ { \"numeric\": [ \"<=\", 1628872008 ] } ]\n" +
"}");
put("between",
"{\n" +
" \"timestamp\": [ { \"numeric\": [ \">=\", 1628872008, \"<=\", 1629044808 ] } ]\n" +
"}");
put("greatThan",
"{\n" +
" \"timestamp\": [ { \"numeric\": [ \">=\", 1629044808 ] } ]\n" +
"}");
}};
String template = "{\n" +
" \"timestamp\": VAL\n" +
"}\n";
final Machine m = new Machine();
for (Entry<String, String> r : rules.entrySet()) {
m.addRule(r.getKey(), r.getValue());
}
for (int tt = 1628872000; tt < 1629045000; tt++) {
String event = template.replace("VAL", Double.toString(tt));
List<String> match = m.rulesForJSONEvent(event);
if (tt <= 1628872008) {
assertTrue(match.contains("lessThan"));
} else if (tt < 1629044808) {
assertTrue(match.contains("between"));
} else {
assertTrue(match.contains("greatThan"));
}
if (tt == 1628872008 || tt == 1629044808) {
assertEquals(2, match.size());
}
}
// delete rules, verify machine becomes empty
for (Entry<String, String> r : rules.entrySet()) {
m.deleteRule(r.getKey(), r.getValue());
}
assertTrue(m.isEmpty());
}
} | 4,844 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/NameStateTest.java | package software.amazon.event.ruler;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class NameStateTest {
@Test
public void testAddSubRule() {
NameState nameState = new NameState();
nameState.addSubRule("rule1", 1.0, Patterns.exactMatch("a"), true);
nameState.addSubRule("rule1", 2.0, Patterns.exactMatch("b"), true);
nameState.addSubRule("rule2", 3.0, Patterns.exactMatch("a"), true);
assertEquals(new HashSet<>(asList(1.0, 3.0)),
nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("a")));
assertEquals(new HashSet<>(asList(2.0)), nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("b")));
assertNull(nameState.getNonTerminalSubRuleIdsForPattern(Patterns.exactMatch("a")));
}
@Test
public void testDeleteSubRule() {
NameState nameState = new NameState();
nameState.addSubRule("rule1", 1.0, Patterns.exactMatch("a"), true);
nameState.addSubRule("rule2", 2.0, Patterns.exactMatch("b"), true);
assertEquals(new HashSet<>(asList(1.0)), nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("a")));
assertEquals(new HashSet<>(asList(2.0)), nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("b")));
nameState.deleteSubRule(1.0, Patterns.exactMatch("b"), true);
assertEquals(new HashSet<>(asList(1.0)), nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("a")));
assertEquals(new HashSet<>(asList(2.0)), nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("b")));
nameState.deleteSubRule(2.0, Patterns.exactMatch("b"), true);
assertEquals(new HashSet<>(asList(1.0)), nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("a")));
assertNull(nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("b")));
nameState.deleteSubRule(2.0, Patterns.exactMatch("a"), true);
assertEquals(new HashSet<>(asList(1.0)), nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("a")));
assertNull(nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("b")));
nameState.deleteSubRule(1.0, Patterns.exactMatch("a"), false);
assertEquals(new HashSet<>(asList(1.0)), nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("a")));
assertNull(nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("b")));
nameState.deleteSubRule(1.0, Patterns.exactMatch("a"), true);
assertNull(nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("a")));
assertNull(nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("b")));
}
@Test
public void testGetTerminalPatterns() {
NameState nameState = new NameState();
nameState.addSubRule("rule1", 1.0, Patterns.exactMatch("a"), true);
nameState.addSubRule("rule1", 2.0, Patterns.exactMatch("b"), false);
nameState.addSubRule("rule2", 3.0, Patterns.exactMatch("a"), false);
nameState.addSubRule("rule3", 4.0, Patterns.exactMatch("c"), true);
Set<Patterns> expectedPatterns = new HashSet<>(Arrays.asList(
Patterns.exactMatch("a"), Patterns.exactMatch("c")));
assertEquals(expectedPatterns, nameState.getTerminalPatterns());
}
@Test
public void testGetNonTerminalPatterns() {
NameState nameState = new NameState();
nameState.addSubRule("rule1", 1.0, Patterns.exactMatch("a"), false);
nameState.addSubRule("rule1", 2.0, Patterns.exactMatch("b"), true);
nameState.addSubRule("rule2", 3.0, Patterns.exactMatch("a"), true);
nameState.addSubRule("rule3", 4.0, Patterns.exactMatch("c"), false);
Set<Patterns> expectedPatterns = new HashSet<>(Arrays.asList(
Patterns.exactMatch("a"), Patterns.exactMatch("c")));
assertEquals(expectedPatterns, nameState.getNonTerminalPatterns());
}
@Test
public void testGetTerminalSubRuleIdsForPattern() {
NameState nameState = new NameState();
nameState.addSubRule("rule1", 1.0, Patterns.exactMatch("a"), false);
nameState.addSubRule("rule1", 2.0, Patterns.exactMatch("a"), true);
nameState.addSubRule("rule2", 3.0, Patterns.exactMatch("b"), false);
nameState.addSubRule("rule3", 4.0, Patterns.exactMatch("a"), true);
assertEquals(new HashSet<>(Arrays.asList(2.0, 4.0)),
nameState.getTerminalSubRuleIdsForPattern(Patterns.exactMatch("a")));
}
@Test
public void testGetNonTerminalSubRuleIdsForPattern() {
NameState nameState = new NameState();
nameState.addSubRule("rule1", 1.0, Patterns.exactMatch("a"), true);
nameState.addSubRule("rule1", 2.0, Patterns.exactMatch("a"), false);
nameState.addSubRule("rule2", 3.0, Patterns.exactMatch("a"), false);
nameState.addSubRule("rule3", 4.0, Patterns.exactMatch("b"), false);
assertEquals(new HashSet<>(Arrays.asList(2.0, 3.0)),
nameState.getNonTerminalSubRuleIdsForPattern(Patterns.exactMatch("a")));
}
@Test
public void testContainsRule() {
NameState nameState = new NameState();
nameState.addSubRule("rule1", 1.0, Patterns.exactMatch("a"), true);
nameState.addSubRule("rule2", 2.0, Patterns.exactMatch("a"), false);
nameState.addSubRule("rule1", 2.0, Patterns.exactMatch("b"), false);
assertTrue(nameState.containsRule("rule1", Patterns.exactMatch("a")));
assertTrue(nameState.containsRule("rule2", Patterns.exactMatch("a")));
assertTrue(nameState.containsRule("rule1", Patterns.exactMatch("b")));
assertFalse(nameState.containsRule("rule3", Patterns.exactMatch("a")));
assertFalse(nameState.containsRule("rule1", Patterns.exactMatch("c")));
}
}
| 4,845 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/ByteMachineTest.java | package software.amazon.event.ruler;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import software.amazon.event.ruler.input.ParseException;
import org.junit.Test;
import static software.amazon.event.ruler.PermutationsGenerator.generateAllPermutations;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class ByteMachineTest {
@Test
public void WHEN_ManyOverLappingStringsAreAdded_THEN_TheyAreParsedProperly() {
String[] patterns = {
"a", "ab", "ab", "ab", "abc", "abx", "abz", "abzz", "x",
"cafe furioso", "café",
"Ξ\uD800\uDF46ज",
"Ξ ज"
};
ByteMachine cut = new ByteMachine();
for (String pattern : patterns) {
cut.addPattern(Patterns.exactMatch(pattern));
}
for (String pattern : patterns) {
assertFalse(cut.transitionOn(pattern).isEmpty());
}
String[] noMatches = {
"foo", "bar", "baz", "cafe pacifica", "cafë"
};
for (String noMatch : noMatches) {
assertTrue(cut.transitionOn(noMatch).isEmpty());
}
}
@Test
public void WHEN_AnythingButPrefixPatternIsAdded_THEN_ItMatchesAppropriately() {
Patterns abpp = Patterns.anythingButPrefix("foo");
ByteMachine bm = new ByteMachine();
bm.addPattern(abpp);
String[] shouldMatch = {
"f",
"fo",
"a",
"33"
};
String[] shouldNotMatch = {
"foo",
"foo1",
"foossssss2sssssssssssss4ssssssssssssss5sssssssssssssss7ssssssssssssssssssssssssssssssssssssssss"
};
Set<NameStateWithPattern> matches;
for (String s : shouldMatch) {
matches = bm.transitionOn(s);
assertEquals(1, matches.size());
}
for (String s : shouldNotMatch) {
matches = bm.transitionOn(s);
assertEquals(0, matches.size());
}
abpp = Patterns.anythingButPrefix("foo");
bm.deletePattern(abpp);
for (String s : shouldMatch) {
matches = bm.transitionOn(s);
assertEquals(0, matches.size());
}
// exercise deletePattern
Set<String> abs = new HashSet<>();
abs.add("foo");
AnythingBut ab = AnythingBut.anythingButMatch(abs);
bm.addPattern(abpp);
Patterns[] trickyPatterns = {
Patterns.prefixMatch("foo"),
Patterns.anythingButPrefix("f"),
Patterns.anythingButPrefix("fo"),
Patterns.anythingButPrefix("fooo"),
Patterns.exactMatch("foo"),
ab
};
for (Patterns tricky : trickyPatterns) {
bm.deletePattern(tricky);
}
for (String s : shouldMatch) {
matches = bm.transitionOn(s);
assertEquals(1, matches.size());
}
}
@Test
public void WHEN_NumericEQIsAdded_THEN_ItMatchesMultipleNumericForms() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.numericEquals(300.0));
String[] threeHundreds = { "300", "3.0e+2", "300.0000" };
for (String threeHundred : threeHundreds) {
assertEquals(1, cut.transitionOn(threeHundred).size());
}
}
@Test
public void WHEN_NumericRangesAreAdded_THEN_TheyWorkCorrectly() {
double[] data = {
-Constants.FIVE_BILLION, -4_999_999_999.99999, -4_999_999_999.99998, -4_999_999_999.99997,
-999999999.99999, -999999999.99, -10000, -0.000002,
0, 0.000001, 3.8, 2.5e4, 999999999.999998, 999999999.999999, 1628955663d, 3206792463d, 4784629263d,
4_999_999_999.99997, 4_999_999_999.99998, 4_999_999_999.99999, Constants.FIVE_BILLION
};
// Orderly add rule and random delete rules
{
Range[] ranges = new Range[data.length-1];
int rangeIdx = 0;
ByteMachine cut = new ByteMachine();
for (int i = 1; i < data.length; i++) {
cut.addPattern(Range.lessThan(data[i]));
ranges[rangeIdx++] = Range.lessThan(data[i]);
}
// shuffle the array
List<Range> list = Arrays.asList(ranges);
Collections.shuffle(list);
list.toArray(ranges);
for (Range range : ranges) {
cut.deletePattern(range);
}
assertTrue("byteMachine must be empty after delete pattern", cut.isEmpty());
}
// first: less than
for (int i = 1; i < data.length; i++) {
ByteMachine cut = new ByteMachine();
cut.addPattern(Range.lessThan(data[i]));
for (double aData : data) {
String num = String.format("%f", aData);
Set<NameStateWithPattern> matched = cut.transitionOn(num);
if (aData < data[i]) {
assertEquals(num + " should match < " + data[i], 1, matched.size());
} else {
assertEquals(num + " should not match <" + data[i], 0, matched.size());
}
}
cut.deletePattern(Range.lessThan(data[i]));
assertTrue("byteMachine must be empty after delete pattern", cut.isEmpty());
}
// <=
for (int i = 1; i < data.length; i++) {
ByteMachine cut = new ByteMachine();
cut.addPattern(Range.lessThanOrEqualTo(data[i]));
for (double aData : data) {
String num = String.format("%f", aData);
Set<NameStateWithPattern> matched = cut.transitionOn(num);
if (aData <= data[i]) {
assertEquals(num + " should match <= " + data[i], 1, matched.size());
} else {
assertEquals(num + " should not match <=" + data[i], 0, matched.size());
}
}
cut.deletePattern(Range.lessThanOrEqualTo(data[i]));
assertTrue("byteMachine must be empty after delete pattern", cut.isEmpty());
}
// >
for (int i = 0; i < (data.length - 1); i++) {
ByteMachine cut = new ByteMachine();
cut.addPattern(Range.greaterThan(data[i]));
for (double aData : data) {
String num = String.format("%f", aData);
Set<NameStateWithPattern> matched = cut.transitionOn(num);
if (aData > data[i]) {
assertEquals(num + " should match > " + data[i], 1, matched.size());
} else {
assertEquals(num + " should not match >" + data[i], 0, matched.size());
}
}
cut.deletePattern(Range.greaterThan(data[i]));
assertTrue("byteMachine must be empty after delete pattern", cut.isEmpty());
}
// >=
for (int i = 0; i < (data.length - 1); i++) {
ByteMachine cut = new ByteMachine();
Range nr = Range.greaterThanOrEqualTo(data[i]);
cut.addPattern(nr);
for (double aData : data) {
String num = String.format("%f", aData);
Set<NameStateWithPattern> matched = cut.transitionOn(num);
if (aData >= data[i]) {
assertEquals(num + " should match > " + data[i], 1, matched.size());
} else {
assertEquals(num + " should not match >" + data[i], 0, matched.size());
}
}
cut.deletePattern(Range.greaterThanOrEqualTo(data[i]));
assertTrue("byteMachine must be empty after delete pattern", cut.isEmpty());
}
// open/open range
for (int i = 0; i < (data.length - 2); i++) {
for (int j = i + 2; j < data.length; j++) {
ByteMachine cut = new ByteMachine();
Range r = Range.between(data[i], true, data[j], true);
cut.addPattern(r);
for (double aData : data) {
String num = String.format("%f", aData);
Set<NameStateWithPattern> matched = cut.transitionOn(num);
if (aData > data[i] && aData < data[j]) {
assertEquals(1, matched.size());
} else {
assertEquals(0, matched.size());
}
}
cut.deletePattern(r);
assertTrue("byteMachine must be empty after delete pattern", cut.isEmpty());
}
}
// open/closed range
for (int i = 0; i < (data.length - 2); i++) {
for (int j = i + 2; j < data.length; j++) {
ByteMachine cut = new ByteMachine();
Range r = Range.between(data[i], true, data[j], false);
cut.addPattern(r);
for (double aData : data) {
String num = String.format("%f", aData);
Set<NameStateWithPattern> matched = cut.transitionOn(num);
if (aData > data[i] && aData <= data[j]) {
assertEquals(1, matched.size());
} else {
assertEquals(0, matched.size());
}
}
cut.deletePattern(r);
assertTrue("byteMachine must be empty after delete pattern", cut.isEmpty());
}
}
// closed/open range
for (int i = 0; i < (data.length - 2); i++) {
for (int j = i + 2; j < data.length; j++) {
ByteMachine cut = new ByteMachine();
Range r = Range.between(data[i], false, data[j], true);
cut.addPattern(r);
for (double aData : data) {
String num = String.format("%f", aData);
Set<NameStateWithPattern> matched = cut.transitionOn(num);
if (aData >= data[i] && aData < data[j]) {
assertEquals(1, matched.size());
} else {
assertEquals(0, matched.size());
}
}
cut.deletePattern(r);
assertTrue("byteMachine must be empty after delete pattern", cut.isEmpty());
}
}
// closed/closed range
for (int i = 0; i < (data.length - 2); i++) {
for (int j = i + 2; j < data.length; j++) {
ByteMachine cut = new ByteMachine();
Range r = Range.between(data[i], false, data[j], false);
cut.addPattern(r);
for (double aData : data) {
String num = String.format("%f", aData);
Set<NameStateWithPattern> matched = cut.transitionOn(num);
if (aData >= data[i] && aData <= data[j]) {
assertEquals(1, matched.size());
} else {
assertEquals(0, matched.size());
}
}
cut.deletePattern(r);
assertTrue("byteMachine must be empty after delete pattern", cut.isEmpty());
}
}
// overlapping ranges
int[] containedCount = new int[data.length];
ByteMachine cut = new ByteMachine();
for (int i = 0; i < (data.length - 2); i++) {
for (int j = i + 2; j < data.length; j++) {
Range r = Range.between(data[i], false, data[j], false);
cut.addPattern(r);
for (int k = 0; k < data.length; k++) {
if (data[k] >= data[i] && data[k] <= data[j]) {
containedCount[k]++;
}
}
}
}
for (int k = 0; k < data.length; k++) {
String num = String.format("%f", data[k]);
Set<NameStateWithPattern> matched = cut.transitionOn(num);
assertEquals(containedCount[k], matched.size());
}
// delete the range
for (int i = 0; i < (data.length - 2); i++) {
for (int j = i + 2; j < data.length; j++) {
Range r = Range.between(data[i], false, data[j], false);
cut.deletePattern(r);
for (int k = 0; k < data.length; k++) {
if (data[k] >= data[i] && data[k] <= data[j]) {
containedCount[k]--;
}
}
}
}
assertTrue("byteMachine must be empty after delete pattern", cut.isEmpty());
for (int k = 0; k < data.length; k++) {
String num = String.format("%f", data[k]);
Set<NameStateWithPattern> matched = cut.transitionOn(num);
assertEquals(containedCount[k], matched.size());
assertEquals(0, matched.size());
}
// overlapping open ranges
containedCount = new int[data.length];
cut = new ByteMachine();
for (int i = 0; i < (data.length - 2); i++) {
for (int j = i + 2; j < data.length; j++) {
Range r = Range.between(data[i], true, data[j], true);
cut.addPattern(r);
for (int k = 0; k < data.length; k++) {
if (data[k] > data[i] && data[k] < data[j]) {
containedCount[k]++;
}
}
}
}
for (int k = 0; k < data.length; k++) {
String num = String.format("%f", data[k]);
Set<NameStateWithPattern> matched = cut.transitionOn(num);
assertEquals(containedCount[k], matched.size());
}
for (int i = 0; i < (data.length - 2); i++) {
for (int j = i + 2; j < data.length; j++) {
Range r = Range.between(data[i], true, data[j], true);
cut.deletePattern(r);
for (int k = 0; k < data.length; k++) {
if (data[k] > data[i] && data[k] < data[j]) {
containedCount[k]--;
}
}
}
}
assertTrue("byteMachine must be empty after delete pattern", cut.isEmpty());
for (int k = 0; k < data.length; k++) {
String num = String.format("%f", data[k]);
Set<NameStateWithPattern> matched = cut.transitionOn(num);
assertEquals(containedCount[k], matched.size());
assertEquals(0, matched.size());
}
}
@Test
public void WHEN_AnExactMatchAndAPrefixMatchCoincide_THEN_TwoNameStateJumpsAreGenerated() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.exactMatch("horse"));
cut.addPattern(Patterns.prefixMatch("horse"));
assertEquals(2, cut.transitionOn("horse").size());
assertEquals(1, cut.transitionOn("horseback").size());
}
@Test
public void WHEN_TheSamePatternIsAddedTwice_THEN_ItOnlyCausesOneNamestateJump() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.exactMatch("foo"));
cut.addPattern(Patterns.exactMatch("foo"));
Set<NameStateWithPattern> l = cut.transitionOn("foo");
assertEquals(1, l.size());
}
@Test
public void WHEN_AnyThingButPatternsAreAdded_THEN_TheyWork() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.anythingButMatch("foo"));
String[] notFoos = { "bar", "baz", "for", "too", "fro", "fo", "foobar" };
for (String notFoo : notFoos) {
assertEquals(1, cut.transitionOn(notFoo).size());
}
assertEquals(0, cut.transitionOn("foo").size());
}
@Test
public void WHEN_AnyThingButStringListPatternsAreAdded_THEN_TheyWork() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.anythingButMatch(new HashSet<>(Arrays.asList("bab","ford"))));
String[] notFoos = { "bar", "baz", "for", "too", "fro", "fo", "foobar" };
for (String notFoo : notFoos) {
assertEquals(1, cut.transitionOn(notFoo).size());
}
assertEquals(0, cut.transitionOn("bab").size());
assertEquals(0, cut.transitionOn("ford").size());
}
@Test
public void WHEN_AnyThingButNumberListPatternsAreAdded_THEN_TheyWork() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.anythingButNumberMatch(
new HashSet<>(Arrays.asList(1.11, 2d))));
cut.addPattern(Patterns.anythingButNumberMatch(
new HashSet<>(Arrays.asList(3.33, 2d))));
String[] notFoos = { "0", "1.1", "5", "9", "112", "fo", "foobar" };
for (String notFoo : notFoos) {
assertEquals(2, cut.transitionOn(notFoo).size());
}
assertEquals(1, cut.transitionOn("1.11").size());
assertEquals(1, cut.transitionOn("3.33").size());
assertEquals(2, cut.transitionOn("1").size());
assertEquals(0, cut.transitionOn("2").size());
cut.deletePattern(Patterns.anythingButNumberMatch(
new HashSet<>(Arrays.asList(1.11, 2d))));
for (String notFoo : notFoos) {
assertEquals(1, cut.transitionOn(notFoo).size());
}
assertEquals(1, cut.transitionOn("1.11").size());
assertEquals(0, cut.transitionOn("3.33").size());
assertEquals(1, cut.transitionOn("1").size());
assertEquals(0, cut.transitionOn("2").size());
assertFalse(cut.isEmpty());
cut.deletePattern(Patterns.anythingButNumberMatch(
new HashSet<>(Arrays.asList(3.33, 2d))));
for (String notFoo : notFoos) {
assertEquals(0, cut.transitionOn(notFoo).size());
}
assertEquals(0, cut.transitionOn("1.11").size());
assertEquals(0, cut.transitionOn("3.33").size());
assertEquals(0, cut.transitionOn("1").size());
assertEquals(0, cut.transitionOn("2").size());
assertTrue(cut.isEmpty());
cut.addPattern(Patterns.anythingButNumberMatch(
new HashSet<>(Arrays.asList(3.33, 2d))));
assertEquals(0, cut.transitionOn("2").size());
assertEquals(0, cut.transitionOn("3.33").size());
assertEquals(1, cut.transitionOn("2022").size());
assertEquals(1, cut.transitionOn("400").size());
}
@Test
public void WHEN_MixedPatternsAreAdded_THEN_TheyWork() {
ByteMachine cut = new ByteMachine();
Patterns p = Patterns.exactMatch("foo");
cut.addPattern(p);
p = Patterns.prefixMatch("foo");
cut.addPattern(p);
p = Patterns.anythingButMatch("foo");
cut.addPattern(p);
p = Patterns.numericEquals(3);
cut.addPattern(p);
p = Range.lessThan(3);
cut.addPattern(p);
p = Range.greaterThan(3);
cut.addPattern(p);
p = Range.lessThanOrEqualTo(3);
cut.addPattern(p);
p = Range.greaterThanOrEqualTo(3);
cut.addPattern(p);
p = Range.between(0, false, 8, false);
cut.addPattern(p);
p = Range.between(0, true, 8, true);
cut.addPattern(p);
String[] notFoos = { "bar", "baz", "for", "too", "fro", "fo", "foobar" };
int[] notFooMatches = { 1, 1, 1, 1, 1, 1, 2 };
for (int i = 0; i < notFooMatches.length; i++) {
assertEquals(notFooMatches[i], cut.transitionOn(notFoos[i]).size());
}
assertEquals(2, cut.transitionOn("foo").size());
String[] numbers = { "3", "2.5", "3.5", "0", "8", "-1", "9" };
int[] numMatches = { 6, 5, 5, 4, 4, 3, 3 } ;
for (int i = 0; i < numbers.length; i++) {
assertEquals("numbers[" + i + "]=" + numbers[i], numMatches[i], cut.transitionOn(numbers[i]).size());
}
}
@Test
public void WHEN_AnythingButIsAPrefixOfAnotherPattern_THEN_TheyWork() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.exactMatch("football"));
cut.addPattern(Patterns.anythingButMatch("foo"));
assertEquals(2, cut.transitionOn("football").size());
assertEquals(0, cut.transitionOn("foo").size());
}
@Test
public void WHEN_NumericEQIsRequested_THEN_DifferentNumberSyntaxesMatch() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.numericEquals(300.0));
assertEquals(1, cut.transitionOn("300").size());
assertEquals(1, cut.transitionOn("300.0000").size());
assertEquals(1, cut.transitionOn("3.0e+2").size());
}
@Test
public void RangePatternEqual() {
double[] data = {
1234, 5678.1234, 7890
};
NameState ns = new NameState();
ByteMatch cut = new ByteMatch(Range.lessThan(data[0]), ns);
ByteMatch cc = new ByteMatch(Range.lessThan(data[1]), ns);
ByteMatch s2 = new ByteMatch(Range.lessThan(data[2]), ns);
Range range1 = (Range) cut.getPattern().clone();
Range range2 = (Range) cc.getPattern().clone();
Range range3 = (Range) s2.getPattern().clone();
assertEquals("pattern match range.", range1, cut.getPattern());
assertEquals("pattern match range.", range2, cc.getPattern());
assertEquals("pattern match range.", range3, s2.getPattern());
assertNotSame("pattern object doesn't match range.", range1, (cut.getPattern()));
assertNotSame("pattern object doesn't match range", range2, (cc.getPattern()));
assertNotSame("pattern object doesn't match range", range3, (s2.getPattern()));
}
@Test
public void WHEN_NumericRangesAdded_THEN_TheyWorkCorrectly_THEN_MatchNothing_AFTER_Removed() {
ByteMachine cut = new ByteMachine();
Range r = Range.between(0, true, 4, false);
Range r1 = Range.between(1, true, 3, false);
cut.addPattern(r);
cut.addPattern(r1);
String num = String.format("%f", 2.0);
assertEquals(2, cut.transitionOn(num).size());
cut.deletePattern(r);
assertEquals(1, cut.transitionOn(num).size());
cut.deletePattern(r1);
assertEquals(0, cut.transitionOn(num).size());
assertTrue("byteMachine must be empty after delete pattern", cut.isEmpty());
}
@Test
public void WHEN_NumericRangesAddedMultipleTime_BecomeEmptyWithOneDelete() {
ByteMachine cut = new ByteMachine();
String num = String.format("%f", 2.0);
Range r = Range.between(0, true, 4, false);
Range r1 = (Range) r.clone();
Range r2 = (Range) r1.clone();
Range r3 = (Range) r2.clone();
assertEquals(0, cut.transitionOn(num).size());
cut.addPattern(r);
assertEquals(1, cut.transitionOn(num).size());
cut.addPattern(r1);
cut.addPattern(r2);
assertNotNull("must find the range pattern", cut.findPattern(r1));
assertEquals(cut.findPattern(r1), cut.findPattern(r3));
assertEquals(1, cut.transitionOn(num).size());
cut.deletePattern(r3);
assertEquals(0, cut.transitionOn(num).size());
assertTrue("byteMachine must be empty after delete pattern", cut.isEmpty());
cut.deletePattern(r);
assertTrue("byteMachine must be empty after delete pattern", cut.isEmpty());
}
@Test
public void WHEN_PatternAdded_THEN_ItCouldBeFound_AndReturnNullForOtherPatternSearch() {
// Range pattern
double[] data = {
-Constants.FIVE_BILLION, -4_999_999_999.99999, -4_999_999_999.99998, -4_999_999_999.99997,
-999999999.99999, -999999999.99, -10000, -0.000002,
0, 0.000001, 3.8, 2.5e4, 999999999.999998, 999999999.999999,
4_999_999_999.99997, 4_999_999_999.99998, 4_999_999_999.99999, Constants.FIVE_BILLION
};
ByteMachine cut = new ByteMachine();
Range r = Range.between(0, true, 4, false);
assertNull("must NOT find the range pattern", cut.findPattern(r));
cut.addPattern(r);
assertNotNull("must find the range pattern", cut.findPattern(r));
for (int i = 0; i < 1000; i++) {
for (int j = i + 1; j < 1001; j++) {
if (i == 0 && j == 4) {
assertNotNull("must find the range pattern", cut.findPattern(Range.between(i, true, j, false)));
} else {
assertNull("must NOT find the range pattern", cut.findPattern(Range.between(i, true, j, false)));
}
}
}
for (int i = 1; i < data.length; i++) {
// first: <
assertNull("must NOT find the range pattern", cut.findPattern(Range.lessThan(data[i])));
// <=
assertNull("must NOT find the range pattern", cut.findPattern(Range.lessThanOrEqualTo(data[i])));
}
for (int i = 0; i < data.length-1; i++) {
// >
assertNull("must NOT find the range pattern", cut.findPattern(Range.greaterThan(data[i])));
// >=
assertNull("must NOT find the range pattern", cut.findPattern(Range.greaterThanOrEqualTo(data[i])));
}
for (int i = 0; i < (data.length - 2); i++) {
for (int j = i + 2; j < data.length; j++) {
// open/open range
assertNull("must NOT find the range pattern", cut.findPattern(Range.between(data[i], true, data[j], true)));
// open/closed range
assertNull("must NOT find the range pattern", cut.findPattern(Range.between(data[i], true, data[j], false)));
}
}
for (int i = 0; i < (data.length - 2); i++) {
for (int j = i + 2; j < data.length; j++) {
// overlap range
assertNull("must NOT find the range pattern", cut.findPattern(Range.between(data[i], true, data[j], true)));
}
}
// other pattern
cut.addPattern(Patterns.exactMatch("test"));
cut.addPattern(Patterns.prefixMatch("test"));
cut.addPattern(Patterns.anythingButMatch("test"));
cut.addPattern(Patterns.numericEquals(1.11));
assertNotNull("must find the pattern", cut.findPattern(Patterns.exactMatch("test")));
assertNotNull("must find the pattern", cut.findPattern(Patterns.prefixMatch("test")));
assertNotNull("must find the pattern", cut.findPattern(Patterns.anythingButMatch("test")));
assertNotNull("must find the pattern", cut.findPattern(Patterns.numericEquals(1.11)));
assertNull("must NOT find the pattern", cut.findPattern(Patterns.exactMatch("test1")));
assertNull("must NOT find the pattern", cut.findPattern(Patterns.prefixMatch("test1")));
assertNull("must NOT find the pattern", cut.findPattern(Patterns.anythingButMatch("test1")));
assertNull("must NOT find the pattern", cut.findPattern(Patterns.numericEquals(1.111)));
cut.deletePattern(Patterns.exactMatch("test"));
cut.deletePattern(Patterns.prefixMatch("test"));
cut.deletePattern(Patterns.anythingButMatch("test"));
cut.deletePattern(Patterns.numericEquals(1.11));
cut.deletePattern(Range.between(0, true, 4, false));
assertTrue("cut is empty", cut.isEmpty());
}
@Test
public void whenKeyExistencePatternAdded_itCouldBeFound_AndBecomesEmptyWithOneDelete() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.existencePatterns());
NameState stateFound;
cut.deletePattern(Patterns.existencePatterns());
stateFound = cut.findPattern(Patterns.existencePatterns());
assertNull(stateFound);
assertTrue(cut.isEmpty());
}
@Test
public void testExistencePatternFindsMatch() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.existencePatterns());
Set<NameStateWithPattern> matches = cut.transitionOn("someValue");
assertEquals(1, matches.size());
cut.deletePattern(Patterns.existencePatterns());
assertTrue(cut.isEmpty());
}
@Test
public void testIfExistencePatternIsNotAdded_itDoesNotFindMatch() {
ByteMachine cut = new ByteMachine();
Set<NameStateWithPattern> matches = cut.transitionOn("someValue");
assertEquals(0, matches.size());
assertTrue(cut.isEmpty());
}
@Test
public void testExistencePattern_WithOtherPatterns_workCorrectly() {
ByteMachine cut = new ByteMachine();
String val = "value";
cut.addPattern(Patterns.existencePatterns());
cut.addPattern(Patterns.exactMatch(val));
Set<NameStateWithPattern> matches = cut.transitionOn("anotherValue");
assertEquals(1, matches.size());
matches = cut.transitionOn(val);
assertEquals(2, matches.size());
cut.deletePattern(Patterns.existencePatterns());
matches = cut.transitionOn("anotherValue");
assertEquals(0, matches.size());
matches = cut.transitionOn(val);
assertEquals(1, matches.size());
cut.deletePattern(Patterns.exactMatch(val));
matches = cut.transitionOn(val);
assertEquals(0, matches.size());
}
@Test
public void testNonNumericValue_DoesNotMatchNumericPattern() {
ByteMachine cut = new ByteMachine();
String val = "0A,";
cut.addPattern(Range.greaterThanOrEqualTo(-1e9));
Set<NameStateWithPattern> matches = cut.transitionOn(val);
assertTrue(matches.isEmpty());
}
@Test
public void testExistencePattern_startingWithDesignatedByteString_WithOtherPatterns_workCorrectly() {
ByteMachine cut = new ByteMachine();
String val = "value";
cut.addPattern(Patterns.existencePatterns());
cut.addPattern(Patterns.exactMatch(val));
Set<NameStateWithPattern> matches = cut.transitionOn("NewValue");
assertEquals(1, matches.size());
matches = cut.transitionOn(val);
assertEquals(2, matches.size());
cut.deletePattern(Patterns.existencePatterns());
matches = cut.transitionOn("NewValue");
assertEquals(0, matches.size());
matches = cut.transitionOn(val);
assertEquals(1, matches.size());
cut.deletePattern(Patterns.exactMatch(val));
matches = cut.transitionOn(val);
assertEquals(0, matches.size());
}
@Test
public void WHEN_ShortcutTransAddedAndDeleted_THEN_TheyWorkCorrectly() {
ByteMachine cut = new ByteMachine();
String [] values = {"a", "ab", "abc", "abcd", "a", "ab", "abc", "abcd", "ac", "acb", "aabc", "abcdeffg"};
// add them in ordering, no proxy transition is reburied.
for (String value : values) {
cut.addPattern(Patterns.exactMatch(value));
}
for (String value :values) {
assertEquals(value + " did not have a match", 1, cut.transitionOn(value).size());
}
for (String value : values) {
cut.deletePattern(Patterns.exactMatch(value));
}
assertTrue(cut.isEmpty());
// add them in reverse ordering, there is only one proxy transition existing.
for (int i = values.length-1; i >=0; i--) {
cut.addPattern(Patterns.exactMatch(values[i]));
}
for (String value :values) {
assertEquals(1, cut.transitionOn(value).size());
}
for (String value : values) {
cut.deletePattern(Patterns.exactMatch(value));
}
assertTrue(cut.isEmpty());
String[] copiedValues = values.clone();
for (int t = 50; t > 0; t--) {
//add them in random order, it should work
randomizeArray(copiedValues);
for (int i = values.length - 1; i >= 0; i--) {
cut.addPattern(Patterns.exactMatch(copiedValues[i]));
}
for (String value : values) {
assertEquals(1, cut.transitionOn(value).size());
}
randomizeArray(copiedValues);
for (String value : copiedValues) {
cut.deletePattern(Patterns.exactMatch(value));
}
assertTrue(cut.isEmpty());
}
// test exactly match and prefix together
for (int t = 50; t > 0; t--) {
//add them in random order, it should work
randomizeArray(copiedValues);
// add them in ordering, both exactly match and prefix match
for (String value : copiedValues) {
cut.addPattern(Patterns.exactMatch(value));
}
randomizeArray(copiedValues);
// add them in ordering, both exactly match and prefix match
for (String value : copiedValues) {
cut.addPattern(Patterns.prefixMatch(value));
}
int[] expected = {2, 3, 4, 5, 2, 3, 4, 5, 3, 4, 3, 6};
for (int i = 0; i < values.length; i++) {
assertEquals(expected[i], cut.transitionOn(values[i]).size());
}
randomizeArray(copiedValues);
for (String value : copiedValues) {
cut.deletePattern(Patterns.exactMatch(value));
cut.deletePattern(Patterns.prefixMatch(value));
}
assertTrue(cut.isEmpty());
}
}
private static void randomizeArray(String[] array){
Random rgen = new Random(); // Random number generator
for (int i=0; i<array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
String temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
}
@Test
public void testSuffixPattern() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.suffixMatch("java"));
String[] shouldBeMatched = { "java", ".java", "abc.java", "jjjava", "123java" };
String[] shouldNOTBeMatched = { "vav", "javaa", "xjavax", "foo", "foojaoova" };
for (String foo : shouldBeMatched) {
assertEquals(1, cut.transitionOn(foo).size());
}
for (String notFoo : shouldNOTBeMatched) {
assertEquals(0, cut.transitionOn(notFoo).size());
}
}
@Test
public void testEqualsIgnoreCasePattern() {
String[] noMatches = new String[] { "JAV", "jav", "ava", "AVA", "JAVAx", "javax", "xJAVA", "xjava" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("jAVa"),
"java", "JAVA", "Java", "jAvA", "jAVa", "JaVa")
);
}
@Test
public void testEqualsIgnoreCasePatternWithExactMatchAsPrefix() {
String[] noMatches = new String[] { "", "ja", "JA", "JAV", "javax" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("jAVa"),
"java", "jAVa", "JavA", "JAVA"),
new PatternMatch(Patterns.exactMatch("ja"),
"ja")
);
}
@Test
public void testEqualsIgnoreCasePatternWithExactMatchAsPrefixLengthOneLess() {
String[] noMatches = new String[] { "", "JAV", "javax" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("jAVa"),
"java", "jAVa", "JavA", "JAVA"),
new PatternMatch(Patterns.exactMatch("jav"),
"jav")
);
}
@Test
public void testEqualsIgnoreCasePatternNonLetterCharacters() {
String[] noMatches = new String[] { "", "2#$^sS我ŐaBc", "1#%^sS我ŐaBc", "1#$^sS大ŐaBc", "1#$^sS我ŏaBc" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("1#$^sS我ŐaBc"),
"1#$^sS我ŐaBc", "1#$^Ss我ŐAbC")
);
}
@Test
public void testEqualsIgnoreCaseLowerCaseCharacterWithDifferentByteLengthForUpperCase() {
String[] noMatches = new String[] { "", "12a34", "12A34" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("12ⱥ34"),
"12ⱥ34", "12Ⱥ34")
);
}
@Test
public void testEqualsIgnoreCaseUpperCaseCharacterWithDifferentByteLengthForLowerCase() {
String[] noMatches = new String[] { "", "12a34", "12A34" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("12Ⱥ34"),
"12ⱥ34", "12Ⱥ34")
);
}
@Test
public void testEqualsIgnoreCaseLowerCaseCharacterWithDifferentByteLengthForUpperCaseAtStartOfString() {
String[] noMatches = new String[] { "", "a12", "A12" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("ⱥ12"),
"ⱥ12", "Ⱥ12")
);
}
@Test
public void testEqualsIgnoreCaseUpperCaseCharacterWithDifferentByteLengthForLowerCaseAtStartOfString() {
String[] noMatches = new String[] { "", "a12", "A12" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("Ⱥ12"),
"ⱥ12", "Ⱥ12")
);
}
@Test
public void testEqualsIgnoreCaseLowerCaseCharacterWithDifferentByteLengthForUpperCaseAtEndOfString() {
String[] noMatches = new String[] { "", "12a", "12A" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("12ⱥ"),
"12ⱥ", "12Ⱥ")
);
}
@Test
public void testEqualsIgnoreCaseUpperCaseCharacterWithDifferentByteLengthForLowerCaseAtEndOfString() {
String[] noMatches = new String[] { "", "12a", "12A" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("12Ⱥ"),
"12ⱥ", "12Ⱥ")
);
}
@Test
public void testEqualsIgnoreCaseManyCharactersWithDifferentByteLengthForLowerCaseAndUpperCase() {
String[] noMatches = new String[] { "", "Ϋ́ȿⱯΐΫ́Η͂k", "ΰⱾɐΪ́ΰῆK" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("ΰɀɐΐΰῆK"),
"Ϋ́ɀⱯΐΫ́Η͂k", "ΰⱿɐΪ́ΰῆK", "Ϋ́ⱿⱯΪ́Ϋ́ῆk", "ΰɀɐΐΰΗ͂K")
);
}
@Test
public void testEqualsIgnoreCaseMiddleCharacterWithDifferentByteLengthForLowerCaseAndUpperCaseWithPrefixMatches() {
String[] noMatches = new String[] { "", "a", "aa" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("abȺcd"),
"abⱥcd", "abȺcd"),
new PatternMatch(Patterns.prefixMatch("ab"),
"ab", "abⱥ", "abȺ", "abⱥcd", "abȺcd"),
new PatternMatch(Patterns.prefixMatch("abⱥ"),
"abⱥ", "abⱥcd"),
new PatternMatch(Patterns.prefixMatch("abȺ"),
"abȺ", "abȺcd")
);
}
@Test
public void testEqualsIgnoreCaseLastCharacterWithDifferentByteLengthForLowerCaseAndUpperCaseWithPrefixMatches() {
String[] noMatches = new String[] { "", "ab" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("abcȺ"),
"abcⱥ", "abcȺ"),
new PatternMatch(Patterns.prefixMatch("abc"),
"abc", "abca", "abcA", "abcⱥ", "abcȺ"),
new PatternMatch(Patterns.prefixMatch("abca"),
"abca"),
new PatternMatch(Patterns.prefixMatch("abcA"),
"abcA")
);
}
@Test
public void testEqualsIgnoreCaseFirstCharacterWithDifferentByteLengthForCasesWithLowerCasePrefixMatch() {
String[] noMatches = new String[] { "", "ⱥ", "Ⱥ", "c" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("ⱥc"),
"ⱥc", "Ⱥc"),
new PatternMatch(Patterns.prefixMatch("ⱥc"),
"ⱥc", "ⱥcd")
);
}
@Test
public void testEqualsIgnoreCaseFirstCharacterWithDifferentByteLengthForCasesWithUpperCasePrefixMatch() {
String[] noMatches = new String[] { "", "ⱥ", "Ⱥ", "c" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("Ⱥc"),
"ⱥc", "Ⱥc"),
new PatternMatch(Patterns.prefixMatch("Ⱥc"),
"Ⱥc", "Ⱥcd")
);
}
@Test
public void testEqualsIgnoreCaseWhereLowerAndUpperCaseAlreadyExist() {
String[] noMatches = new String[] { "", "a", "b" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixMatch("ab"),
"ab", "abc", "abC"),
new PatternMatch(Patterns.prefixMatch("AB"),
"AB", "ABC", "ABc"),
new PatternMatch(Patterns.equalsIgnoreCaseMatch("ab"),
"ab", "AB", "Ab", "aB")
);
}
@Test
public void testEqualsIgnoreCasePatternMultipleWithMultipleExactMatch() {
String[] noMatches = new String[] { "", "he", "HEL", "hell", "HELL", "helloxx" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("hElLo"),
"hello", "HELLO", "HeLlO", "hElLo"),
new PatternMatch(Patterns.equalsIgnoreCaseMatch("HeLlOX"),
"hellox", "HELLOX", "HeLlOx", "hElLoX"),
new PatternMatch(Patterns.exactMatch("hello"),
"hello"),
new PatternMatch(Patterns.exactMatch("HELLO"),
"HELLO"),
new PatternMatch(Patterns.exactMatch("hel"),
"hel")
);
}
@Test
public void testEqualsIgnoreCaseWithExactMatchLeadingCharacterSameLowerAndUpperCase() {
String[] noMatches = new String[] { "", "!", "!A", "a", "A", "b", "B" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.equalsIgnoreCaseMatch("!b"),
"!b", "!B"),
new PatternMatch(Patterns.exactMatch("!a"),
"!a")
);
}
@Test
public void testPrefixEqualsIgnoreCasePattern() {
String[] noMatches = new String[] { "", "JAV", "jav", "ava", "AVA", "xJAVA", "xjava", "jAV", "AVa" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("jAVa"),
"java", "JAVA", "Java", "jAvA", "jAVa", "JaVa", "JAVAx", "javax", "JaVaaaaaaa")
);
}
@Test
public void testPrefixEqualsIgnoreCasePatternWithExactMatchAsPrefix() {
String[] noMatches = new String[] { "", "jA", "Ja", "JAV", "jav", "ava", "AVA", "xJAVA", "xjava", "jAV", "AVa" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("jAVa"),
"java", "JAVA", "Java", "jAvA", "jAVa", "JaVa", "JAVAx", "javax", "JaVaaaaaaa"),
new PatternMatch(Patterns.exactMatch("ja"),
"ja")
);
}
@Test
public void testPrefixEqualsIgnoreCasePatternWithExactMatchAsPrefixLengthOneLess() {
String[] noMatches = new String[] { "", "JAV" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("jAVa"),
"java", "jAVa", "JavA", "JAVA", "javax"),
new PatternMatch(Patterns.exactMatch("jav"),
"jav")
);
}
@Test
public void testPrefixEqualsIgnoreCasePatternNonLetterCharacters() {
String[] noMatches = new String[] { "", "2#$^sS我ŐaBc", "1#%^sS我ŐaBc", "1#$^sS大ŐaBc", "1#$^sS我ŏaBc" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("1#$^sS我ŐaBc"),
"1#$^sS我ŐaBcd", "1#$^Ss我ŐAbCaaaaa", "1#$^Ss我ŐAbC我")
);
}
@Test
public void testPrefixEqualsIgnoreCaseLowerCaseCharacterWithDifferentByteLengthForUpperCase() {
String[] noMatches = new String[] { "", "12a34", "12A34" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("12ⱥ34"),
"12ⱥ34", "12Ⱥ34", "12ⱥ3478", "12Ⱥ34aa", "12Ⱥ34ȺȺ")
);
}
@Test
public void testPrefixEqualsIgnoreCaseUpperCaseCharacterWithDifferentByteLengthForLowerCase() {
String[] noMatches = new String[] { "", "12a34", "12A34" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("12Ⱥ34"),
"12ⱥ34", "12Ⱥ34", "12ⱥ3478", "12Ⱥ34aa", "12Ⱥ34ⱥȺ")
);
}
@Test
public void testPrefixEqualsIgnoreCaseLowerCaseCharacterWithDifferentByteLengthForUpperCaseAtStartOfString() {
String[] noMatches = new String[] { "", "a12", "A12" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("ⱥ12"),
"ⱥ12", "Ⱥ12", "ⱥ1234", "Ⱥ12ab", "ⱥ12ⱥⱥ", "Ⱥ12ⱥⱥ")
);
}
@Test
public void testPrefixEqualsIgnoreCaseUpperCaseCharacterWithDifferentByteLengthForLowerCaseAtStartOfString() {
String[] noMatches = new String[] { "", "a12", "A12" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("Ⱥ12"),
"ⱥ12", "Ⱥ12", "ⱥ1234", "Ⱥ12ab", "ⱥ12ⱥⱥ", "Ⱥ12ⱥⱥ")
);
}
@Test
public void testPrefixEqualsIgnoreCaseLowerCaseCharacterWithDifferentByteLengthForUpperCaseAtEndOfString() {
String[] noMatches = new String[] { "", "12a", "12A" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("12ⱥ"),
"12ⱥ", "12Ⱥ", "12ⱥⱥⱥⱥⱥ", "12ȺȺȺȺ", "12ȺⱥⱥȺⱥⱥȺ")
);
}
@Test
public void testPrefixEqualsIgnoreCaseUpperCaseCharacterWithDifferentByteLengthForLowerCaseAtEndOfString() {
String[] noMatches = new String[] { "", "12a", "12A" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("12Ⱥ"),
"12ⱥ", "12Ⱥ", "12ⱥⱥⱥⱥⱥ", "12ȺȺȺȺ", "12ȺⱥⱥȺⱥⱥȺ")
);
}
@Test
public void testPrefixEqualsIgnoreCaseManyCharactersWithDifferentByteLengthForLowerCaseAndUpperCase() {
String[] noMatches = new String[] { "", "Ϋ́ȿⱯΐΫ́Η͂k", "ΰⱾɐΪ́ΰῆK" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("ΰɀɐΐΰῆK"),
"Ϋ́ɀⱯΐΫ́Η͂k", "ΰⱿɐΪ́ΰῆK", "Ϋ́ⱿⱯΪ́Ϋ́ῆk", "ΰɀɐΐΰΗ͂K", "Ϋ́ɀⱯΐΫ́Η͂kÄ́ɀⱯΐΫ́Η͂", "ΰⱿɐΪ́ΰῆKä́ɀⱯΐΫ́Η͂")
);
}
@Test
public void testPrefixEqualsIgnoreCaseMiddleCharacterWithDifferentByteLengthForLowerCaseAndUpperCaseWithPrefixMatches() {
String[] noMatches = new String[] { "", "a", "aa" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("abȺcd"),
"abⱥcd", "abȺcd", "abⱥcdea", "abȺcdCCC"),
new PatternMatch(Patterns.prefixMatch("ab"),
"ab", "abⱥ", "abȺ", "abⱥcd", "abȺcd", "abⱥcdea", "abȺcdCCC"),
new PatternMatch(Patterns.prefixMatch("abⱥ"),
"abⱥ", "abⱥcd", "abⱥcdea"),
new PatternMatch(Patterns.prefixMatch("abȺ"),
"abȺ", "abȺcd", "abȺcdCCC")
);
}
@Test
public void testPrefixEqualsIgnoreCaseLastCharacterWithDifferentByteLengthForLowerCaseAndUpperCaseWithPrefixMatches() {
String[] noMatches = new String[] { "", "ab" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("abcȺ"),
"abcⱥ", "abcȺ", "abcⱥaa", "abcȺbb"),
new PatternMatch(Patterns.prefixMatch("abc"),
"abc", "abca", "abcA", "abcⱥ", "abcȺ", "abcⱥaa", "abcȺbb"),
new PatternMatch(Patterns.prefixMatch("abca"),
"abca"),
new PatternMatch(Patterns.prefixMatch("abcA"),
"abcA")
);
}
@Test
public void testPrefixEqualsIgnoreCaseFirstCharacterWithDifferentByteLengthForCasesWithLowerCasePrefixMatch() {
String[] noMatches = new String[] { "", "ⱥ", "Ⱥ", "c" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("ⱥc"),
"ⱥc", "Ⱥc", "ⱥcd"),
new PatternMatch(Patterns.prefixMatch("ⱥc"),
"ⱥc", "ⱥcd")
);
}
@Test
public void testPrefixEqualsIgnoreCaseFirstCharacterWithDifferentByteLengthForCasesWithUpperCasePrefixMatch() {
String[] noMatches = new String[] { "", "ⱥ", "Ⱥ", "c" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("Ⱥc"),
"ⱥc", "Ⱥc", "ⱥcdddd", "Ⱥcd"),
new PatternMatch(Patterns.prefixMatch("Ⱥc"),
"Ⱥc", "Ⱥcd")
);
}
@Test
public void testPrefixEqualsIgnoreCaseWhereLowerAndUpperCaseAlreadyExist() {
String[] noMatches = new String[] { "", "a", "b" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixMatch("ab"),
"ab", "abc", "abC"),
new PatternMatch(Patterns.prefixMatch("AB"),
"AB", "ABC", "ABc"),
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("ab"),
"ab", "AB", "Ab", "aB", "ab", "abc", "abC", "AB", "ABC", "ABc")
);
}
@Test
public void testPrefixEqualsIgnoreCasePatternMultipleWithMultipleExactMatch() {
String[] noMatches = new String[] { "", "he", "HEL", "hell", "HELL"};
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("hElLo"),
"hello", "hellox", "HeLlOx", "hElLoX", "HELLOX", "HELLO", "HeLlO", "hElLo"),
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("HeLlOX"),
"hellox", "HELLOX", "HeLlOx", "hElLoX"),
new PatternMatch(Patterns.exactMatch("hello"),
"hello"),
new PatternMatch(Patterns.exactMatch("HELLO"),
"HELLO"),
new PatternMatch(Patterns.exactMatch("hel"),
"hel")
);
}
@Test
public void testPrefixEqualsIgnoreCasePatternMultipleWithMultipleEqualsIgnoreCaseMatch() {
String[] noMatches = new String[] { "", "he", "hell", "HELL" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("hElLo"),
"hello", "hellox", "HELLOX", "HeLlOx", "hElLoX", "helloxx"),
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("HeLlOX"),
"hellox", "HELLOX", "HeLlOx", "hElLoX", "helloxx"),
new PatternMatch(Patterns.equalsIgnoreCaseMatch("hello"),
"hello"),
new PatternMatch(Patterns.equalsIgnoreCaseMatch("hel"),
"hel", "HEL")
);
}
@Test
public void testPrefixEqualsIgnoreCaseWithExactMatchLeadingCharacterSameLowerAndUpperCase() {
String[] noMatches = new String[] { "", "!", "!A", "a", "A", "b", "B" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("!b"),
"!b", "!B", "!bcd", "!BCdE"),
new PatternMatch(Patterns.exactMatch("!a"),
"!a")
);
}
@Test
public void testPrefixEqualsIgnoreCaseWithPrefixMatchLeadingCharacterSameLowerAndUpperCase() {
String[] noMatches = new String[] { "", "!", "!A", "a", "A", "b", "B" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("!b"),
"!b", "!B", "!bcd", "!BCdE"),
new PatternMatch(Patterns.prefixMatch("!a"),
"!a")
);
}
@Test
public void testSuffixEqualsIgnoreCasePattern() {
String[] noMatches = new String[] { "", "JAV", "jav", "ava", "AVA", "JAVAx", "javax", "jAV", "AVa" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("jAVa"),
"java", "JAVA", "Java", "jAvA", "jAVa", "JaVa", "helloJAVA", "hijava", "jjjjjjJaVa")
);
}
@Test
public void testSuffixEqualsIgnoreCasePatternWithReverseExactMatchAsSuffix() {
String[] noMatches = new String[] { "", "jA", "Ja", "JAV", "jav", "ava", "AVA", "JAVAx", "javax", "jAV", "AVa" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("jAVa"),
"java", "JAVA", "Java", "jAvA", "jAVa", "JaVa", "xJAVA", "xjava", "jjJJJJaVa"),
new PatternMatch(Patterns.exactMatch("av"),
"av")
);
}
@Test
public void testSuffixEqualsIgnoreCasePatternWithReverseExactMatchAsSuffixLengthOneLess() {
String[] noMatches = new String[] { "", "JAV" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("jAVa"),
"java", "jAVa", "JavA", "JAVA", "xjava"),
new PatternMatch(Patterns.exactMatch("ava"),
"ava")
);
}
@Test
public void testSuffixEqualsIgnoreCasePatternNonLetterCharacters() {
String[] noMatches = new String[] { "", "1#$^sS我ŐaBd", "1#%^sS我ŐaBc", "1#$^sS大ŐaBc", "1#$^sS我ŏaBc" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("1#$^sS我ŐaBc"),
"aa1#$^sS我ŐaBc", "1111#$^Ss我ŐAbC", "我我1#$^Ss我ŐAbC")
);
}
@Test
public void testSuffixEqualsIgnoreCaseLowerCaseCharacterWithDifferentByteLengthForUpperCase() {
String[] noMatches = new String[] { "", "12a34", "12A34" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("12ⱥ34"),
"12ⱥ34", "12Ⱥ34", "7812ⱥ34", "aa12Ⱥ34", "ȺȺ12Ⱥ34")
);
}
@Test
public void testSuffixEqualsIgnoreCaseUpperCaseCharacterWithDifferentByteLengthForLowerCase() {
String[] noMatches = new String[] { "", "12a34", "12A34" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("12Ⱥ34"),
"12ⱥ34", "12Ⱥ34", "7812ⱥ34", "aa12Ⱥ34", "ⱥȺ12Ⱥ34")
);
}
@Test
public void testSuffixEqualsIgnoreCaseLowerCaseCharacterWithDifferentByteLengthForUpperCaseAtStartOfString() {
String[] noMatches = new String[] { "", "a12", "A12" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("ⱥ12"),
"ⱥ12", "Ⱥ12", "34ⱥ12", "abȺ12", "ⱥⱥⱥ12", "ⱥⱥȺ12")
);
}
@Test
public void testSuffixEqualsIgnoreCaseUpperCaseCharacterWithDifferentByteLengthForLowerCaseAtStartOfString() {
String[] noMatches = new String[] { "", "a12", "A12" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("Ⱥ12"),
"ⱥ12", "Ⱥ12", "34ⱥ12", "abȺ12", "ⱥⱥⱥ12", "ⱥⱥȺ12")
);
}
@Test
public void testSuffixEqualsIgnoreCaseLowerCaseCharacterWithDifferentByteLengthForUpperCaseAtEndOfString() {
String[] noMatches = new String[] { "", "12a", "12A" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("12ⱥ"),
"12ⱥ", "12Ⱥ", "ⱥⱥⱥⱥ12ⱥ", "ȺȺȺ12Ⱥ", "ⱥⱥȺⱥⱥȺ12Ⱥ")
);
}
@Test
public void testSuffixEqualsIgnoreCaseUpperCaseCharacterWithDifferentByteLengthForLowerCaseAtEndOfString() {
String[] noMatches = new String[] { "", "12a", "12A" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("12Ⱥ"),
"12ⱥ", "12Ⱥ", "ⱥⱥⱥⱥ12ⱥ", "ȺȺȺ12Ⱥ", "ⱥⱥȺⱥⱥȺ12Ⱥ")
);
}
@Test
public void testSuffixEqualsIgnoreCaseManyCharactersWithDifferentByteLengthForLowerCaseAndUpperCase() {
String[] noMatches = new String[] { "", "Ϋ́ȿⱯΐΫ́Η͂k", "ΰⱾɐΪ́ΰῆK" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("ΰɀɐΐΰῆK"),
"Ϋ́ɀⱯΐΫ́Η͂k", "ΰⱿɐΪ́ΰῆK", "Ϋ́ⱿⱯΪ́Ϋ́ῆk", "ΰɀɐΐΰΗ͂K", "Ä́ɀⱯΐΫ́Η͂Ϋ́ɀⱯΐΫ́Η͂k", "ä́ɀⱯΐΫ́Η͂ΰⱿɐΪ́ΰῆK")
);
}
@Test
public void testSuffixEqualsIgnoreCaseMiddleCharacterWithDifferentByteLengthForLowerCaseAndUpperCaseWithSuffixMatches() {
String[] noMatches = new String[] { "", "a", "aa" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("abȺcd"),
"abⱥcd", "abȺcd", "eaabⱥcd", "CCCabȺcd"),
new PatternMatch(Patterns.suffixMatch("cd"),
"cd", "ⱥcd", "Ⱥcd", "abⱥcd", "abȺcd", "abⱥcd", "eaabⱥcd", "CCCabȺcd"),
new PatternMatch(Patterns.suffixMatch("ⱥcd"),
"ⱥcd", "abⱥcd", "eaabⱥcd"),
new PatternMatch(Patterns.suffixMatch("Ⱥcd"),
"Ⱥcd", "abȺcd", "CCCabȺcd")
);
}
@Test
public void testSuffixEqualsIgnoreCaseLastCharacterWithDifferentByteLengthForLowerCaseAndUpperCaseWithSuffixMatches() {
String[] noMatches = new String[] { "", "ab" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("abcȺ"),
"abcⱥ", "abcȺ", "AbcȺ", "aaabcⱥ", "bbabcȺ"),
new PatternMatch(Patterns.suffixMatch("bcȺ"),
"bcȺ", "abcȺ", "AbcȺ", "ⱥbcȺ", "bbabcȺ"),
new PatternMatch(Patterns.suffixMatch("abca"),
"abca"),
new PatternMatch(Patterns.suffixMatch("abcA"),
"abcA")
);
}
@Test
public void testSuffixEqualsIgnoreCaseFirstCharacterWithDifferentByteLengthForCasesWithLowerCaseSuffixMatch() {
String[] noMatches = new String[] { "", "ⱥ", "Ⱥ", "c" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("ⱥc"),
"ⱥc", "Ⱥc", "dⱥc"),
new PatternMatch(Patterns.suffixMatch("ⱥc"),
"ⱥc", "dⱥc")
);
}
@Test
public void testSuffixEqualsIgnoreCaseFirstCharacterWithDifferentByteLengthForCasesWithUpperCaseSuffixMatch() {
String[] noMatches = new String[] { "", "ⱥ", "Ⱥ", "c" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("Ⱥc"),
"ⱥc", "Ⱥc", "ddddⱥc", "dȺc"),
new PatternMatch(Patterns.suffixMatch("Ⱥc"),
"Ⱥc", "dȺc")
);
}
@Test
public void testSuffixEqualsIgnoreCaseWhereLowerAndUpperCaseAlreadyExist() {
String[] noMatches = new String[] { "", "a", "b" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixMatch("ab"),
"ab", "cab", "Cab"),
new PatternMatch(Patterns.suffixMatch("AB"),
"AB", "CAB", "cAB"),
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("ab"),
"ab", "AB", "Ab", "aB", "ab", "cab", "Cab", "AB", "CAB", "cAB")
);
}
@Test
public void testSuffixEqualsIgnoreCasePatternMultipleWithMultipleExactMatch() {
String[] noMatches = new String[] { "", "he", "HEL", "hell", "HELL"};
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("hElLo"),
"hello", "xhello", "xHeLlO", "XhElLo", "XHELLO", "HELLO", "HeLlO", "hElLo"),
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("XHeLlO"),
"xhello", "XHELLO", "xHeLlO", "XhElLo"),
new PatternMatch(Patterns.exactMatch("hello"),
"hello"),
new PatternMatch(Patterns.exactMatch("HELLO"),
"HELLO"),
new PatternMatch(Patterns.exactMatch("hel"),
"hel")
);
}
@Test
public void testSuffixEqualsIgnoreCasePatternMultipleWithMultipleEqualsIgnoreCaseMatch() {
String[] noMatches = new String[] { "", "he", "hell", "HELL" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("hElLo"),
"hello", "xhello", "XHELLO", "xHeLlO", "XhElLo", "xxhello"),
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("XHeLlO"),
"xhello", "XHELLO", "xHeLlO", "XhElLo", "xxhello"),
new PatternMatch(Patterns.equalsIgnoreCaseMatch("hello"),
"hello"),
new PatternMatch(Patterns.equalsIgnoreCaseMatch("hel"),
"hel", "HEL")
);
}
@Test
public void testSuffixEqualsIgnoreCaseWithExactMatchLeadingCharacterSameLowerAndUpperCase() {
String[] noMatches = new String[] { "", "!", "!A", "a", "A", "b", "B" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("b!"),
"b!", "B!", "cdb!", "CdEB!"),
new PatternMatch(Patterns.exactMatch("!a"),
"!a")
);
}
@Test
public void testSuffixEqualsIgnoreCaseWithPrefixMatchLeadingCharacterSameLowerAndUpperCase() {
String[] noMatches = new String[] { "", "!", "!A", "a", "A", "b", "B" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixMatch("!b"),
"!b"),
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("b!"),
"b!", "B!", "cdb!", "CdEB!"),
new PatternMatch(Patterns.prefixMatch("!a"),
"!a")
);
}
@Test
public void testSuffixEqualsIgnoreCaseWithWildcardMatchBeingAddedLater() {
String[] noMatches = new String[] { "", "!", "!A", "a", "A", "b", "B" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("b!"),
"b!", "B!", "cdb!", "CdEB!"),
new PatternMatch(Patterns.wildcardMatch("*b"),
"!b", "b")
);
}
@Test
public void testSuffixEqualsIgnoreCaseWithExistingWildcardMatch() {
String[] noMatches = new String[] { "", "!", "!A", "a", "A", "b", "B" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("*b"),
"!b", "b"),
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("b!"),
"b!", "B!", "cdb!", "CdEB!")
);
}
@Test
public void testSuffixEqualsIgnoreCaseWithPrefixEqualsIgnoreCaseMatchBeingAddedLater() {
String[] noMatches = new String[] { "", "ab", "bcȺ", "bcⱥ" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("abcȺ"),
"abcⱥ", "abcȺ", "AbcȺ", "aaabcⱥ", "bbabcȺ", "ⱥcbaabcȺ", "ⱥcbaabcⱥ"),
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("Ⱥcba"),
"ⱥcba", "Ⱥcba", "Ⱥcba", "ⱥcbaaa", "Ⱥcbabb", "ⱥcbaabcȺ", "ⱥcbaabcⱥ"),
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("abcȺ"),
"abcⱥ", "abcȺ", "AbcȺ", "abcⱥaa", "abcȺbb")
);
}
@Test
public void testSuffixEqualsIgnoreCaseWithExistingPrefixEqualsIgnoreCaseMatch() {
String[] noMatches = new String[] { "", "ab", "bcȺ", "bcⱥ" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("Ⱥcba"),
"ⱥcba", "Ⱥcba", "Ⱥcba", "ⱥcbaaa", "Ⱥcbabb", "ⱥcbaabcȺ", "ⱥcbaabcⱥ"),
new PatternMatch(Patterns.prefixEqualsIgnoreCaseMatch("abcȺ"),
"abcⱥ", "abcȺ", "AbcȺ", "abcⱥaa", "abcȺbb"),
new PatternMatch(Patterns.suffixEqualsIgnoreCaseMatch("abcȺ"),
"abcⱥ", "abcȺ", "AbcȺ", "aaabcⱥ", "bbabcȺ", "ⱥcbaabcȺ", "ⱥcbaabcⱥ")
);
}
@Test
public void testWildcardSingleWildcardCharacter() {
testPatternPermutations(
new PatternMatch(Patterns.wildcardMatch("*"),
"", "*", "h", "hello")
);
}
@Test
public void testWildcardLeadingWildcardCharacter() {
String[] noMatches = new String[] { "", "ello", "hellx", "xhellx", "hell5rHGGHo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("*hello"),
"hello", "hhello", "xxxhello", "*hello", "23Őzhello")
);
}
@Test
public void testWildcardNormalPositionWildcardCharacter() {
String[] noMatches = new String[] { "", "hlo", "hll", "hellol", "hel5rHGGHlo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*llo"),
"hllo", "hello", "hxxxllo", "hel23Őzlllo")
);
}
@Test
public void testWildcardSecondLastCharWildcardCharacter() {
String[] noMatches = new String[] { "", "hell", "helox", "hellox", "hel5rHGGHe" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hel*o"),
"helo", "hello", "helxxxo", "hel23Őzlllo")
);
}
@Test
public void testWildcardTrailingWildcardCharacter() {
String[] noMatches = new String[] { "", "hell", "hellx", "hellxo", "hol5rHGGHo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hello*"),
"hello", "hellox", "hellooo", "hello*", "hello23Őzlllo")
);
}
@Test
public void testWildcardMultipleWildcardCharacters() {
String[] noMatches = new String[] { "", "ho", "heeo", "helx", "llo", "hex5rHGGHo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*l*o"),
"hlo", "helo", "hllo", "hloo", "hello", "hxxxlxxxo", "h*l*o", "hel*o", "h*llo", "hel23Őzlllo")
);
}
@Test
public void testWildcardLastCharAndThirdLastCharWildcardCharacters() {
String[] noMatches = new String[] { "", "he", "hex", "hexxx" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*l*"),
"hel", "hexl", "helx", "helxx", "helxl", "helxlx", "helxxl", "helxxlxx", "helxxlxxl")
);
}
@Test
public void testWildcardLastCharAndThirdLastCharWildcardCharactersForStringOfLengthThree() {
String[] noMatches = new String[] { "", "x", "xx", "xtx" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("*l*"),
"l", "xl", "lx", "xlx", "xxl", "lxx", "xxlxx", "xlxlxlxlxl", "lxlxlxlxlx")
);
}
@Test
public void testWildcardEscapedAsterisk() {
String[] noMatches = new String[] { "helo", "hello" };
testPatternPermutations(noMatches,
// Only one backslash in the actual string. Need to escape the backslash for Java compiler.
new PatternMatch(Patterns.wildcardMatch("hel\\*o"),
"hel*o")
);
}
@Test
public void testWildcardEscapedAsteriskFollowedByWildcard() {
String[] noMatches = new String[] { "heo", "helo", "hello", "he*l" };
testPatternPermutations(noMatches,
// Only one backslash in the actual string. Need to escape the backslash for Java compiler.
new PatternMatch(Patterns.wildcardMatch("he\\**o"),
"he*o", "he*llo", "he*hello")
);
}
@Test
public void testWildcardEscapedBackslash() {
String[] noMatches = new String[] { "hello", "he\\\\llo" };
testPatternPermutations(noMatches,
// Only two backslashes in the actual string. Need to escape the backslashes for Java compiler.
new PatternMatch(Patterns.wildcardMatch("he\\\\llo"),
"he\\llo")
);
}
@Test
public void testWildcardEscapedBackslashFollowedByEscapedAsterisk() {
String[] noMatches = new String[] { "hello", "he\\\\llo", "he\\llo", "he\\xxllo" };
testPatternPermutations(noMatches,
// Only three backslashes in the actual string. Need to escape the backslashes for Java compiler.
new PatternMatch(Patterns.wildcardMatch("he\\\\\\*llo"),
"he\\*llo")
);
}
@Test
public void testWildcardEscapedBackslashFollowedByWildcard() {
String[] noMatches = new String[] { "hello", "he\\ll" };
testPatternPermutations(noMatches,
// Only two backslashes in the actual string. Need to escape the backslashes for Java compiler.
new PatternMatch(Patterns.wildcardMatch("he\\\\*llo"),
"he\\llo", "he\\*llo", "he\\\\llo", "he\\\\\\llo", "he\\xxllo")
);
}
@Test
public void testWildcardInvalidEscapeCharacter() {
try {
new ByteMachine().addPattern(Patterns.wildcardMatch("he\\llo"));
fail("Expected ParseException");
} catch (ParseException e) {
assertEquals("Invalid escape character at pos 2", e.getMessage());
}
}
@Test
public void testWildcardSingleBackslashAllowedByExactMatch() {
String[] noMatches = new String[] { "hello", "he\\\\llo" };
testPatternPermutations(noMatches,
// Only one backslash in the actual string. Need to escape the backslash for Java compiler.
new PatternMatch(Patterns.exactMatch("he\\llo"),
"he\\llo")
);
}
@Test
public void testWildcardSingleWildcardCharacterWithOtherPatterns() {
testPatternPermutations(
new PatternMatch(Patterns.wildcardMatch("*"),
"", "*", "h", "ho", "hello"),
new PatternMatch(Patterns.wildcardMatch("h*o"),
"ho", "hello"),
new PatternMatch(Patterns.exactMatch("hello"),
"hello")
);
}
@Test
public void testWildcardLeadingWildcardCharacterNotUsedByExactMatch() {
String[] noMatches = new String[] { "", "hello", "hellox", "blahabc" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("*hello"),
"hello", "xhello", "hehello"),
new PatternMatch(Patterns.exactMatch("abc"),
"abc")
);
}
@Test
public void testWildcardTwoPatternsFirstLeadingSecondNormalPositionAdjacent() {
String[] noMatches = new String[] { "", "h", "ello", "hel", "hlo", "hell" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("*hello"),
"hello", "xhello", "hehello"),
new PatternMatch(Patterns.wildcardMatch("h*llo"),
"hllo", "hello", "hehello")
);
}
@Test
public void testWildcardTwoPatternsFirstLeadingSecondNormalPositionNonAdjacent() {
String[] noMatches = new String[] { "", "h", "ello", "hel", "heo", "hell" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("*hello"),
"hello", "xhello", "hehello"),
new PatternMatch(Patterns.wildcardMatch("he*lo"),
"helo", "hello", "hehello")
);
}
@Test
public void testWildcardTwoPatternsFirstLeadingSecondLastCharAndThirdLastCharAdjacent() {
String[] noMatches = new String[] { "", "e", "l", "lo", "hel" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("*elo"),
"elo", "helo", "xhelo"),
new PatternMatch(Patterns.wildcardMatch("e*l*"),
"el", "elo", "exl", "elx", "exlx", "exxl", "elxx", "exxlxx")
);
}
@Test
public void testWildcardTwoPatternsFirstLeadingSecondLastCharAndThirdLastCharNonAdjacent() {
String[] noMatches = new String[] { "", "he", "hexxo", "ello" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("*hello"),
"hello", "xhello", "xxhello"),
new PatternMatch(Patterns.wildcardMatch("he*l*"),
"hel", "hello", "helo", "hexl", "hexlx", "hexxl", "helxx", "hexxlxx")
);
}
@Test
public void testWildcardTwoPatternsFirstNormalPositionSecondNormalPositionAdjacent() {
String[] noMatches = new String[] { "", "hlo", "heo", "hllol", "helol" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*llo"),
"hllo", "hello", "hxxxllo", "hexxxllo"),
new PatternMatch(Patterns.wildcardMatch("he*lo"),
"helo", "hello", "hexxxlo", "hexxxllo")
);
}
@Test
public void testWildcardTwoPatternsFirstNormalPositionSecondNormalPositionNonAdjacent() {
String[] noMatches = new String[] { "", "hlox", "hllo", "helo", "heox", "helx", "hellx", "helloxx", "heloxx" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*llox"),
"hllox", "hellox", "hxxxllox", "helhllox", "hheloxllox"),
new PatternMatch(Patterns.wildcardMatch("hel*ox"),
"helox", "hellox", "helxxxox", "helhllox", "helhlloxox")
);
}
@Test
public void testWildcardTwoPatternsFirstNormalPositionSecondLastCharAndThirdLastCharAdjacent() {
String[] noMatches = new String[] { "", "h", "he", "hl", "el", "hlo", "llo", "hllol", "hxll", "hexxx" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*llo"),
"hllo", "hello", "hxxxllo", "hexxxllo", "hexxxlllo"),
new PatternMatch(Patterns.wildcardMatch("he*l*"),
"hel", "helo", "hexl", "hello", "helol", "hexxxlo", "hexxxllo", "hexxxlllo")
);
}
@Test
public void testWildcardTwoPatternsFirstNormalPositionSecondLastCharAndThirdLastCharNonAdjacent() {
String[] noMatches = new String[] { "", "h", "hex", "hl", "exl", "hxlo", "xllo", "hxllol", "hxxll", "hexxx" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*xllo"),
"hxllo", "hexllo", "hxxxllo", "hexxxllo"),
new PatternMatch(Patterns.wildcardMatch("hex*l*"),
"hexl", "hexlo", "hexxl", "hexllo", "hexlol", "hexxxlo", "hexxxllo", "hexxxlllo")
);
}
@Test
public void testWildcardTwoPatternsFirstNormalPositionSecondSecondLastCharAdjacent() {
String[] noMatches = new String[] { "", "hel", "heo", "hlo", "hellxox" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*lo"),
"helo", "hello", "hexxxlo", "helxxxlo"),
new PatternMatch(Patterns.wildcardMatch("hel*o"),
"helo", "hello", "hellxo", "helxxxo", "helxxxlo")
);
}
@Test
public void testWildcardTwoPatternsFirstNormalPositionSecondSecondLastCharNonAdjacent() {
String[] noMatches = new String[] { "", "hlo", "hll", "hel", "helox" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*llo"),
"hllo", "hello", "hxxxllo", "helllo"),
new PatternMatch(Patterns.wildcardMatch("hel*o"),
"helo", "hello", "helxo", "helllo")
);
}
@Test
public void testWildcardTwoPatternsFirstNormalPositionSecondTrailing() {
String[] noMatches = new String[] { "", "he", "hel", "helox", "helx", "hxlo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*lo"),
"helo", "hello", "helllo", "helxlo"),
new PatternMatch(Patterns.wildcardMatch("hell*"),
"hell", "hello", "helllo", "hellx", "hellxxx")
);
}
@Test
public void testWildcardTwoPatternsFirstSecondLastCharSecondTrailing() {
String[] noMatches = new String[] { "", "hel", "helox", "helxox", "hexo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hel*o"),
"helo", "hello", "helllo", "hellloo", "helloo", "heloo"),
new PatternMatch(Patterns.wildcardMatch("hell*"),
"hell", "hello", "helllo", "hellloo", "helloo", "hellox")
);
}
@Test
public void testWildcardTwoPatternsBothTrailing() {
String[] noMatches = new String[] { "", "he", "hex", "hexlo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hel*"),
"hel", "helx", "hello", "hellox"),
new PatternMatch(Patterns.wildcardMatch("hello*"),
"hello", "hellox")
);
}
@Test
public void testWildcardLeadingWildcardOccursBeforeLeadingCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "ello", "hell" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("*hello"),
"hello", "hhello", "hhhello"),
new PatternMatch(Patterns.exactMatch("hello"),
"hello")
);
}
@Test
public void testWildcardNormalPositionWildcardOccursBeforeNormalPositionCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "he", "hel", "heo", "heloz", "hellox", "heloxo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*lo"),
"helo", "hello", "helllo"),
new PatternMatch(Patterns.exactMatch("helox"),
"helox")
);
}
@Test
public void testWildcardSecondLastCharWildcardOccursBeforeNormalPositionCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "he", "helx", "helo", "hexlx", "hellox", "heloxx" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*l"),
"hel", "hexl", "hexxxl"),
new PatternMatch(Patterns.exactMatch("helox"),
"helox")
);
}
@Test
public void testWildcardTrailingWildcardOccursBeforeNormalPositionCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "h", "hxlox", "hxelox" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*"),
"he", "helo", "helox", "heloxx"),
new PatternMatch(Patterns.exactMatch("helox"),
"helox")
);
}
@Test
public void testWildcardMultipleWildcardOccursBeforeNormalPositionCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "h", "he", "hel", "hexxo", "hexxohexxo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*l*o"),
"hlo", "helo", "hllo", "hello", "hexloo", "hellohello", "hellohellxo"),
new PatternMatch(Patterns.exactMatch("hellohello"),
"hellohello")
);
}
@Test
public void testWildcardLastCharAndThirdLastCharWildcardOccursBeforeNormalPositionCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "h", "he", "hlo", "hexxo", "hexxohexxo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*l*"),
"hel", "helo", "hexl", "hello", "hexloo", "hellohellx", "hellohello"),
new PatternMatch(Patterns.exactMatch("hellohello"),
"hellohello")
);
}
@Test
public void testWildcardLeadingWildcardOccursBeforeSameFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "x", "hx" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("*h"),
"h", "hh", "xhh"),
new PatternMatch(Patterns.exactMatch("h"),
"h")
);
}
@Test
public void testWildcardNormalPositionWildcardOccursBeforeSameFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "hel", "helx", "heoo", "helxoxo", "heloxo", "helxoox" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hel*oo"),
"heloo", "helloo", "helxxoo"),
new PatternMatch(Patterns.exactMatch("helo"),
"helo")
);
}
@Test
public void testWildcardNormalPositionWildcardOccursBeforeDivergentFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "hel", "helo", "heoo", "helxoxo", "heloxo", "helxoox" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hel*oo"),
"heloo", "helloo", "helxxoo"),
new PatternMatch(Patterns.exactMatch("helx"),
"helx")
);
}
@Test
public void testWildcardSecondLastCharWildcardOccursBeforeSameFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "hel", "hexlo", "helox" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hel*o"),
"helo", "hello", "helxxxo"),
new PatternMatch(Patterns.exactMatch("helo"),
"helo")
);
}
@Test
public void testWildcardSecondLastCharWildcardOccursBeforeDivergentFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "hel", "hexl", "helo", "helxx" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hel*o"),
"helo", "hello", "helxo", "helxxxo"),
new PatternMatch(Patterns.exactMatch("helx"),
"helx")
);
}
@Test
public void testWildcardTrailingWildcardOccursBeforeFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "hex", "hexl" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hel*"),
"hel", "helo", "hello", "heloo" ),
new PatternMatch(Patterns.exactMatch("helo"),
"helo")
);
}
@Test
public void testWildcardMultipleWildcardOccursBeforeSameFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "ho", "hell", "ello", "hxo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*l*o"),
"hlo", "helo", "hllo", "hello", "hxxlo", "hlxxo", "hxxlxxo"),
new PatternMatch(Patterns.exactMatch("hello"),
"hello")
);
}
@Test
public void testWildcardMultipleWildcardOccursBeforeDivergentFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "ho", "hell", "ello", "hxo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*l*o"),
"hlo", "helo", "hllo", "hello", "hxxlo", "hlxxo", "hxxlxxo"),
new PatternMatch(Patterns.exactMatch("hellx"),
"hellx")
);
}
@Test
public void testWildcardLastCharAndThirdLastCharWildcardOccursBeforeFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "h", "l", "elo", "hex", "hexo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*l*"),
"hl", "hel", "hlo", "helo", "heel", "hloo", "heelo", "heloo", "heeloo" ),
new PatternMatch(Patterns.exactMatch("helo"),
"helo")
);
}
@Test
public void testWildcardLeadingWildcardOccursAtDivergentCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "ello", "hellobye", "bbye" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("*hello"),
"hello", "xhello", "byehello"),
new PatternMatch(Patterns.exactMatch("bye"),
"bye")
);
}
@Test
public void testWildcardNormalPositionWildcardOccursAtDivergentCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "hel", "heo", "hexo", "hexzz" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*lo"),
"helo", "hello", "hexxxlo"),
new PatternMatch(Patterns.exactMatch("hexz"),
"hexz")
);
}
@Test
public void testWildcardSecondLastCharWildcardOccursAtDivergentCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "hel", "heloxz", "helxzz" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hel*o"),
"helo", "heloo", "hello", "helloo", "helxxxo", "helxzo"),
new PatternMatch(Patterns.exactMatch("helxz"),
"helxz")
);
}
@Test
public void testWildcardTrailingWildcardOccursAtDivergentCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "he", "hex" , "hexzz" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hel*"),
"hel", "helx", "helxz", "hello"),
new PatternMatch(Patterns.exactMatch("helxz"),
"helxz")
);
}
@Test
public void testWildcardMultipleWildcardOccursAtDivergentCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "ho", "hxl", "bye", "lbye", "hbye" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*l*o"),
"hlo", "helo", "hllo", "hello", "hxxlo", "hlxxo", "hxxlxxo", "hlbyeo"),
new PatternMatch(Patterns.exactMatch("hlbye"),
"hlbye")
);
}
@Test
public void testWildcardLastCharAndThirdLastCharWildcardOccursAtDivergentCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "ho", "hxl", "bye", "lbye", "hbye" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*l*"),
"hel", "hexl", "helo", "hello", "hexxl", "helxx", "helbye", "hellobye", "helbyeo"),
new PatternMatch(Patterns.exactMatch("helbye"),
"helbye")
);
}
@Test
public void testWildcardNormalPositionWildcardOccursInMiddleOfExactMatch() {
String[] noMatches = new String[] { "", "he", "hel", "hellx", "hexllo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*ll"),
"hell", "hexll", "hexxll"),
new PatternMatch(Patterns.exactMatch("hello"),
"hello")
);
}
@Test
public void testWildcardSecondLastCharWildcardOccursInMiddleOfExactMatch() {
String[] noMatches = new String[] { "", "hxl", "hxel", "hex", "hexlx" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*l"),
"hel", "hexl", "hexyzl"),
new PatternMatch(Patterns.exactMatch("hello"),
"hello")
);
}
@Test
public void testWildcardTrailingWildcardOccursInMiddleOfExactMatch() {
String[] noMatches = new String[] { "", "hex", "hexl" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hel*"),
"hel", "helx", "helhel", "hello", "hellox"),
new PatternMatch(Patterns.exactMatch("hello"),
"hello")
);
}
@Test
public void testWildcardNormalPositionWildcardOccursAfterFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "hell", "hexlo", "helxo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hel*lo"),
"hello", "helllllo", "helxxxlo"),
new PatternMatch(Patterns.exactMatch("hel"),
"hel")
);
}
@Test
public void testWildcardSecondLastCharWildcardOccursAfterFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "he", "heo", "heloox" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hel*o"),
"helo", "heloo", "hello", "helxo", "helllllxlllo"),
new PatternMatch(Patterns.exactMatch("hel"),
"hel")
);
}
@Test
public void testWildcardTrailingWildcardOccursAfterFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "he", "hex", "hexl" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hel*"),
"hel", "hello"),
new PatternMatch(Patterns.exactMatch("hel"),
"hel")
);
}
@Test
public void testWildcardMultipleWildcardOccursAfterFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "x", "ho", "hxo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*l*o"),
"hlo", "helo", "hllo", "hello", "hxxlxxo"),
new PatternMatch(Patterns.exactMatch("h"),
"h")
);
}
@Test
public void testWildcardLastCharAndThirdLastCharWildcardOccursAfterFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "h", "hl", "hex" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*l*"),
"hel", "hexl", "helo", "hello", "hexxlxx"),
new PatternMatch(Patterns.exactMatch("he"),
"he")
);
}
@Test
public void testWildcardMultipleWildcardOccursSurroundingFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "he", "hl", "ho", "hxo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*l*o"),
"hlo", "helo", "hllo", "hello", "hxxlxxo"),
new PatternMatch(Patterns.exactMatch("hel"),
"hel")
);
}
@Test
public void testWildcardLastCharAndThirdLastCharWildcardOccursSurroundingFinalCharacterOfExactMatch() {
String[] noMatches = new String[] { "", "he", "hl", "hexo", "el" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*l*"),
"hel", "hell", "helo", "hello", "hexxlxx"),
new PatternMatch(Patterns.exactMatch("hell"),
"hell")
);
}
@Test
public void testWildcardExactMatchHasWildcardCharacter() {
String[] noMatches = new String[] { "hel", "heo", "hlo", "helox", "hxlo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*lo"),
"helo", "he*lo", "hello", "hellllllo"),
new PatternMatch(Patterns.exactMatch("he*lo"),
"he*lo")
);
}
@Test
public void testWildcardFourMultipleWildcardPatternsInterweaving() {
String[] noMatches = new String[] { "", "ab", "bc", "ac", "xbyazc", "xbycza", "xcybza" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("*a*b*c"),
"abc", "aabbcc", "xaybzc", "xxayybzzc"),
new PatternMatch(Patterns.wildcardMatch("a*b*c*"),
"abc", "aabbcc", "axbycz", "azzbyyczz"),
new PatternMatch(Patterns.wildcardMatch("*a*c*b"),
"acb", "aaccbb", "xayczb", "xxayyczzb"),
new PatternMatch(Patterns.wildcardMatch("a*c*b*"),
"acb", "aaccbb", "axcybz", "axxcyybzz")
);
}
@Test
public void testWildcardWithAnythingButPattern() {
testPatternPermutations(
new PatternMatch(Patterns.wildcardMatch("he*lo"),
"helo", "hello", "hexxxlo"),
new PatternMatch(Patterns.anythingButMatch("hello"),
"", "helo", "helol", "hexxxlo")
);
}
@Test
public void testWildcardWithAnythingButSetPattern() {
testPatternPermutations(
new PatternMatch(Patterns.wildcardMatch("he*lo"),
"helo", "hello", "hexxxlo"),
new PatternMatch(Patterns.anythingButMatch(new HashSet<>(Arrays.asList("helo", "hello"))),
"", "helol", "hexxxlo")
);
}
@Test
public void testWildcardWithAnythingButPrefixPatternWildcardStartsWithPrefix() {
String[] noMatches = new String[] { "he", "hel", "hell", "hexxx" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*lo"),
"helo", "hello", "hellllo"),
new PatternMatch(Patterns.anythingButPrefix("he"),
"", "h", "hllo", "x", "xx")
);
}
@Test
public void testWildcardWithAnythingButSuffixPatternEndsWithSuffix() {
String[] noMatches = new String[] { "going", "leaving", "ng", "gong" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.anythingButSuffix("ng"),
"", "g", "gog", "x", "xx")
);
}
@Test
public void testWildcardWithAnythingButPrefixPatternWildcardStartsWithHalfOfPrefix() {
String[] noMatches = new String[] { "he", "hel", "hell", "hello", "hexxx" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hx*lo"),
"hxlo", "hxllo", "hxllllo"),
new PatternMatch(Patterns.anythingButPrefix("he"),
"", "h", "hxlo", "hxllo", "hxllllo", "x", "xx")
);
}
@Test
public void testWildcardWithAnythingButPrefixPatternWildcardStartsWithNoneOfPrefix() {
String[] noMatches = new String[] { "xe", "xex", "xexx" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hx*lo"),
"hxlo", "hxllo", "hxllllo"),
new PatternMatch(Patterns.anythingButPrefix("xe"),
"", "x", "xyyy", "h", "he", "hxlo", "hxllo", "hxllllo")
);
}
@Test
public void testWildcardWithPrefixPatternWildcardStartsWithPrefix() {
String[] noMatches = new String[] { "", "hlo", "elo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*lo"),
"helo", "hello", "hellllo"),
new PatternMatch(Patterns.prefixMatch("he"),
"he", "helo", "hello", "hellllo")
);
}
@Test
public void testWildcardWithPrefixPatternWildcardStartsWithHalfOfPrefix() {
String[] noMatches = new String[] { "", "hx", "hxl", "hlo", "elo", "xlo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hx*lo"),
"hxlo", "hxllo", "hxllllo"),
new PatternMatch(Patterns.prefixMatch("he"),
"he", "helo", "hello", "hellllo")
);
}
@Test
public void testWildcardWithPrefixPatternWildcardStartsWithNoneOfPrefix() {
String[] noMatches = new String[] { "", "h", "x", "xx", "xxl", "xlo", "hxllo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("xx*lo"),
"xxlo", "xxllo", "xxllllo"),
new PatternMatch(Patterns.prefixMatch("he"),
"he", "helo", "hello", "hellllo")
);
}
@Test
public void testWildcardWithSuffixPatternWildcardEndsWithSuffix() {
String[] noMatches = new String[] { "", "he", "hel" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*lo"),
"helo", "hello", "hellllo"),
new PatternMatch(Patterns.suffixMatch("lo"),
"lo", "helo", "hello", "hellllo")
);
}
@Test
public void testWildcardWithSuffixPatternWildcardEndsWithHalfOfSuffix() {
String[] noMatches = new String[] { "", "he", "hex", "exo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*xo"),
"hexo", "hexxo", "hexxxxo"),
new PatternMatch(Patterns.suffixMatch("lo"),
"lo", "helo", "hello", "hellllo")
);
}
@Test
public void testWildcardWithSuffixPatternWildcardEndsWithNoneOfSuffix() {
String[] noMatches = new String[] { "", "he", "hex", "exy", "exo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*xy"),
"hexy", "hexxy", "hexxxxy"),
new PatternMatch(Patterns.suffixMatch("lo"),
"lo", "helo", "hello", "hellllo")
);
}
@Test
public void testWildcardWithEqualsIgnoreCasePattern() {
String[] noMatches = new String[] { "", "hel", "heo", "HEXLO", "HExLO", "hexlO", "helllLo", "hElo", "HEXlo" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("he*lo"),
"helo", "hello", "heLlo", "hellllo"),
new PatternMatch(Patterns.equalsIgnoreCaseMatch("heLLo"),
"heLLo", "hello", "HELLO", "HEllO", "HeLlO", "hElLo", "heLlo")
);
}
@Test
public void testWildcardWithExistencePattern() {
testPatternPermutations(
new PatternMatch(Patterns.wildcardMatch("he*lo"),
"helo", "hello", "hellllo"),
new PatternMatch(Patterns.existencePatterns(),
"", "a", "b", "c", "abc", "helo", "hello", "hellllo")
);
}
@Test
public void testWildcardSecondWildcardCharacterIsNotReusedByOtherWildcardRule() {
String[] noMatches = new String[] { "", "abcd", "bcde", "ae", "xabcde", "abcdex" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("a*bc*de"),
"abcde", "axbcde", "abcxde", "axbcxde"),
new PatternMatch(Patterns.wildcardMatch("a*bcde"),
"abcde", "axbcde")
);
}
@Test
public void testWildcardAddTwiceDeleteOnceLeadingWildcard() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.wildcardMatch("*hello"));
cut.addPattern(Patterns.wildcardMatch("*hello"));
cut.deletePattern(Patterns.wildcardMatch("*hello"));
assertTrue(cut.isEmpty());
}
@Test
public void testWildcardAddTwiceDeleteOnceNormalPositionWildcard() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.wildcardMatch("h*llo"));
cut.addPattern(Patterns.wildcardMatch("h*llo"));
cut.deletePattern(Patterns.wildcardMatch("h*llo"));
assertTrue(cut.isEmpty());
}
@Test
public void testWildcardAddTwiceDeleteOnceSecondLastCharWildcard() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.wildcardMatch("hell*o"));
cut.addPattern(Patterns.wildcardMatch("hell*o"));
cut.deletePattern(Patterns.wildcardMatch("hell*o"));
assertTrue(cut.isEmpty());
}
@Test
public void testWildcardAddTwiceDeleteOnceTrailingWildcard() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.wildcardMatch("hello*"));
cut.addPattern(Patterns.wildcardMatch("hello*"));
cut.deletePattern(Patterns.wildcardMatch("hello*"));
assertTrue(cut.isEmpty());
}
@Test
public void testWildcardAddTwiceDeleteOnceMultipleWildcard() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.wildcardMatch("h*l*o"));
cut.addPattern(Patterns.wildcardMatch("h*l*o"));
cut.deletePattern(Patterns.wildcardMatch("h*l*o"));
assertTrue(cut.isEmpty());
}
@Test
public void testWildcardAddTwiceDeleteOnceLastCharAndThirdLastCharWildcard() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.wildcardMatch("he*l*"));
cut.addPattern(Patterns.wildcardMatch("he*l*"));
cut.deletePattern(Patterns.wildcardMatch("he*l*"));
assertTrue(cut.isEmpty());
}
@Test
public void testWildcardAddTwiceDeleteOnceSingleCharWildcard() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.wildcardMatch("*"));
cut.addPattern(Patterns.wildcardMatch("*"));
cut.deletePattern(Patterns.wildcardMatch("*"));
assertTrue(cut.isEmpty());
}
@Test
public void testWildcardAddTwiceDeleteOnceMixed() {
ByteMachine cut = new ByteMachine();
for (int i = 0; i < 2; i ++){
cut.addPattern(Patterns.wildcardMatch("h*llo"));
cut.addPattern(Patterns.wildcardMatch("*"));
cut.addPattern(Patterns.wildcardMatch("*hello"));
cut.addPattern(Patterns.wildcardMatch("hello*"));
cut.addPattern(Patterns.wildcardMatch("hell*o"));
cut.addPattern(Patterns.wildcardMatch("h*l*o"));
cut.addPattern(Patterns.wildcardMatch("he*l*"));
}
cut.deletePattern(Patterns.wildcardMatch("h*llo"));
cut.deletePattern(Patterns.wildcardMatch("*"));
cut.deletePattern(Patterns.wildcardMatch("*hello"));
cut.deletePattern(Patterns.wildcardMatch("hello*"));
cut.deletePattern(Patterns.wildcardMatch("hell*o"));
cut.deletePattern(Patterns.wildcardMatch("h*l*o"));
cut.deletePattern(Patterns.wildcardMatch("he*l*"));
assertTrue(cut.isEmpty());
}
@Test
public void testWildcardMachineNotEmptyWithSingleWildcardCharacterPattern() {
ByteMachine cut = new ByteMachine();
cut.addPattern(Patterns.wildcardMatch("*"));
assertFalse(cut.isEmpty());
cut.deletePattern(Patterns.wildcardMatch("*"));
assertTrue(cut.isEmpty());
}
@Test
public void testWildcardRuleIsNotDuplicated() {
ByteMachine cut = new ByteMachine();
for (int i = 0; i < 10; i++) {
cut.addPattern(Patterns.wildcardMatch("1*2345"));
}
assertEquals(2, cut.evaluateComplexity(new MachineComplexityEvaluator(Integer.MAX_VALUE)));
}
@Test
public void testWildcardRuleIsNotDuplicatedWildcardIsFirstChar() {
ByteMachine cut = new ByteMachine();
for (int i = 0; i < 10; i++) {
cut.addPattern(Patterns.wildcardMatch("*123"));
}
assertEquals(2, cut.evaluateComplexity(new MachineComplexityEvaluator(Integer.MAX_VALUE)));
}
@Test
public void testWildcardRuleIsNotDuplicatedWildcardIsSecondLastChar() {
ByteMachine cut = new ByteMachine();
for (int i = 0; i < 10; i++) {
cut.addPattern(Patterns.wildcardMatch("1*2"));
}
assertEquals(2, cut.evaluateComplexity(new MachineComplexityEvaluator(Integer.MAX_VALUE)));
}
@Test
public void testWildcardRuleIsNotDuplicatedWildcardIsLastChar() {
ByteMachine cut = new ByteMachine();
for (int i = 0; i < 10; i++) {
cut.addPattern(Patterns.wildcardMatch("1*"));
}
assertEquals(2, cut.evaluateComplexity(new MachineComplexityEvaluator(Integer.MAX_VALUE)));
}
@Test
public void testWildcardRuleIsNotDuplicatedWildcardIsThirdLastAndLastChar() {
ByteMachine cut = new ByteMachine();
for (int i = 0; i < 10; i++) {
cut.addPattern(Patterns.wildcardMatch("12*3*"));
}
assertEquals(3, cut.evaluateComplexity(new MachineComplexityEvaluator(Integer.MAX_VALUE)));
}
@Test
public void testWildcardMultipleWildcardPatterns1() {
// Considering the following as potential matches: "hello", "hxxllo", "xhello", "xxhello", "hellox", "helloxx", "hellxo", "hellxxo", "", "helxlo", "kaboom"
String[] noMatches = new String[] { "", "helxlo", "kaboom" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("h*llo"),
"hello", "hxxllo"),
new PatternMatch(Patterns.wildcardMatch("*hello"),
"hello", "xhello", "xxhello"),
new PatternMatch(Patterns.wildcardMatch("hello*"),
"hello", "hellox", "helloxx"),
new PatternMatch(Patterns.wildcardMatch("hell*o"),
"hello", "hellxo", "hellxxo")
);
}
@Test
public void testWildcardMultipleWildcardPatterns2() {
// Considering the following as potential matches: "hello", "hellox", "hxllo", "hxlxo", "xlo", "", "hell", "hellx", "xell", "xellox"
String[] noMatches = new String[] { "", "hell", "hellx", "xell", "xellox" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("hello*"),
"hello", "hellox"),
new PatternMatch(Patterns.wildcardMatch("h*llo"),
"hello", "hxllo"),
new PatternMatch(Patterns.wildcardMatch("h*l*o"),
"hello", "hxllo", "hxlxo"),
new PatternMatch(Patterns.wildcardMatch("*lo"),
"hello", "hxllo", "xlo")
);
}
@Test
public void testWildcardMultipleMixedPatterns() {
// Considering the following as potential matches: "", "x", "hello", "xhello", "helo", "helxo", "hellox", "", "x", "xello"
String[] noMatches = new String[] { "", "x", "xello" };
testPatternPermutations(noMatches,
new PatternMatch(Patterns.wildcardMatch("*hello"),
"hello", "xhello"),
new PatternMatch(Patterns.wildcardMatch("hel*o"),
"hello", "helo", "helxo"),
new PatternMatch(Patterns.wildcardMatch("hello*"),
"hello", "hellox"),
new PatternMatch(Patterns.wildcardMatch("h*o"),
"hello", "helo", "helxo"),
new PatternMatch(Patterns.exactMatch("hello"),
"hello"),
new PatternMatch(Patterns.exactMatch("helo"),
"helo"),
new PatternMatch(Patterns.prefixMatch("h"),
"hello", "helo", "helxo", "hellox")
);
}
@Test
public void testWildcardNoConsecutiveWildcardCharacters() {
try {
new ByteMachine().addPattern(Patterns.wildcardMatch("h**o"));
fail("Expected ParseException");
} catch (ParseException e) {
assertEquals("Consecutive wildcard characters at pos 1", e.getMessage());
}
}
@Test
public void testAddMatchPatternGivenNameStateReturned() {
NameState nameState = new NameState();
ByteMachine cut = new ByteMachine();
assertSame(nameState, cut.addPattern(Patterns.exactMatch("a"), nameState));
}
@Test
public void testAddMatchPatternNoNameStateGiven() {
ByteMachine cut = new ByteMachine();
assertNotNull(cut.addPattern(Patterns.exactMatch("a")));
}
@Test
public void testAddExistencePatternGivenNameStateReturned() {
NameState nameState = new NameState();
ByteMachine cut = new ByteMachine();
assertSame(nameState, cut.addPattern(Patterns.existencePatterns(), nameState));
}
@Test
public void testAddExistencePatternNoNameStateGiven() {
ByteMachine cut = new ByteMachine();
assertNotNull(cut.addPattern(Patterns.existencePatterns()));
}
@Test
public void testAddAnythingButPatternGivenNameStateReturned() {
NameState nameState = new NameState();
ByteMachine cut = new ByteMachine();
assertSame(nameState, cut.addPattern(Patterns.anythingButMatch("z"), nameState));
}
@Test
public void testAddAnythingButPatternNoNameStateGiven() {
ByteMachine cut = new ByteMachine();
assertNotNull(cut.addPattern(Patterns.anythingButMatch("z")));
}
@Test
public void testAddRangePatternGivenNameStateReturned() {
NameState nameState = new NameState();
ByteMachine cut = new ByteMachine();
assertSame(nameState, cut.addPattern(Range.lessThan(5), nameState));
}
@Test
public void testAddRangePatternNoNameStateGiven() {
ByteMachine cut = new ByteMachine();
assertNotNull(cut.addPattern(Range.lessThan(5)));
}
private void testPatternPermutations(PatternMatch ... patternMatches) {
testPatternPermutations(new String[0], patternMatches);
}
/**
* Adds all given patterns to the machine according to all possible permutations. For a given permutation, as each
* pattern is added, the machine is exercised against the given match values, and we verify that each match value
* generates the expected number of matches. After adding the last pattern of a permutation and verifying the
* matches, we delete all patterns, verifying the expected number of matches after each pattern deletion, and
* verifying the machine is empty after the last pattern is deleted. Deletion can be done in one of two ways. For
* sufficiently large numbers of permutations, we simply choose a random permutation for the deletion. However, for
* smaller numbers of permutations, we perform deletion according to all permutations, i.e. for each addition
* permutation, we exercise all deletion permutations, which is (n!)^2 where n is the number of patterns.
*
* Any match specified by one PatternMatch will be evaluated against all patterns. So if you specify that one
* pattern has matched a certain value, you need to specify that same value for all other patterns that match it as
* well. Provide values that will not match any patterns in the noMatches array and this function will verify that
* they are never matched. If you provide a value in the noMatches array that is present in one of the PatternMatch
* objects, it will have no effect; i.e. the value will still be expected to match the pattern.
*
* @param noMatches Array of values that do not match any of the given patterns.
* @param patternMatches Array where each element contains a pattern and values that will match the pattern.
*/
private void testPatternPermutations(String[] noMatches, PatternMatch ... patternMatches) {
long seed = new Random().nextLong();
System.out.println("USE ME TO REPRODUCE - ByteMachineTest.testPatternPermutations seeding with " + seed);
Random r = new Random(seed);
ByteMachine cut = new ByteMachine();
Set<String> matchValues = Stream.of(patternMatches)
.map(patternMatch -> patternMatch.matches)
.flatMap(set -> set.stream())
.collect(Collectors.toSet());
matchValues.addAll(Arrays.asList(noMatches));
Matches matches = new Matches(matchValues.stream()
.map(string -> new Match(string))
.collect(Collectors.toList())
.toArray(new Match[0]));
List<PatternMatch[]> permutations = generateAllPermutations(patternMatches);
for (PatternMatch[] additionPermutation : permutations) {
// Magic number alert: For 5 or less patterns, it is reasonable to test all deletion permutations for each
// addition permutation. But for 6 or more patterns, the runtime becomes ridiculous, so we will settle for
// choosing a random deletion permutation for each addition permutation.
if (patternMatches.length <= 5) {
for (PatternMatch[] deletionPermutation : permutations) {
testPatternPermutation(cut, additionPermutation, deletionPermutation, matches);
}
} else {
testPatternPermutation(cut, additionPermutation, permutations.get(r.nextInt(permutations.size())),
matches);
}
}
}
private void testPatternPermutation(ByteMachine cut, PatternMatch[] additionPermutation,
PatternMatch[] deletionPermutation, Matches matches) {
for (PatternMatch patternMatch : additionPermutation) {
cut.addPattern(matches.registerPattern(patternMatch));
for (Match match : matches.get()) {
assertEquals("Failed on " + match.value,
match.getNumPatternsRegistered(), cut.transitionOn(match.value).size());
}
}
for (PatternMatch patternMatch : deletionPermutation) {
cut.deletePattern(matches.deregisterPattern(patternMatch));
for (Match match : matches.get()) {
assertEquals("Failed on " + match.value, match.getNumPatternsRegistered(),
cut.transitionOn(match.value).size());
}
}
assertTrue(cut.isEmpty());
matches.assertNoPatternsRegistered();
}
private static class Matches {
private final Match[] matches;
public Matches(Match ... matches) {
this.matches = matches;
}
public Match[] get() {
return matches;
}
public Patterns registerPattern(PatternMatch patternMatch) {
for (Match match : matches) {
match.registerPattern(patternMatch);
}
return patternMatch.pattern;
}
public Patterns deregisterPattern(PatternMatch patternMatch) {
for (Match match : matches) {
match.deregisterPattern(patternMatch);
}
return patternMatch.pattern;
}
public void assertNoPatternsRegistered() {
for (Match match : matches) {
assertEquals(0, match.getNumPatternsRegistered());
}
}
}
private static class Match {
private final String value;
private int num = 0;
public Match(String value) {
this.value = value;
}
public void registerPattern(PatternMatch patternMatch) {
if (patternMatch.matches.contains(value)) {
num++;
}
}
public void deregisterPattern(PatternMatch patternMatch) {
if (patternMatch.matches.contains(value)) {
num--;
}
}
public int getNumPatternsRegistered() {
return num;
}
}
private static class PatternMatch {
private final Patterns pattern;
private final Set<String> matches;
public PatternMatch(Patterns pattern, String ... matches) {
this.pattern = pattern;
this.matches = new HashSet<>(Arrays.asList(matches));
}
}
}
| 4,846 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/RulerTest.java | package software.amazon.event.ruler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class RulerTest {
private static final String JSON_FROM_RFC = " {\n" +
" \"Image\": {\n" +
" \"Width\": 800,\n" +
" \"Height\": 600,\n" +
" \"Title\": \"View from 15th Floor\",\n" +
" \"Thumbnail\": {\n" +
" \"Url\": \"http://www.example.com/image/481989943\",\n" +
" \"Height\": 125,\n" +
" \"Width\": 100\n" +
" },\n" +
" \"Animated\" : false,\n" +
" \"IDs\": [116, 943, 234, 38793]\n" +
" }\n" +
" }";
private static final String JSON_FROM_README = "{\n" +
" \"version\": \"0\",\n" +
" \"id\": \"ddddd4-aaaa-7777-4444-345dd43cc333\",\n" +
" \"detail-type\": \"EC2 Instance State-change Notification\",\n" +
" \"source\": \"aws.ec2\",\n" +
" \"account\": \"012345679012\",\n" +
" \"time\": \"2017-10-02T16:24:49Z\",\n" +
" \"region\": \"us-east-1\",\n" +
" \"resources\": [\n" +
" \"arn:aws:ec2:us-east-1:012345679012:instance/i-000000aaaaaa00000\"\n" +
" ],\n" +
" \"detail\": {\n" +
" \"c.count\": 5,\n" +
" \"d.count\": 3,\n" +
" \"x.limit\": 301.8,\n" +
" \"source-ip\": \"10.0.0.33\",\n" +
" \"instance-id\": \"i-000000aaaaaa00000\",\n" +
" \"state\": \"running\"\n" +
" }\n" +
"}\n";
private static final String JSON_FROM_README_WITH_FLAT_FORMAT = "{\n" +
" \"version\": \"0\",\n" +
" \"id\": \"ddddd4-aaaa-7777-4444-345dd43cc333\",\n" +
" \"detail-type\": \"EC2 Instance State-change Notification\",\n" +
" \"source\": \"aws.ec2\",\n" +
" \"account\": \"012345679012\",\n" +
" \"time\": \"2017-10-02T16:24:49Z\",\n" +
" \"region\": \"us-east-1\",\n" +
" \"resources\": [\n" +
" \"arn:aws:ec2:us-east-1:012345679012:instance/i-000000aaaaaa00000\"\n" +
" ],\n" +
" \"detail.c.count\": 5,\n" +
" \"detail.d.count\": 3,\n" +
" \"detail.x.limit\": 301.8,\n" +
" \"detail.instance-id\": \"i-000000aaaaaa00000\",\n" +
" \"detail.state\": \"running\"\n" +
"}\n";
private static final String JSON_WITH_COMPLEX_ARRAYS = "{\n" +
" \"employees\":[\n" +
" [\n" +
" { \"firstName\":\"John\", \"lastName\":\"Doe\" , \"ids\" : [ 1234, 1000, 9999 ] },\n" +
" { \"firstName\":\"Anna\", \"lastName\":\"Smith\" }\n" +
" ],\n" +
" [\n" +
" { \"firstName\":\"Peter\", \"lastName\":\"Jones\", \"ids\" : [ ] }\n" +
" ]\n" +
" ]\n" +
"}";
@Test
public void WHEN_RulesFromReadmeAreTried_THEN_TheyWork() throws Exception {
String[] rules = {
"{\n" +
" \"detail-type\": [ \"EC2 Instance State-change Notification\" ],\n" +
" \"resources\": [ \"arn:aws:ec2:us-east-1:012345679012:instance/i-000000aaaaaa00000\" ],\n" +
" \"detail\": {\n" +
" \"state\": [ \"initializing\", \"running\" ]\n" +
" }\n" +
"}",
"{\n" +
" \"time\": [ { \"prefix\": \"2017-10-02\" } ],\n" +
" \"detail\": {\n" +
" \"state\": [ { \"anything-but\": \"initializing\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"detail\": {\n" +
" \"source-ip\": [ { \"cidr\": \"10.0.0.0/24\" } ],\n" +
" \"c.count\": [ { \"numeric\": [ \">\", 0, \"<=\", 5 ] } ],\n" +
" \"d.count\": [ { \"numeric\": [ \"<\", 10 ] } ],\n" +
" \"x.limit\": [ { \"numeric\": [ \"=\", 3.018e2 ] } ]\n" +
" }\n" +
"} \n",
"{\n" +
" \"detail\": {\n" +
" \"state\": [ { \"anything-but\": { \"prefix\": \"init\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"detail\": {\n" +
" \"state\": [ { \"prefix\": { \"equals-ignore-case\": \"RuNn\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"detail\": {\n" +
" \"state\": [ { \"suffix\": \"ning\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"detail\": {\n" +
" \"state\": [ { \"suffix\": { \"equals-ignore-case\": \"nInG\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"detail\": {\n" +
" \"source-ip\": [ { \"cidr\": \"10.0.0.0/24\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"detail\": {\n" +
" \"source-ip\": [ { \"cidr\": \"10.0.0.0/8\" } ]\n" +
" }\n" +
"}"
};
for (String rule : rules) {
assertTrue(Ruler.matchesRule(JSON_FROM_README, rule));
// None flattened rule should not be matched with the flattened event
// Keep these around until we can make the tests pass for `Ruler.match`
assertTrue(Ruler.matches(JSON_FROM_README, rule));
assertFalse(Ruler.matches(JSON_FROM_README_WITH_FLAT_FORMAT, rule));
}
}
@Test
public void WHEN_WeWriteRulesToMatchVariousFieldCombos_THEN_TheyWork() throws Exception {
String[] matchingRules = {
" {\n" +
" \"Image\": {\n" +
" \"Width\": [ 800 ],\n" +
" \"Thumbnail\": {\n" +
" \"Height\": [ 125, 300 ]\n" +
" }\n" +
" }\n" +
" }",
" {\n" +
" \"Image\": {\n" +
" \"Thumbnail\": {\n" +
" \"Url\": [ { \"prefix\": \"http\" } ]\n" +
" }\n" +
" }\n" +
" }",
" {\n" +
" \"Image\": {\n" +
" \"Title\": [ { \"prefix\": { \"equals-ignore-case\": \"VIeW\" } } ]\n" +
" }\n" +
" }",
" {\n" +
" \"Image\": {\n" +
" \"Title\": [ { \"suffix\": { \"equals-ignore-case\": \"LoOr\" } } ]\n" +
" }\n" +
" }",
" {\n" +
" \"Image\": {\n" +
" \"Title\": [ { \"suffix\": \"loor\" } ]\n" +
" }\n" +
" }",
" {\n" +
" \"Image\": {\n" +
" \"Width\": [ { \"numeric\": [ \"<\", 1000 ] } ],\n" +
" \"Height\": [ { \"numeric\": [ \"<=\", 600 ] } ],\n" +
" \"Title\": [ { \"anything-but\": \"View from 15th Flood\" } ],\n" +
" \"Thumbnail\": {\n" +
" \"Url\": [ { \"prefix\": \"http\" } ],\n" +
" \"Height\": [ { \"numeric\": [ \">\", 124, \"<\", 126 ] } ],\n" +
" \"Width\": [ { \"numeric\": [ \">=\", 99.999, \"<=\", 100 ] } ]\n" +
" },\n" +
" \"Animated\": [ false ]\n" +
" }\n" +
"}\n"
};
String[] nonMatchingRules = {
" {\n" +
" \"Image\": {\n" +
" \"Width\": [ { \"numeric\": [ \"<\", 800 ] } ]\n" +
" }\n" +
"}\n",
" {\n" +
" \"Image\": {\n" +
" \"Height\": [ { \"numeric\": [ \"<\", 599 ] } ]\n" +
" }\n" +
"}\n",
" {\n" +
" \"Image\": {\n" +
" \"Title\": [ { \"anything-but\": \"View from 15th Floor\" } ]\n" +
" }\n" +
"}\n",
" {\n" +
" \"Image\": {\n" +
" \"Thumbnail\": {\n" +
" \"Url\": [ { \"prefix\": \"https\" } ]\n" +
" }\n" +
" }\n" +
"}\n",
" {\n" +
" \"Image\": {\n" +
" \"Thumbnail\": {\n" +
" \"Height\": [ { \"numeric\": [ \">\", 124, \"<\", 125 ] } ]\n" +
" }\n" +
" }\n" +
"}\n",
" {\n" +
" \"Image\": {\n" +
" \"Thumbnail\": {\n" +
" \"Width\": [ { \"numeric\": [ \">=\", 100.00001, \"<=\", 1001] } ]\n" +
" }\n" +
" }\n" +
"}\n",
" {\n" +
" \"Image\": {\n" +
" \"Animated\": [ true ]\n" +
" }\n" +
"}\n"
};
for (String rule : matchingRules){
assertTrue(Ruler.matchesRule(JSON_FROM_RFC, rule));
}
for (String rule : nonMatchingRules) {
assertFalse(Ruler.matchesRule(JSON_FROM_RFC, rule));
}
}
@Test
public void WHEN_CompareIsPassedComparableNumbers_THEN_ItOrdersThemCorrectly() {
double[] data = {
-Constants.FIVE_BILLION, -999999999.99999, -999999999.99, -10000, -0.000002,
0, 0.000001, 3.8, 3.9, 11, 12, 2.5e4, 999999999.999998, 999999999.999999, Constants.FIVE_BILLION
};
for (double d1 : data) {
for (double d2 : data) {
byte[] s0 = ComparableNumber.generate(d1).getBytes(StandardCharsets.UTF_8);
byte[] s1 = ComparableNumber.generate(d2).getBytes(StandardCharsets.UTF_8);
if (d1 < d2) {
assertTrue(Ruler.compare(s0, s1) < 0);
} else if (d1 == d2) {
assertEquals(0, Ruler.compare(s0, s1));
} else {
assertTrue(Ruler.compare(s0, s1) > 0);
}
}
}
}
@Test
public void WHEN_JSONContainsManyElementTypes_THEN_TheyCanAllBeRetrievedByPath() throws Exception {
JsonNode json = new ObjectMapper().readTree(JSON_FROM_RFC);
JsonNode n;
n = Ruler.tryToRetrievePath(json, Collections.singletonList("Image"));
assertNotNull(n);
assertTrue(n.isObject());
n = Ruler.tryToRetrievePath(json, Arrays.asList("Image", "Width"));
assertNotNull(n);
assertTrue(n.isNumber());
assertEquals(800.0, n.asDouble(), 0.001);
n = Ruler.tryToRetrievePath(json, Arrays.asList("Image","Height"));
assertNotNull(n);
assertTrue(n.isNumber());
assertEquals(600, n.asDouble(), 0.001);
n = Ruler.tryToRetrievePath(json, Arrays.asList("Image","Title"));
assertNotNull(n);
assertTrue(n.isTextual());
n = Ruler.tryToRetrievePath(json, Arrays.asList("Image","Thumbnail"));
assertNotNull(n);
assertTrue(n.isObject());
n = Ruler.tryToRetrievePath(json, Arrays.asList("Image","Thumbnail","Url"));
assertNotNull(n);
assertTrue(n.isTextual());
n = Ruler.tryToRetrievePath(json, Arrays.asList("Image","Thumbnail","Height"));
assertNotNull(n);
assertTrue(n.isNumber());
assertEquals(125.0, n.asDouble(), 0.001);
n = Ruler.tryToRetrievePath(json, Arrays.asList("Image","Thumbnail","Width"));
assertNotNull(n);
assertTrue(n.isNumber());
assertEquals(100.0, n.asDouble(), 0.001);
n = Ruler.tryToRetrievePath(json, Arrays.asList("Image","Animated"));
assertNotNull(n);
assertTrue(n.isBoolean());
n = Ruler.tryToRetrievePath(json, Collections.singletonList("x"));
assertNull(n);
n = Ruler.tryToRetrievePath(json, Arrays.asList("Thumbnail","foo"));
assertNull(n);
}
@Test
public void WHEN_JSONContainsArrays_THEN_RulerNoCompileMatchesWork() throws Exception {
String[] matchingRules = new String[] {
"{\n" +
" \"employees\": {\n" +
" \"firstName\": [\"Anna\"]\n" +
" }\n" +
"}",
"{\n" +
" \"employees\": {\n" +
" \"firstName\": [\"John\"],\n" +
" \"ids\": [ 1000 ]\n" +
" }\n" +
"}",
"{\n" +
" \"employees\": {\n" +
" \"firstName\": [\"Anna\"],\n" +
" \"ids\": [ { \"exists\": false } ]\n" +
" }\n" +
"}"
};
String[] nonMatchingRules = new String[] {
"{\n" +
" \"employees\": {\n" +
" \"firstName\": [\"Alice\"]\n" +
" }\n" +
"}",
"{\n" + // See JSON Array Matching in README
" \"employees\": {\n" +
" \"firstName\": [\"Anna\"],\n" +
" \"lastName\": [\"Jones\"]\n" +
" }\n" +
"}",
"{\n" +
" \"employees\": {\n" +
" \"firstName\": [\"Alice\"],\n" +
" \"lastName\": [\"Bob\"]\n" +
" }\n" +
"}",
"{\n" +
" \"a\": [ \"b\" ]\n" +
"}",
"{\n" +
" \"employees\": [ \"b\" ]\n" +
"}",
"{\n" +
" \"employees\": {\n" +
" \"firstName\": [\"Anna\"],\n" +
" \"ids\": [ 1000 ]\n" +
" }\n" +
"}",
"{\n" +
" \"employees\": {\n" +
" \"firstName\": [\"Anna\"],\n" +
" \"ids\": [ { \"exists\": true } ]\n" +
" }\n" +
"}"
};
for(String rule : matchingRules) {
assertTrue(rule, Ruler.matchesRule(JSON_WITH_COMPLEX_ARRAYS, rule));
}
for(String rule : nonMatchingRules) {
assertFalse(rule, Ruler.matchesRule(JSON_WITH_COMPLEX_ARRAYS, rule));
}
}
@Test
public void WHEN_WeTryToMatchExistsRules_THEN_TheyWork() throws Exception {
String rule1 = "{ \"a\" : [ { \"exists\": true } ] }";
String rule2 = "{ \"b\" : [ { \"exists\": false } ] }";
String rule3 = "{ \"x\" : [ {\"exists\": true} ] }";
String rule4 = "{ \"x\" : [ {\"exists\": false} ] }";
String event1 = "{ \"a\" : 1 }";
String event2 = "{ \"b\" : 2 }";
String event3 = "{ \"x\" : \"X\" }";
assertTrue("1/1", Ruler.matchesRule(event1, rule1));
assertTrue("2/1", Ruler.matchesRule(event1, rule2));
assertFalse("3/1", Ruler.matchesRule(event1, rule3));
assertTrue("4/1", Ruler.matchesRule(event1, rule4));
assertFalse("1/2", Ruler.matchesRule(event2, rule1));
assertFalse("2/2", Ruler.matchesRule(event2, rule2));
assertFalse("3/2", Ruler.matchesRule(event2, rule3));
assertTrue("4/2", Ruler.matchesRule(event2, rule4));
assertFalse("1/3", Ruler.matchesRule(event3, rule1));
assertTrue("2/3", Ruler.matchesRule(event3, rule2));
assertTrue("3/3", Ruler.matchesRule(event3, rule3));
assertFalse("4/3", Ruler.matchesRule(event3, rule4));
}
@Test
public void WHEN_WeTryReallySimpleRules_THEN_TheyWork() throws Exception {
String rule1 = "{ \"a\" : [ 1 ] }";
String rule2 = "{ \"b\" : [ 2 ] }";
String rule3 = "{ \"x\" : [ \"X\" ] }";
String event1 = "{ \"a\" : 1 }";
String event2 = "{ \"b\" : 2 }";
String event3 = "{ \"x\" : \"X\" }";
String event4 = "{ \"x\" : true }";
assertTrue("1/1", Ruler.matchesRule(event1, rule1));
assertTrue("2/2", Ruler.matchesRule(event2, rule2));
assertTrue("3/3", Ruler.matchesRule(event3, rule3));
assertFalse("4/1", Ruler.matchesRule(event4, rule1));
assertFalse("4/2", Ruler.matchesRule(event4, rule2));
assertFalse("4/3", Ruler.matchesRule(event4, rule3));
}
@Test
public void WHEN_WeTryAnythingButRules_THEN_Theywork() throws Exception {
String rule = "{\n" +
"\"a\": [ { \"anything-but\": [ \"dad0\",\"dad1\",\"dad2\" ] } ],\n" +
"\"b\": [ { \"anything-but\": [ 111, 222, 333 ] } ],\n" +
"\"c\": [ { \"anything-but\": \"zdd\" } ],\n" +
"\"d\": [ { \"anything-but\": 444 } ],\n" +
"\"z\": [ { \"numeric\": [ \">\", 0, \"<\", 1 ] } ],\n" +
"\"w\": [ { \"anything-but\": { \"prefix\": \"zax\" } } ],\n" +
"\"n\": [ { \"anything-but\": { \"suffix\": \"ing\" } } ],\n" +
"\"o\": [ { \"anything-but\": {\"equals-ignore-case\": \"CamelCase\" } } ],\n" +
"\"p\": [ { \"anything-but\": {\"equals-ignore-case\": [\"CamelCase\", \"AbC\"] } } ]\n" +
"}";
String[] events = {
"{" +
" \"a\": \"child1\",\n" +
" \"b\": \"444\",\n" +
" \"c\": \"child1\",\n" +
" \"d\": 123,\n" +
" \"w\": \"xaz\",\n" +
" \"z\": 0.001, \n" +
" \"n\": \"nomatch\", \n" +
" \"o\": \"nomatch\", \n" +
" \"p\": \"nomatch\" \n" +
"}\n",
"{" +
" \"a\": \"dad789\",\n" +
" \"b\": 789,\n" +
" \"c\": \"zdd\",\n" +
" \"d\": 123,\n" +
" \"w\": \"xaz\",\n" +
" \"z\": 0.001, \n" +
" \"n\": \"nomatch\", \n" +
" \"o\": \"nomatch\", \n" +
" \"p\": \"nomatch\" \n" +
"}\n",
"{" +
" \"a\": \"dad789\",\n" +
" \"b\": 789,\n" +
" \"c\": \"child1\",\n" +
" \"d\": 123,\n" +
" \"w\": \"xaz\",\n" +
" \"z\": 1.01, \n" +
" \"n\": \"nomatch\", \n" +
" \"o\": \"nomatch\", \n" +
" \"p\": \"nomatch\" \n" +
"}\n",
"{" +
" \"a\": \"dad1\",\n" +
" \"b\": 345,\n" +
" \"c\": \"child1\",\n" +
" \"d\": 123,\n" +
" \"w\": \"xaz\",\n" +
" \"z\": 0.001, \n" +
" \"n\": \"nomatch\", \n" +
" \"o\": \"nomatch\", \n" +
" \"p\": \"nomatch\" \n" +
"}\n",
"{" +
" \"a\": \"abc\",\n" +
" \"b\": 111,\n" +
" \"c\": \"child1\",\n" +
" \"d\": 123,\n" +
" \"w\": \"xaz\",\n" +
" \"z\": 0.001, \n" +
" \"n\": \"nomatch\", \n" +
" \"o\": \"nomatch\", \n" +
" \"p\": \"nomatch\" \n" +
"}\n",
"{" +
" \"a\": \"dad1\",\n" +
" \"b\": 333,\n" +
" \"c\": \"child1\",\n" +
" \"d\": 123,\n" +
" \"w\": \"xaz\",\n" +
" \"z\": 0.001, \n" +
" \"n\": \"nomatch\", \n" +
" \"o\": \"nomatch\", \n" +
" \"p\": \"nomatch\" \n" +
"}\n",
"{" +
" \"a\": \"abc\",\n" +
" \"b\": 0,\n" +
" \"c\": \"child1\",\n" +
" \"d\": 444,\n" +
" \"w\": \"xaz\",\n" +
" \"z\": 0.999999, \n" +
" \"n\": \"nomatch\", \n" +
" \"o\": \"nomatch\", \n" +
" \"p\": \"nomatch\" \n" +
"}\n",
"{" +
" \"a\": \"child1\",\n" +
" \"b\": \"444\",\n" +
" \"c\": \"child1\",\n" +
" \"d\": 123,\n" +
" \"w\": \"zaxonie\",\n" +
" \"z\": 0.001, \n" +
" \"n\": \"nomatch\", \n" +
" \"o\": \"nomatch\", \n" +
" \"p\": \"nomatch\" \n" +
"}\n",
"{" +
" \"a\": \"child1\",\n" +
" \"b\": \"444\",\n" +
" \"c\": \"child1\",\n" +
" \"d\": 123,\n" +
" \"w\": \"xaz\",\n" +
" \"z\": 0.001, \n" +
" \"n\": \"matching\", \n" +
" \"o\": \"nomatch\", \n" +
" \"p\": \"nomatch\" \n" +
"}\n",
"{" +
" \"a\": \"child1\",\n" +
" \"b\": \"444\",\n" +
" \"c\": \"child1\",\n" +
" \"d\": 123,\n" +
" \"w\": \"xaz\",\n" +
" \"z\": 0.001, \n" +
" \"n\": \"nomatch\", \n" +
" \"o\": \"camelcase\", \n" +
" \"p\": \"nomatch\" \n" +
"}\n",
"{" +
" \"a\": \"child1\",\n" +
" \"b\": \"444\",\n" +
" \"c\": \"child1\",\n" +
" \"d\": 123,\n" +
" \"w\": \"xaz\",\n" +
" \"z\": 0.001, \n" +
" \"n\": \"nomatch\", \n" +
" \"o\": \"nomatch\", \n" +
" \"p\": \"abc\" \n" +
"}\n",
};
boolean[] result = {true, false, false, false, false, false, false, false, false, false, false };
for (int i = 0; i< events.length; i++) {
assertEquals(events[i], result[i], Ruler.matchesRule(events[i], rule));
}
}
@Test
public void WHEN_WeTryEqualsIgnoreCaseRules_THEN_TheyWork() throws Exception {
String rule = "{\n" +
"\"a\": [ { \"equals-ignore-case\": \"aBc\" } ],\n" +
"\"b\": [ { \"equals-ignore-case\": \"Def\" } ],\n" +
"\"c\": [ { \"equals-ignore-case\": \"xyZ\" } ]\n" +
"}";
String[] events = {
"{" +
" \"a\": \"ABC\",\n" +
" \"b\": \"defx\",\n" +
" \"c\": \"xYz\",\n" +
" \"d\": \"rst\"\n" +
"}\n",
"{" +
" \"a\": \"ABC\",\n" +
" \"c\": \"xYz\",\n" +
" \"d\": \"rst\"\n" +
"}\n",
"{" +
" \"a\": \"ABC\",\n" +
" \"b\": \"xYz\",\n" +
" \"c\": \"def\",\n" +
" \"d\": \"rst\"\n" +
"}\n",
"{" +
" \"a\": \"ABC\",\n" +
" \"b\": \"def\",\n" +
" \"c\": \"xYz\",\n" +
" \"d\": \"rst\"\n" +
"}\n"
};
boolean[] result = {false, false, false, true };
for (int i = 0; i< events.length; i++) {
assertEquals(events[i], result[i], Ruler.matchesRule(events[i], rule));
}
}
@Test
public void WHEN_WeTryWildcardRules_THEN_TheyWork() throws Exception {
String rule = "{\n" +
"\"a\": [ { \"wildcard\": \"*bc\" } ],\n" +
"\"b\": [ { \"wildcard\": \"d*f\" } ],\n" +
"\"c\": [ { \"wildcard\": \"xy*\" } ],\n" +
"\"d\": [ { \"wildcard\": \"xy*\" } ]\n" +
"}";
String[] events = {
"{" +
" \"a\": \"abcbc\",\n" +
" \"b\": \"deeeefx\",\n" +
" \"c\": \"xy\",\n" +
" \"d\": \"xyzzz\"\n" +
"}\n",
"{" +
" \"a\": \"abcbc\",\n" +
" \"b\": \"deeeef\",\n" +
" \"d\": \"xyzzz\"\n" +
"}\n",
"{" +
" \"a\": \"abcbc\",\n" +
" \"b\": \"xy\",\n" +
" \"c\": \"deeeef\",\n" +
" \"d\": \"xyzzz\"\n" +
"}\n",
"{" +
" \"a\": \"abcbc\",\n" +
" \"b\": \"deeeef\",\n" +
" \"c\": \"xy\",\n" +
" \"d\": \"xyzzz\"\n" +
"}\n"
};
boolean[] result = {false, false, false, true };
for (int i = 0; i< events.length; i++) {
assertEquals(events[i], result[i], Ruler.matchesRule(events[i], rule));
}
}
}
| 4,847 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/PermutationsGenerator.java | package software.amazon.event.ruler;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class PermutationsGenerator {
private PermutationsGenerator() { }
public static <T> List<T[]> generateAllPermutations(T[] array) {
int numPermutations = IntStream.rangeClosed(1, array.length).reduce((x, y) -> x * y).getAsInt();
List<T[]> result = new ArrayList<>(numPermutations);
generateAllPermutationsRecursive(array.length, array, result);
return result;
}
private static <T> void generateAllPermutationsRecursive(int n, T[] array, List<T[]> result) {
if (n == 1) {
result.add(array.clone());
} else {
for (int i = 0; i < n - 1; i++) {
generateAllPermutationsRecursive(n - 1, array, result);
if (n % 2 == 0) {
swap(array, i, n - 1);
} else {
swap(array, 0, n - 1);
}
}
generateAllPermutationsRecursive(n - 1, array, result);
}
}
private static <T> void swap(T[] input, int a, int b) {
T tmp = input[a];
input[a] = input[b];
input[b] = tmp;
}
} | 4,848 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/EventTest.java | package software.amazon.event.ruler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class EventTest {
private
String[] catchAllRules = {
"{\n" +
" \"Image\": {\n" +
" \"Width\": [ 200 ],\n" +
" \"Height\": [ 200 ],\n" +
" \"Title\": [ \"Whatever\" ],\n" +
" \"Thumbnail\": {\n" +
" \"Url\": [ \"https://foo.com\" ],\n" +
" \"Height\": [ 125 ],\n" +
" \"Width\": [ 225 ]\n" +
" },\n" +
" \"Animated\": [ true ],\n" +
" \"IDs\": [2, 4, 6]\n" +
" }\n" +
"}"
};
private String[] jsonFromRFC = {
" {\n" +
" \"Image\": {\n" +
" \"Width\": 800,\n" +
" \"Height\": 600,\n" +
" \"Title\": \"View from 15th Floor\",\n" +
" \"Thumbnail\": {\n" +
" \"Url\": \"http://www.example.com/image/481989943\",\n" +
" \"Height\": 125,\n" +
" \"Width\": 100\n" +
" },\n" +
" \"Animated\" : false,\n" +
" \"IDs\": [116, 943, 234, 38793]\n" +
" }\n" +
" }",
"{\n" +
" \"version\": \"0\",\n" +
" \"id\": \"ddddd4-aaaa-7777-4444-345dd43cc333\",\n" +
" \"detail-type\": \"EC2 Instance State-change Notification\",\n" +
" \"source\": \"aws.ec2\",\n" +
" \"account\": \"012345679012\",\n" +
" \"time\": \"2017-10-02T16:24:49Z\",\n" +
" \"region\": \"us-east-1\",\n" +
" \"resources\": [\n" +
" \"arn:aws:ec2:us-east-1:012345679012:instance/i-000000aaaaaa00000\"\n" +
" ],\n" +
" \"detail\": {\n" +
" \"c-count\": 5,\n" +
" \"d-count\": 3,\n" +
" \"x-limit\": 301.8,\n" +
" \"instance-id\": \"i-000000aaaaaa00000\",\n" +
" \"state\": \"running\"\n" +
" }\n" +
"}"
};
@Test
public void WHEN_EventIsConstructed_THEN_SimpleArraysAreHandledCorrectly() throws Exception {
Machine m = new Machine();
m.addRule("r1", catchAllRules[0]);
Event e = new Event(jsonFromRFC[0], m);
String[] wantKeys = {
"Image.Animated", "Image.Height", "Image.IDs", "Image.IDs", "Image.IDs", "Image.IDs",
"Image.Thumbnail.Height", "Image.Thumbnail.Url", "Image.Thumbnail.Width", "Image.Title", "Image.Width"
};
String[] wantVals = {
"false", "600", null, null, null, null, "125", "\"http://www.example.com/image/481989943\"",
"100", "\"View from 15th Floor\"", "800"
};
checkFlattening(e, wantKeys, wantVals);
}
@Test
public void WHEN_EventIsConstructed_THEN_HeterogeneousArraysAreHandled() throws Exception {
String hetero = "{\n" +
" \"lines\": [\n" +
" { \n" +
" \"intensities\": [\n" +
" [ 0.5 ]\n" +
" ],\n" +
" \"points\": [\n" +
" [\n" +
" [\n" +
" 483.3474497412421, 287.48116291799363, {\"pp\" : \"index0\"}\n" +
" ],\n" +
" [\n" +
" {\"pp\" : \"index1\"}, 489.9999497412421, 299.99996291799363\n" +
" ]\n" +
" ]\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}";
String rule = "{\n" +
" \"lines\": \n" +
" { \n" +
" \"points\": [287.48116291799363],\n" +
" \"points\": { \n" +
" \"pp\" : [\"index0\"]\n" +
" }\n" +
" }\n" +
"}";
String[] wantedFieldNames = {
"lines.points", "lines.points", "lines.points", "lines.points", "lines.points.pp", "lines.points.pp"
};
String[] wantedArrayMemberships = {
"0[0] 2[0] 1[0] ", "0[0] 2[0] 1[0] ", "0[0] 2[1] 1[0] ", "0[0] 2[1] 1[0] ", "0[0] 2[0] 3[2] 1[0] ",
"0[0] 4[0] 2[1] 1[0] "
};
Machine m = new Machine();
m.addRule("r", rule);
Event e = new Event(hetero, m);
for (int i = 0; i < e.fields.size(); i++) {
assertEquals("testcase #" + i, wantedFieldNames[i], e.fields.get(i).name);
assertEquals("testcase #" + i, wantedArrayMemberships[i], e.fields.get(i).arrayMembership.toString());
}
List<String> res = m.rulesForJSONEvent(hetero);
assertEquals(1, res.size());
assertEquals("r", res.get(0));
}
@Test
public void WHEN_EventsIsConstructed_THEN_NestedArraysAreHandled() throws Exception {
String songs = "{\n" +
" \"Songs\": [\n" +
" {\n" +
" \"Name\": \"Norwegian Wood\",\n" +
" \"Writers\": [\n" +
"\t{\n" +
"\t \"First\": \"John\",\n" +
"\t \"Last\": \"Lennon\"\n" +
"\t},\n" +
"\t{\n" +
"\t \"First\": \"Paul\",\n" +
"\t \"Last\": \"McCartney\"\n" +
"\t}\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"Name\": \"Paint It Black\",\n" +
" \"Writers\": [\n" +
"\t{\n" +
"\t \"First\": \"Keith\",\n" +
"\t \"Last\": \"Richards\"\n" +
"\t},\n" +
"\t{\n" +
"\t \"First\": \"Mick\",\n" +
"\t \"Last\": \"Jagger\"\n" +
"\t}\n" +
" ]\n" +
" }\n" +
" ],\n" +
" \"Z\": 1" +
"}\n";
String songsRule = "{\n" +
" \"Songs\": {\n" +
" \"Name\": [ \"Norwegian Wood\" ],\n" +
" \"Writers\": {\n" +
" \"First\": [ \"John\" ],\n" +
" \"Last\": [ \"Lennon\" ]\n" +
" }\n" +
" }\n" +
"}\n";
String[] wantedKeys = {
"Songs.Name", "Songs.Name",
"Songs.Writers.First", "Songs.Writers.First", "Songs.Writers.First", "Songs.Writers.First",
"Songs.Writers.Last", "Songs.Writers.Last", "Songs.Writers.Last", "Songs.Writers.Last",
"Z"
};
String[] vals = {
"Norwegian Wood", "Paint It Black",
"John", "Keith", "Mick", "Paul",
"Jagger", "Lennon", "McCartney", "Richards",
"Z"
};
String[] membershipStrings = {
"0[0]", "0[1]",
"0[0] 1[0]", "0[1] 2[0]", "0[1] 2[1]", "0[0] 1[1]",
"0[1] 2[1]", "0[0] 1[0]", "0[0] 1[1]", "0[1] 2[0]",
null
};
Map<String, String> wantedMemberships = new HashMap<>();
for (int i = 0; i < vals.length; i++) {
wantedMemberships.put('"' + vals[i] + '"', membershipStrings[i]);
}
Machine m = new Machine();
m.addRule("r1", songsRule);
Event e = new Event(songs, m);
checkFlattening(e, wantedKeys, null);
for (Field f : e.fields) {
assertEquals(f.val, wantedMemberships.get(f.val), f.arrayMembership.toString().trim());
}
}
private void checkFlattening(Event e, String[] wantedKeys, String[] wantedVals) {
for (int i = 0; i < e.fields.size(); i++) {
assertEquals(wantedKeys[i], e.fields.get(i).name);
if (wantedVals != null && wantedVals[i] != null) {
assertEquals(wantedVals[i], e.fields.get(i).val);
}
}
}
@Test
public void WHEN_InvalidJSONIsPresented_THEN_ErrorsAreHandledAppropriately() {
String[] bads = { null, "{ 3 4 5", "[1,2,3]" };
for (String bad : bads) {
try {
Event.flatten(bad);
fail("Should throw exception");
} catch (IllegalArgumentException e) {
// yay
}
}
}
@Test
public void WHEN_VariousShapesOfJSONArePresented_THEN_TheyAreFlattenedCorectly() throws Exception {
String[][] desiredNameVals = {
{
"Image.Animated", "false",
"Image.Height", "600",
"Image.IDs", "116",
"Image.IDs", "943",
"Image.IDs", "234",
"Image.IDs", "38793",
"Image.Thumbnail.Height", "125",
"Image.Thumbnail.Url", "\"http://www.example.com/image/481989943\"",
"Image.Thumbnail.Width", "100",
"Image.Title", "\"View from 15th Floor\"",
"Image.Width", "800"
},
{
"account", "\"012345679012\"",
"detail-type", "\"EC2 Instance State-change Notification\"",
"detail.c-count", "5",
"detail.d-count", "3",
"detail.instance-id", "\"i-000000aaaaaa00000\"",
"detail.state", "\"running\"",
"detail.x-limit", "301.8",
"id", "\"ddddd4-aaaa-7777-4444-345dd43cc333\"",
"region", "\"us-east-1\"",
"resources", "\"arn:aws:ec2:us-east-1:012345679012:instance/i-000000aaaaaa00000\"",
"source", "\"aws.ec2\"",
"time", "\"2017-10-02T16:24:49Z\"",
"version", "\"0\"",
}
};
ObjectMapper objectMapper = new ObjectMapper();
for (int i = 0; i < jsonFromRFC.length; i++) {
String json = jsonFromRFC[i];
// test method which accepts raw json
List<String> nameVals = Event.flatten(json);
// test method which accepts parsed json
JsonNode rootNode = objectMapper.readTree(json);
List<String> nameValsWithParsedJson = Event.flatten(rootNode);
// verify both paths tpo flatten an event produce equivalent results
assertEquals(nameValsWithParsedJson, nameVals);
assertEquals(desiredNameVals[i].length, nameVals.size());
for (int j = 0; j < nameVals.size(); j++) {
assertEquals(desiredNameVals[i][j], nameVals.get(j));
}
}
}
@Test
public void WHEN_PathsOfVariousLengthsAreStringified_THEN_TheyAreCorrect() {
Stack<String> stack = new Stack<>();
assertEquals("", Event.pathName(stack));
stack.push("foo");
assertEquals("foo", Event.pathName(stack));
stack.push("bar");
assertEquals("foo.bar", Event.pathName(stack));
stack.push("baz");
assertEquals("foo.bar.baz", Event.pathName(stack));
stack.pop();
assertEquals("foo.bar", Event.pathName(stack));
}
@Test
public void WHEN_NameValPairsAreStored_ListsAreReturnedAppropriately() {
Map<String, List<String>> map = new HashMap<>();
Stack<String> stack = new Stack<>();
stack.push("foo");
Event.recordNameVal(map, stack, "bar");
stack.pop();
stack.push("x");
stack.push("y");
Event.recordNameVal(map, stack, "1");
Event.recordNameVal(map, stack, "2");
assertNull(map.get("z"));
List<String> a = map.get("foo");
assertEquals(1, a.size());
assertTrue(a.contains("bar"));
a = map.get("x.y");
assertEquals(2, a.size());
assertTrue(a.contains("1"));
assertTrue(a.contains("2"));
}
} | 4,849 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/JsonRuleCompilerTest.java | package software.amazon.event.ruler;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class JsonRuleCompilerTest {
@Test
public void testBigNumbers() throws Exception {
Machine m = new Machine();
String rule = "{\n" +
" \"account\": [ 123456789012 ]\n" +
"}";
String event = "{\"account\": 123456789012 }";
m.addRule("r1", rule);
assertEquals(1, m.rulesForJSONEvent(event).size());
}
@Test
public void testPrefixEqualsIgnoreCaseCompile() {
String json = "{\"a\": [ { \"prefix\": { \"equals-ignore-case\": \"child\" } } ] }";
assertNull("Good prefix equals-ignore-case should parse", JsonRuleCompiler.check(json));
}
@Test
public void testSuffixEqualsIgnoreCaseCompile() {
String json = "{\"a\": [ { \"suffix\": { \"equals-ignore-case\": \"child\" } } ] }";
assertNull("Good suffix equals-ignore-case should parse", JsonRuleCompiler.check(json));
}
@Test
public void testVariantForms() throws Exception {
Machine m = new Machine();
String r1 = "{\n" +
" \"a\": [ 133.3 ]\n" +
"}";
String r2 = "{\n" +
" \"a\": [ { \"numeric\": [ \">\", 120, \"<=\", 140 ] } ]\n" +
"}";
String r3 = "{\n" +
" \"b\": [ \"192.0.2.0\" ]\n" +
"}\n";
String r4 = "{\n" +
" \"b\": [ { \"cidr\": \"192.0.2.0/24\" } ]\n" +
"}";
String event = "{\n" +
" \"a\": 133.3,\n" +
" \"b\": \"192.0.2.0\"\n" +
"}";
m.addRule("r1", r1);
m.addRule("r2", r2);
m.addRule("r3", r3);
m.addRule("r4", r4);
List<String> nr = m.rulesForJSONEvent(event);
assertEquals(4, nr.size());
}
@Test
public void testCompile() throws Exception {
String j = "[1,2,3]";
assertNotNull("Top level must be an object", JsonRuleCompiler.check(j));
InputStream is = new ByteArrayInputStream(j.getBytes(StandardCharsets.UTF_8));
assertNotNull("Top level must be an object (bytes)", JsonRuleCompiler.check(is));
j = "{\"a\":1}";
assertNotNull("Values must be in an array", JsonRuleCompiler.check(j.getBytes(StandardCharsets.UTF_8)));
j = "{\"a\":[ { \"x\":2 } ]}";
assertNotNull("Array values must be primitives", JsonRuleCompiler.check(new StringReader(j)));
j = "{ \"foo\": {}}";
assertNotNull("Objects must not be empty", JsonRuleCompiler.check(new StringReader(j)));
j = "{ \"foo\": []}";
assertNotNull("Arrays must not be empty", JsonRuleCompiler.check(new StringReader(j)));
j = "{\"a\":[1]}";
assertNull(JsonRuleCompiler.check(j));
Map<String, List<Patterns>> m = JsonRuleCompiler.compile(new ByteArrayInputStream(j.getBytes(StandardCharsets.UTF_8))).get(0);
List<Patterns> l = m.get("a");
assertEquals(2, l.size());
for (Patterns p : l) {
ValuePatterns vp = (ValuePatterns) p;
if (p.type() == MatchType.NUMERIC_EQ) {
assertEquals(ComparableNumber.generate(1.0), vp.pattern());
} else {
assertEquals("1", vp.pattern());
}
}
j = "{\"a\": [ { \"prefix\": \"child\" } ] }";
assertNull("Good prefix should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"suffix\": \"child\" } ] }";
assertNull("Good suffix should parse", RuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": \"child\" } ] }";
assertNull("Good anything-but should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": [\"child0\",\"child1\",\"child2\"] } ] }";
assertNull("Good anything-but should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": [111,222,333] } ] }";
assertNull("Good anything-but should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": \"child0\" } ] }";
assertNull("Good anything-but should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": 111 } ] }";
assertNull("Good anything-but should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": { \"prefix\": \"foo\" } } ] }";
assertNull("Good anything-but should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": { \"suffix\": \"foo\" } } ] }";
assertNull("Good anything-but should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": {\"equals-ignore-case\": \"rule\" } } ] }";
assertNull("Good anything-but/ignore-case should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": {\"equals-ignore-case\": [\"abc\", \"123\"] } } ] }";
assertNull("Good anything-but/ignore-case should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"exactly\": \"child\" } ] }";
assertNull("Good exact-match should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"exists\": true } ] }";
assertNull("Good exists true should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"exists\": false } ] }";
assertNull("Good exists false should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"cidr\": \"10.0.0.0/8\" } ] }";
assertNull("Good CIDR should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"equals-ignore-case\": \"abc\" } ] }";
assertNull("Good equals-ignore-case should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"wildcard\": \"a*b*c\" } ] }";
assertNull("Good wildcard should parse", JsonRuleCompiler.check(j));
String[] badPatternTypes = {
"{\"a\": [ { \"exactly\": 33 } ] }",
"{\"a\": [ { \"prefix\": \"child\", \"foo\": [] } ] }",
"{\"a\": [ { \"prefix\": 3 } ] }",
"{\"a\": [ { \"prefix\": [1, 2 3] } ] }",
"{\"a\": [ { \"suffix\": \"child\", \"foo\": [] } ] }",
"{\"a\": [ { \"suffix\": 3 } ] }",
"{\"a\": [ { \"suffix\": [1, 2 3] } ] }",
"{\"a\": [ { \"foo\": \"child\" } ] }",
"{\"a\": [ { \"cidr\": \"foo\" } ] }",
"{\"a\": [ { \"anything-but\": \"child\", \"foo\": [] } ] }",
"{\"a\": [ { \"anything-but\": [1, 2 3] } ] }",
"{\"a\": [ { \"anything-but\": \"child\", \"foo\": [] } ] }",
"{\"a\": [ { \"anything-but\": [\"child0\",111,\"child2\"] } ] }",
"{\"a\": [ { \"anything-but\": [1, 2 3] } ] }",
"{\"a\": [ { \"anything-but\": { \"foo\": 3 } ] }",
"{\"a\": [ { \"anything-but\": { \"prefix\": 27 } } ] }",
"{\"a\": [ { \"anything-but\": { \"prefix\": \"\" } } ] }",
"{\"a\": [ { \"anything-but\": { \"prefix\": \"foo\", \"a\":1 } } ] }",
"{\"a\": [ { \"anything-but\": { \"prefix\": \"foo\" }, \"x\": 1 } ] }",
"{\"a\": [ { \"anything-but\": { \"suffix\": 27 } } ] }",
"{\"a\": [ { \"anything-but\": { \"suffix\": \"\" } } ] }",
"{\"a\": [ { \"anything-but\": { \"suffix\": \"foo\", \"a\":1 } } ] }",
"{\"a\": [ { \"anything-but\": { \"suffix\": \"foo\" }, \"x\": 1 } ] }",
"{\"a\": [ { \"anything-but\" : { \"equals-ignore-case\": [1, 2 3] } } ] }",
"{\"a\": [ { \"anything-but\": {\"equals-ignore-case\": [1, 2, 3] } } ] }", // no numbers
"{\"a\": [ { \"equals-ignore-case\": 5 } ] }",
"{\"a\": [ { \"equals-ignore-case\": [ \"abc\" ] } ] }",
"{\"a\": [ { \"prefix\": { \"invalid-expression\": [ \"abc\" ] } } ] }",
"{\"a\": [ { \"prefix\": { \"equals-ignore-case\": 5 } } ] }",
"{\"a\": [ { \"prefix\": { \"equals-ignore-case\": [ \"abc\" ] } } ] }",
"{\"a\": [ { \"prefix\": { \"equals-ignore-case\": \"abc\", \"test\": \"def\" } } ] }",
"{\"a\": [ { \"prefix\": { \"equals-ignore-case\": \"abc\" }, \"test\": \"def\" } ] }",
"{\"a\": [ { \"prefix\": { \"equals-ignore-case\": [ 1, 2 3 ] } } ] }",
"{\"a\": [ { \"suffix\": { \"invalid-expression\": [ \"abc\" ] } } ] }",
"{\"a\": [ { \"suffix\": { \"equals-ignore-case\": 5 } } ] }",
"{\"a\": [ { \"suffix\": { \"equals-ignore-case\": [ \"abc\" ] } } ] }",
"{\"a\": [ { \"suffix\": { \"equals-ignore-case\": \"abc\", \"test\": \"def\" } } ] }",
"{\"a\": [ { \"suffix\": { \"equals-ignore-case\": \"abc\" }, \"test\": \"def\" } ] }",
"{\"a\": [ { \"suffix\": { \"equals-ignore-case\": [ 1, 2 3 ] } } ] }",
"{\"a\": [ { \"wildcard\": 5 } ] }",
"{\"a\": [ { \"wildcard\": [ \"abc\" ] } ] }"
};
for (String badPattern : badPatternTypes) {
assertNotNull("bad pattern shouldn't parse", JsonRuleCompiler.check(badPattern));
}
j = "{\n"
+ " \"resources\": [\n"
+ " \"r1\",\n"
+ " \"r2\"\n"
+ " ]\n"
+ "}";
m = JsonRuleCompiler.compile(j).get(0);
l = m.get("resources");
assertEquals(2, l.size());
ValuePatterns vp1 = (ValuePatterns) l.get(0);
ValuePatterns vp2 = (ValuePatterns) l.get(1);
assertEquals("\"r1\"", vp1.pattern());
assertEquals("\"r2\"", vp2.pattern());
j = "{\n"
+ " \"detail-getType\": [ \"ec2/spot-bid-matched\" ],\n"
+ " \"detail\" : { \n"
+ " \"state\": [ \"in-service\", \"dead\" ]\n"
+ " }\n"
+ "}\n";
m = JsonRuleCompiler.compile(j).get(0);
assertEquals(2, m.size());
l = m.get("detail-getType");
vp1 = (ValuePatterns) l.get(0);
assertEquals("\"ec2/spot-bid-matched\"", vp1.pattern());
l = m.get("detail.state");
assertEquals(2, l.size());
vp1 = (ValuePatterns) l.get(0);
vp2 = (ValuePatterns) l.get(1);
assertEquals("\"in-service\"", vp1.pattern());
assertEquals("\"dead\"", vp2.pattern());
}
@Test
public void testNumericExpressions() {
String[] goods = {
"[\"=\", 3.8]", "[\"=\", 0.00000033]", "[\"=\", -4e-8]", "[\"=\", 55555]",
"[\"<\", 3.8]", "[\"<\", 0.00000033]", "[\"<\", -4e-8]", "[\"<\", 55555]",
"[\">\", 3.8]", "[\">\", 0.00000033]", "[\">\", -4e-8]", "[\">\", 55555]",
"[\"<=\", 3.8]", "[\"<=\", 0.00000033]", "[\"<=\", -4e-8]", "[\"<=\", 55555]",
"[\">=\", 3.8]", "[\">=\", 0.00000033]", "[\">=\", -4e-8]", "[\">=\", 55555]",
"[\">\", 0, \"<\", 1]", "[\">=\", 0, \"<\", 1]",
"[\">\", 0, \"<=\", 1]", "[\">=\", 0, \"<=\", 1]"
};
String[] bads = {
"[\"=\", true]", "[\"=\", 2.0e22]", "[\"=\", \"-4e-8\"]", "[\"=\"]",
"[\"<\", true]", "[\"<\", 2.0e22]", "[\"<\", \"-4e-8\"]", "[\"<\"]",
"[\">=\", true]", "[\">=\", 2.0e22]", "[\">=\", \"-4e-8\"]", "[\">=\"]",
"[\"<=\", true]", "[\"<=\", 2.0e22]", "[\"<=\", \"-4e-8\"]", "[\"<=\"]",
"[\"<>\", 1, \">\", 0]", "[\"==\", 1, \">\", 0]",
"[\"<\", 1, \">\", 0]", "[\">\", 1, \"<\", 1]",
"[\">\", 30, \"<\", 1]", "[\">\", 1, \"<\", 30, false]"
};
for (String good : goods) {
String json = "{\"x\": [{\"numeric\": " + good + "}]}";
String m = JsonRuleCompiler.check(json);
assertNull(json + " => " + m, m);
}
for (String bad : bads) {
String json = "{\"x\": [{\"numeric\": " + bad + "}]}";
String m = JsonRuleCompiler.check(json);
assertNotNull("Bad: " + json, m);
}
}
@Test
public void testExistsExpression() {
String[] goods = {
"true ",
" false "
};
String[] bads = {
"\"badString\"",
"\"= abc\"",
"true, \"extraKey\": \"extraValue\" "
};
for (String good : goods) {
String json = "{\"x\": [{\"exists\": " + good + "}]}";
String m = JsonRuleCompiler.check(json);
assertNull(json + " => " + m, m);
}
for (String bad : bads) {
String json = "{\"x\": [{\"exists\": " + bad + "}]}";
String m = JsonRuleCompiler.check(json);
assertNotNull("Bad: " + json, m);
}
}
@Test
public void testEnd2End() throws Exception {
Machine machine = new Machine();
String[] event = {
"account", "\"012345678901\"",
"detail-getType", "\"ec2/spot-bid-matched\"",
"detail.instanceId", "arn:aws:ec2:us-east-1::image/ami-1a2b3c4d\"",
"detail.spotInstanceRequestId", "\"eaa472d8-8422-a9bb-8888-4919fd99310\"",
"detail.state", "\"in-service\"",
"detail.requestParameters.zone", "\"us-east-1a\"",
"id", "\"cdc73f9d-aea9-11e3-9d5a-835b769c0d9c\"",
"region", "\"us-west-2\"",
"resources", "\"arn:aws:ec2:us-east-1::image/ami-1a2b3c4d\"",
"source", "\"aws.ec2\"",
"tags", "\"2015Q1",
"tags", "\"Euro-fleet\"",
"time", "\"2014-03-18T14:30:07Z\"",
"version", "\"0\"",
};
String rule1 = "{\n"
+ " \"resources\": [\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-1a2b3c4d\",\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-98765432\"\n"
+ " ]\n"
+ "}\n";
String rule2 = "{\n"
+ " \"detail-getType\": [ \"ec2/spot-bid-matched\" ],\n"
+ " \"detail\" : { \n"
+ " \"state\": [ \"in-service\" ]\n"
+ " }\n"
+ "}\n";
String rule3 = "{\n"
+ " \"tags\": [ \"Euro-fleet\", \"Asia-fleet\" ]\n"
+ "}\n";
String rule4 = "{\n"
+ " \"resources\": [\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-1a2b3c4d\",\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-98765432\"\n"
+ " ],\n"
+ " \"detail.state\": [ \"halted\", \"pending\"]\n"
+ "}\n";
String rule5 = "{\n"
+ " \"resources\": [\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-1a2b3c4d\",\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-98765432\"\n"
+ " ],\n"
+ " \"detail.request-level\": [ \"urgent\"]\n"
+ "}\n";
String rule6 = "{\n"
+ " \"detail-getType\": [ \"ec2/spot-bid-matched\" ],\n"
+ " \"detail\" : { \n"
+ " \"requestParameters\": {\n"
+ " \"zone\": [\n"
+ " \"us-east-1a\"\n"
+ " ]\n"
+ " }\n"
+ " }\n"
+ "}\n";
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
machine.addRule("rule3", rule3);
machine.addRule("rule4", rule4);
machine.addRule("rule5", rule5);
machine.addRule("rule6", rule6);
List<String> found = machine.rulesForEvent(event);
assertEquals(4, found.size());
assertTrue(found.contains("rule1"));
assertTrue(found.contains("rule2"));
assertTrue(found.contains("rule3"));
assertTrue(found.contains("rule6"));
}
@Test
public void testBasicFunctionOfOrRelationshipRules() throws Exception {
final Machine machine = new Machine();
String event = "{\n" +
" \"detail\": {\n" +
" \"detail-type\": \"EC2 Instance State-change Notification\",\n" +
" \"resources\": \"arn:aws:ec2:us-east-1:123456789012:instance/i-000000aaaaaa00000\",\n" +
" \"info\": {\n" +
" \"state-status\": \"running\",\n" +
" \"state-count\": {\n" +
" \"count\": 100\n" +
" }\n" +
" },\n" +
" \"c-count\": 1,\n" +
" \"d-count\": 8\n" +
" },\n" +
" \"news\": {\n" +
" \"newsProviders\": \"p1\",\n" +
" \"newCondition1\": \"news111\",\n" +
" \"newCondition2\": \"news222\"\n" +
" }\n" +
"}";
String rule1 = "{\n" +
" \"detail\": {\n" +
" \"$or\" : [\n" +
" {\"c-count\": [ { \"numeric\": [ \">\", 0, \"<=\", 5 ] } ]},\n" +
" {\"d-count\": [ { \"numeric\": [ \"<\", 10 ] } ]},\n" +
" {\"x-limit\": [ { \"numeric\": [ \"=\", 3.018e2 ] } ]}\n" +
" ]\n" +
" }\n" +
"}";
String rule2 = "{\n" +
" \"detail\": {\n" +
" \"detail-type\": [ \"EC2 Instance State-change Notification\" ],\n" +
" \"resources\": [ \"arn:aws:ec2:us-east-1:123456789012:instance/i-000000aaaaaa00000\" ],\n" +
" \"info\": {\n" +
" \"state-status\": [ \"initializing\", \"running\" ],\n" +
" \"state-count\" : { \n" +
" \"count\" : [ 100 ]\n" +
" }\n" +
" },\n" +
" \"$or\" : [\n" +
" {\"c-count\": [ { \"numeric\": [ \">\", 0, \"<=\", 5 ] } ]},\n" +
" {\"d-count\": [ { \"numeric\": [ \"<\", 10 ] } ]},\n" +
" {\"x-limit\": [ { \"numeric\": [ \"=\", 3.018e2 ] } ]}\n" +
" ]\n" +
" },\n" +
" \"news\": {\n" +
" \"newsProviders\": [ \"p1\", \"p2\" ],\n" +
" \"$or\" : [\n" +
" {\"newCondition1\": [ \"news111\" ] },\n" +
" {\"newCondition2\": [ \"news222\"] }\n" +
" ]\n" +
" }\n" +
"}";
List<Map<String, List<Patterns>>> compiledRules;
compiledRules = JsonRuleCompiler.compile(rule1);
assertEquals(3, compiledRules.size());
compiledRules = JsonRuleCompiler.compile(rule2);
assertEquals(6, compiledRules.size());
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
List<String> found = machine.rulesForJSONEvent(event);
assertEquals(2, found.size());
assertTrue(found.contains("rule1"));
assertTrue(found.contains("rule2"));
machine.deleteRule("rule1", rule1);
found = machine.rulesForJSONEvent(event);
assertEquals(1, found.size());
machine.deleteRule("rule2", rule2);
found = machine.rulesForJSONEvent(event);
assertEquals(0, found.size());
assertTrue(machine.isEmpty());
}
@Test
public void testMoreCaseOfOrRelationshipRules() throws Exception {
final Machine machine = new Machine();
final JsonNode rules = GenericMachineTest.readAsTree("orRelationshipRules.json");
assertTrue(rules.isArray());
assertTrue(machine.isEmpty());
final int expectedSubRuleSize [] = {2, 4, 3, 4, 2};
final String expectedCompiledRules [] = {
"[{metricName=[VP:\"CPUUtilization\" (T:EXACT), VP:\"ReadLatency\" (T:EXACT)]}, {namespace=[VP:\"AWS/EC2\" (T:EXACT), VP:\"AWS/ES\" (T:EXACT)]}]",
"[{detail.source=[VP:\"aws.cloudwatch\" (T:EXACT)], metricName=[VP:\"CPUUtilization\" (T:EXACT), VP:\"ReadLatency\" (T:EXACT)]}, {namespace=[VP:\"AWS/EC2\" (T:EXACT), VP:\"AWS/ES\" (T:EXACT)], detail.source=[VP:\"aws.cloudwatch\" (T:EXACT)]}, {detail.detail-type=[VP:\"CloudWatch Alarm State Change\" (T:EXACT)], metricName=[VP:\"CPUUtilization\" (T:EXACT), VP:\"ReadLatency\" (T:EXACT)]}, {namespace=[VP:\"AWS/EC2\" (T:EXACT), VP:\"AWS/ES\" (T:EXACT)], detail.detail-type=[VP:\"CloudWatch Alarm State Change\" (T:EXACT)]}]",
"[{source=[VP:\"aws.cloudwatch\" (T:EXACT)], metricName=[VP:\"CPUUtilization\" (T:EXACT), VP:\"ReadLatency\" (T:EXACT)]}, {namespace=[VP:\"AWS/EC2\" (T:EXACT), VP:\"AWS/ES\" (T:EXACT)], metricType=[VP:\"MetricType\" (T:EXACT)], source=[VP:\"aws.cloudwatch\" (T:EXACT)]}, {source=[VP:\"aws.cloudwatch\" (T:EXACT)], scope=[VP:\"Service\" (T:EXACT)]}]",
"[{source=[VP:\"aws.cloudwatch\" (T:EXACT)], metricName=[VP:\"CPUUtilization\" (T:EXACT), VP:\"ReadLatency\" (T:EXACT)]}, {namespace=[VP:\"AWS/EC2\" (T:EXACT), VP:\"AWS/ES\" (T:EXACT)], metricType=[VP:\"MetricType\" (T:EXACT)], source=[VP:\"aws.cloudwatch\" (T:EXACT)], metricId=[VP:11C379816DD880 (T:NUMERIC_EQ), VP:1234 (T:EXACT)]}, {namespace=[VP:\"AWS/EC2\" (T:EXACT), VP:\"AWS/ES\" (T:EXACT)], metricType=[VP:\"MetricType\" (T:EXACT)], spaceId=[VP:11C379737B4A00 (T:NUMERIC_EQ), VP:1000 (T:EXACT)], source=[VP:\"aws.cloudwatch\" (T:EXACT)]}, {source=[VP:\"aws.cloudwatch\" (T:EXACT)], scope=[VP:\"Service\" (T:EXACT)]}]",
"[{detail.state.value=[VP:\"ALARM\" (T:EXACT)], source=[VP:\"aws.cloudwatch\" (T:EXACT)], withConfiguration.metrics.metricStat.metric.namespace=[VP:\"AWS/EC2\" (T:EXACT)]}, {detail.state.value=[VP:\"ALARM\" (T:EXACT)], source=[VP:\"aws.cloudwatch\" (T:EXACT)], withoutConfiguration.metric.name=[VP:\"AWS/Default\" (T:EXACT)]}]"
};
int i = 0;
List<Map<String, List<Patterns>>> compiledRules;
for (final JsonNode rule : rules) {
String ruleStr = rule.toString();
compiledRules = JsonRuleCompiler.compile(ruleStr);
assertEquals(expectedCompiledRules[i], compiledRules.toString());
assertEquals(expectedSubRuleSize[i], compiledRules.size());
machine.addRule("rule-" + i, ruleStr);
i++;
}
assertTrue(!machine.isEmpty());
// after delete the rule, verify the machine become empty again.
i = 0;
for (final JsonNode rule : rules) {
machine.deleteRule("rule-" + i, rule.toString());
i++;
}
assertTrue(machine.isEmpty());
}
@Test
public void testWrongOrRelationshipRules() throws Exception {
// enable the "$or" feature
final Machine machine = new Machine();
final JsonNode rules = GenericMachineTest.readAsTree("wrongOrRelationshipRules.json");
assertTrue(rules.isArray());
int i = 0;
for (final JsonNode rule : rules) {
try {
machine.addRule("rule-"+i, rule.toString());
} catch (JsonParseException e) {
i++;
}
}
// verify each rule had thrown JsonParseException.
assertEquals(rules.size(), i);
}
@Test
public void testOrFieldCanKeepWorkingInLegacyRuleCompiler() throws Exception {
// Not enable any feature when construct the Machine.
final Machine machine = new Machine();
// there are 3 rules in the file, all of them are wrong to use $or tag
final JsonNode rules = GenericMachineTest.readAsTree("normalRulesWithOrWording.json");
assertTrue(rules.isArray());
assertTrue(machine.isEmpty());
final String expectedCompiledRules [] = {
"{$or=[0A000000/0A0000FF:false/false (T:NUMERIC_RANGE)]}",
"{$or.namespace=[VP:\"AWS/EC2\" (T:EXACT), VP:\"AWS/ES\" (T:EXACT)], source=[VP:\"aws.cloudwatch\" (T:EXACT)], $or.metricType=[VP:\"MetricType\" (T:EXACT)]}",
"{detail.$or=[11C37937E08000/11C379382CCB40:true/false (T:NUMERIC_RANGE), 0A000000/0AFFFFFF:false/false (T:NUMERIC_RANGE)], time=[VP:\"2017-10-02 (T:PREFIX)]}",
"{detail.$or=[11C37937E08000/11C379382CCB40:true/false (T:NUMERIC_RANGE), 11C37938791680/2386F26FC10000:true/false (T:NUMERIC_RANGE)]}"
};
int i = 0;
// verify the legacy rules with using "$or" as normal field can work correctly with legacy RuleCompiler
for (final JsonNode rule : rules) {
machine.addRule("Rule-" + i, rule.toString());
Map<String, List<Patterns>> r = RuleCompiler.compile(rule.toString());
assertEquals(expectedCompiledRules[i], r.toString());
i++;
}
// verify each rule had thrown JsonParseException.
assertEquals(rules.size(), i);
assertTrue(!machine.isEmpty());
// verify the legacy rules with using "$or" as normal field can not work with the new JsonRuleCompiler
i = 0;
for (final JsonNode rule : rules) {
try {
machine.deleteRule("Rule-" + i, rule.toString());
JsonRuleCompiler.compile(rule.toString());
} catch (JsonParseException e) {
i++;
}
}
// verify each rule had thrown JsonParseException.
assertEquals(rules.size(), i);
// after delete the rule, verify the machine become empty again.
assertTrue(machine.isEmpty());
}
@Test
public void testWildcardConsecutiveWildcards() throws IOException {
try {
JsonRuleCompiler.compile("{\"key\": [{\"wildcard\": \"abc**def\"}]}");
fail("Expected JSONParseException");
} catch (JsonParseException e) {
assertEquals("Consecutive wildcard characters at pos 4\n" +
" at [Source: (String)\"{\"key\": [{\"wildcard\": \"abc**def\"}]}\"; line: 1, column: 33]",
e.getMessage());
}
}
@Test
public void testWildcardInvalidEscapeCharacter() throws IOException {
try {
JsonRuleCompiler.compile("{\"key\": [{\"wildcard\": \"a*c\\def\"}]}");
fail("Expected JSONParseException");
} catch (JsonParseException e) {
assertEquals("Unrecognized character escape 'd' (code 100)\n" +
" at [Source: (String)\"{\"key\": [{\"wildcard\": \"a*c\\def\"}]}\"; line: 1, column: 29]",
e.getMessage());
}
}
}
| 4,850 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/CIDRTest.java | package software.amazon.event.ruler;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class CIDRTest {
@Test
public void SpotMalformedCIDRs() {
String[] badCIDrs = {
"192.168.0.1/33",
"foo",
"foo/bar/baz",
"192.168.0.1/foo",
"192.168.0.1/-3424",
"snorkle/3",
"10.10.10.10.10/3",
"2.1.0.-1/3",
"2400:6500:3:3:3:3:3:3:3:3FF00::36FB:1F80/122",
"2400:6500:3:3:-5:3:3:3:3:3FF00::36FB:1F80/122",
"2400:6500:3:3:3:3:FFFFFFFFFFF:3:3:3FF00::36FB:1F80/122",
"2400:6500:FF00::36FB:1F80/222"
};
for (String bad : badCIDrs) {
try {
CIDR.cidr(bad);
fail("Allowed bad CIDR: " + bad);
} catch (Exception e) {
//yay
}
}
}
@Test
public void testToStringFailures() {
String[] bads = {
"700.168.0.1",
"foo",
"foo/bar/baz",
"192.-3.0.1",
"snorkle",
"10.10.10.10.10",
"2.1.0.-1",
"2400:6500:3:3:-5:3:3:3:3:3FF00::36FB:1F80",
"2400:6500:3:3:3:3:FFFFFFFFFFF:3:3:3FF00::36FB:1F80/122"
};
for (String bad : bads) {
assertEquals(bad, CIDR.ipToStringIfPossible(bad));
}
}
@Test
public void TestDigitSequence() {
byte[] l = Range.digitSequence((byte) '4', (byte) 'C', false, false);
byte[] wanted = {'5', '6', '7', '8', '9', 'A', 'B'};
for (int i = 0; i < wanted.length; i++) {
assertEquals(wanted[i], l[i]);
}
l = Range.digitSequence((byte) '4', (byte) 'C', true, false);
byte[] wanted2 = {'4', '5', '6', '7', '8', '9', 'A', 'B'};
for (int i = 0; i < wanted2.length; i++) {
assertEquals(wanted2[i], l[i]);
}
l = Range.digitSequence((byte) '4', (byte) 'C', false, true);
byte[] wanted3 = {'5', '6', '7', '8', '9', 'A', 'B', 'C'};
for (int i = 0; i < wanted3.length; i++) {
assertEquals(wanted3[i], l[i]);
}
l = Range.digitSequence((byte) '4', (byte) 'C', true, true);
byte[] wanted4 = {'4', '5', '6', '7', '8', '9', 'A', 'B', 'C'};
for (int i = 0; i < wanted4.length; i++) {
assertEquals(wanted4[i], l[i]);
}
byte F = (byte) 'F';
try {
byte[] got;
got = Range.digitSequence((byte) 'F', (byte) 'F', false, true);
assertEquals(1, got.length);
assertEquals(F, got[0]);
Range.digitSequence((byte) 'F', (byte) 'F', true, false);
assertEquals(1, got.length);
assertEquals(F, got[0]);
} catch (RuntimeException e) {
fail("Blew up on F-F seq");
}
}
@Test
public void TestToString() {
String[] addresses = {
"0011:2233:4455:6677:8899:aabb:ccdd:eeff",
"2001:db8::ff00:42:8329",
"::1",
"10.0.0.0",
"54.240.196.171",
"192.0.2.0",
"13.32.0.0",
"27.0.0.0",
"52.76.128.0",
"34.192.0.0",
"2400:6500:FF00::36FB:1F80",
"2600:9000::",
"2600:1F11::",
"2600:1F14::"
};
String[] wanted= {
"00112233445566778899AABBCCDDEEFF",
"20010DB8000000000000FF0000428329",
"00000000000000000000000000000001",
"0A000000",
"36F0C4AB",
"C0000200",
"0D200000",
"1B000000",
"344C8000",
"22C00000",
"24006500FF0000000000000036FB1F80",
"26009000000000000000000000000000",
"26001F11000000000000000000000000",
"26001F14000000000000000000000000"
};
for (int i = 0; i < addresses.length; i++) {
assertEquals(addresses[i], wanted[i], CIDR.ipToString(addresses[i]));
}
}
@Test
public void TestCorrectRanges() {
String[] addresses = {
// The first few do not specify the minimum IP address of the CIDR range. But these are still real
// CIDRs. We must calculate the floor of the CIDR range ourselves.
"0011:2233:4455:6677:8899:aabb:ccdd:eeff/24",
"2001:db8::ff00:42:8329/24",
"::1/24",
"10.0.0.0/24",
"54.240.196.171/24",
"192.0.2.0/24",
"13.32.0.0/15",
"27.0.0.0/22",
"52.76.128.0/17",
"34.192.0.0/12",
"2400:6500:FF00::36FB:1F80/122",
"2600:9000::/28",
"2600:1F11::/36",
"2600:1F14::/35"
};
String[] wanted = {
"00112200000000000000000000000000/001122FFFFFFFFFFFFFFFFFFFFFFFFFF:false/false (T:NUMERIC_RANGE)",
"20010D00000000000000000000000000/20010DFFFFFFFFFFFFFFFFFFFFFFFFFF:false/false (T:NUMERIC_RANGE)",
"00000000000000000000000000000000/000000FFFFFFFFFFFFFFFFFFFFFFFFFF:false/false (T:NUMERIC_RANGE)",
"0A000000/0A0000FF:false/false (T:NUMERIC_RANGE)",
"36F0C400/36F0C4FF:false/false (T:NUMERIC_RANGE)",
"C0000200/C00002FF:false/false (T:NUMERIC_RANGE)",
"0D200000/0D21FFFF:false/false (T:NUMERIC_RANGE)",
"1B000000/1B0003FF:false/false (T:NUMERIC_RANGE)",
"344C8000/344CFFFF:false/false (T:NUMERIC_RANGE)",
"22C00000/22CFFFFF:false/false (T:NUMERIC_RANGE)",
"24006500FF0000000000000036FB1F80/24006500FF0000000000000036FB1FBF:false/false (T:NUMERIC_RANGE)",
"26009000000000000000000000000000/2600900FFFFFFFFFFFFFFFFFFFFFFFFF:false/false (T:NUMERIC_RANGE)",
"26001F11000000000000000000000000/26001F110FFFFFFFFFFFFFFFFFFFFFFF:false/false (T:NUMERIC_RANGE)",
"26001F14000000000000000000000000/26001F141FFFFFFFFFFFFFFFFFFFFFFF:false/false (T:NUMERIC_RANGE)"
};
Machine m = new Machine();
for (int i = 0; i < addresses.length; i++) {
String addr = addresses[i];
Range c = CIDR.cidr(addr);
tryAddingAsRule(m, c);
assertEquals(wanted[i], c.toString());
}
}
@Test
public void TestCorrectRangesForSingleIpAddress() {
String[] addresses = {
"0011:2233:4455:6677:8899:aabb:ccdd:eeff",
"2001:db8::ff00:42:8329",
"::0",
"::3",
"::9",
"::a",
"::f",
"2400:6500:FF00::36FB:1F80",
"2400:6500:FF00::36FB:1F85",
"2400:6500:FF00::36FB:1F89",
"2400:6500:FF00::36FB:1F8C",
"2400:6500:FF00::36FB:1F8F",
"54.240.196.255",
"255.255.255.255",
"255.255.255.0",
"255.255.255.5",
"255.255.255.10",
"255.255.255.16",
"255.255.255.26",
"255.255.255.27"
};
String[] wanted = {
"00112233445566778899AABBCCDDEEFE/00112233445566778899AABBCCDDEEFF:true/false (T:NUMERIC_RANGE)",
"20010DB8000000000000FF0000428329/20010DB8000000000000FF000042832A:false/true (T:NUMERIC_RANGE)",
"00000000000000000000000000000000/00000000000000000000000000000001:false/true (T:NUMERIC_RANGE)",
"00000000000000000000000000000003/00000000000000000000000000000004:false/true (T:NUMERIC_RANGE)",
"00000000000000000000000000000009/0000000000000000000000000000000A:false/true (T:NUMERIC_RANGE)",
"0000000000000000000000000000000A/0000000000000000000000000000000B:false/true (T:NUMERIC_RANGE)",
"0000000000000000000000000000000E/0000000000000000000000000000000F:true/false (T:NUMERIC_RANGE)",
"24006500FF0000000000000036FB1F80/24006500FF0000000000000036FB1F81:false/true (T:NUMERIC_RANGE)",
"24006500FF0000000000000036FB1F85/24006500FF0000000000000036FB1F86:false/true (T:NUMERIC_RANGE)",
"24006500FF0000000000000036FB1F89/24006500FF0000000000000036FB1F8A:false/true (T:NUMERIC_RANGE)",
"24006500FF0000000000000036FB1F8C/24006500FF0000000000000036FB1F8D:false/true (T:NUMERIC_RANGE)",
"24006500FF0000000000000036FB1F8E/24006500FF0000000000000036FB1F8F:true/false (T:NUMERIC_RANGE)",
"36F0C4FE/36F0C4FF:true/false (T:NUMERIC_RANGE)",
"FFFFFFFE/FFFFFFFF:true/false (T:NUMERIC_RANGE)",
"FFFFFF00/FFFFFF01:false/true (T:NUMERIC_RANGE)",
"FFFFFF05/FFFFFF06:false/true (T:NUMERIC_RANGE)",
"FFFFFF0A/FFFFFF0B:false/true (T:NUMERIC_RANGE)",
"FFFFFF10/FFFFFF11:false/true (T:NUMERIC_RANGE)",
"FFFFFF1A/FFFFFF1B:false/true (T:NUMERIC_RANGE)",
"FFFFFF1B/FFFFFF1C:false/true (T:NUMERIC_RANGE)"
};
Machine m = new Machine();
for (int i = 0; i < addresses.length; i++) {
String addr = addresses[i];
Range c = CIDR.ipToRangeIfPossible(addr);
tryAddingAsRule(m, c);
assertEquals(wanted[i], c.toString());
}
assertTrue(!m.isEmpty());
for (int i = addresses.length - 1; i >= 0; i--) {
String addr = addresses[i];
Range c = CIDR.ipToRangeIfPossible(addr);
assertEquals(wanted[i], c.toString());
tryDeletingAsRule(m, c);
}
assertTrue(m.isEmpty());
}
@Test
public void testInvalidIPMatchedByIPv6Regex() throws Exception {
String invalidIpRule = "{ \"a\": [ \"08:23\" ] }";
Machine machine = new Machine();
machine.addRule("r1", invalidIpRule);
assertEquals(Arrays.asList("r1"), machine.rulesForJSONEvent("{ \"a\": [ \"08:23\" ] }"));
}
private void tryAddingAsRule(Machine m, Range r) {
try {
List<Patterns> lp = new ArrayList<>();
lp.add(r);
Map<String, List<Patterns>> map = new HashMap<>();
map.put("a", lp);
m.addPatternRule("x", map);
} catch (Exception e) {
fail("Failed to add: " + r);
}
}
private void tryDeletingAsRule(Machine m, Range r) {
try {
List<Patterns> lp = new ArrayList<>();
lp.add(r);
Map<String, List<Patterns>> map = new HashMap<>();
map.put("a", lp);
m.deletePatternRule("x", map);
} catch (Exception e) {
fail("Failed to add: " + r);
}
}
} | 4,851 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/PathTest.java | package software.amazon.event.ruler;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PathTest {
@Test
public void WHEN_PushAndPopAreUsed_THEN_TheyOperateSymmetrically() {
Path cut = new Path();
String[] vals = {"foo", "bar", "baz", "33"};
for (int i = 0; i < vals.length; i++) {
cut.push(vals[i]);
assertEquals(join(vals, i), cut.name());
}
for (int i = vals.length - 1; i >= 0; i--) {
assertEquals(join(vals, i), cut.name());
assertEquals(vals[i], cut.pop());
}
}
private String join(String[] strings, int last) {
StringBuilder j = new StringBuilder(strings[0]);
for (int i = 1; i <= last; i++) {
j.append(".").append(strings[i]);
}
return j.toString();
}
} | 4,852 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/ByteStateTest.java | package software.amazon.event.ruler;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import static software.amazon.event.ruler.CompoundByteTransition.coalesce;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class ByteStateTest {
private ByteState state;
@Before
public void setUp() {
state = new ByteState();
}
@Test
public void getNextByteStateShouldReturnThisState() {
assertSame(state, state.getNextByteState());
}
@Test
public void setNextByteStateShouldReturnNullWhenGivenNextStateIsNull() {
assertNull(state.setNextByteState(null));
}
@Test
public void setNextByteStateShouldReturnGivenNextStateWhenGivenNextStateIsNotNull() {
ByteState nextState = new ByteState();
ByteTransition transition = state.setNextByteState(nextState);
assertSame(nextState, transition);
}
@Test
public void getMatchShouldReturnNull() {
assertNull(state.getMatch());
}
@Test
public void getMatchesShouldReturnEmptySet() {
assertEquals(Collections.emptySet(), state.getMatches());
}
@Test
public void setMatchShouldReturnThisStateWhenGivenMatchIsNull() {
ByteTransition transition = state.setMatch(null);
assertSame(state, transition);
}
@Test
public void setMatchShouldReturnNewCompositeTransitionWhenGivenMatchIsNotNull() {
ByteMatch match = new ByteMatch(Patterns.exactMatch("xyz"), new NameState());
ByteTransition transition = state.setMatch(match);
assertTrue(transition instanceof CompositeByteTransition);
assertSame(state, transition.getNextByteState());
assertEquals(match, transition.getMatches());
}
@Test
public void hasNoTransitionsShouldReturnTrueWhenThisStateHasNoTransitions() {
boolean hasNoTransitions = state.hasNoTransitions();
assertTrue(hasNoTransitions);
}
@Test
public void hasNoTransitionsShouldReturnFalseWhenThisStateHasTransitions() {
state.addTransition((byte) 'a', new ByteState());
boolean hasNoTransitions = state.hasNoTransitions();
assertFalse(hasNoTransitions);
}
@Test
public void getTransitionShouldReturnNullWhenThisStateHasNoTransitions() {
ByteTransition transition = state.getTransition((byte) 'a');
assertNull(transition);
}
@Test
public void getTransitionShouldReturnNullWhenMappingDoesNotExistAndThisStateHasOneTransition() {
state.addTransition((byte) 'a', new ByteState());
ByteTransition transition = state.getTransition((byte) 'b');
assertNull(transition);
}
@Test
public void getTransitionShouldReturnTransitionWhenMappingExistsAndThisStateHasOneTransition() {
byte b = 'a';
SingleByteTransition transition = new ByteState();
state.addTransition(b, transition);
ByteTransition actualTransition = state.getTransition(b);
assertSame(transition, actualTransition);
}
@Test
public void getTransitionShouldReturnTransitionWhenMappingExistsAndThisStateHasTwoTransition() {
byte b1 = 'a';
byte b2 = 'b';
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
state.addTransition(b1, transition1);
state.addTransition(b2, transition2);
ByteTransition actualTransition = state.getTransition(b1);
assertSame(transition1, actualTransition);
}
@Test
public void putTransitionShouldCreateExpectedMappings() {
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
SingleByteTransition transition3 = new ByteState();
SingleByteTransition transition4 = new ByteState();
state.putTransition((byte) 'a', transition1);
state.putTransition((byte) 'a', transition2);
state.putTransition((byte) 'b', transition3);
state.putTransition((byte) 'c', transition4);
assertSame(transition2, state.getTransition((byte) 'a'));
assertSame(transition3, state.getTransition((byte) 'b'));
assertSame(transition4, state.getTransition((byte) 'c'));
}
@Test
public void addTransitionShouldCreateMappingWhenMappingDoesNotExistAndThisStateHasNoTransitions() {
byte b = 'a';
SingleByteTransition transition = new ByteState();
state.addTransition(b, transition);
assertSame(transition, state.getTransition(b));
}
@Test
public void addTransitionShouldProduceCompoundByteStateWhenMappingExistsAndThisStateHasOneTransition() {
byte b = 'a';
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
state.addTransition(b, transition1);
state.addTransition(b, transition2);
ByteTransition resultantTransition = state.getTransition(b);
assertTrue(resultantTransition instanceof CompoundByteTransition);
CompoundByteTransition compoundByteTransition = (CompoundByteTransition) resultantTransition;
assertEquals(new HashSet<>(Arrays.asList(transition1, transition2)), compoundByteTransition.expand());
}
@Test
public void addTransitionShouldCreateMappingWhenMappingDoesNotExistAndThisStateHasOneTransition() {
byte b1 = 'a';
byte b2 = 'b';
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
state.addTransition(b1, transition1);
state.addTransition(b2, transition2);
assertSame(transition1, state.getTransition(b1));
assertSame(transition2, state.getTransition(b2));
}
@Test
public void addTransitionShouldCreateMappingWhenMappingDoesNotExistAndThisStateHasTwoTransitions() {
byte b1 = 'a';
byte b2 = 'b';
byte b3 = 'c';
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
SingleByteTransition transition3 = new ByteState();
state.addTransition(b1, transition1);
state.addTransition(b2, transition2);
state.addTransition(b3, transition3);
assertSame(transition1, state.getTransition(b1));
assertSame(transition2, state.getTransition(b2));
assertSame(transition3, state.getTransition(b3));
}
@Test
public void removeTransitionShouldDoNothingWhenMappingDoesNotExistAndThisStateHasNoTransitions() {
byte b = 'a';
state.removeTransition(b, new ByteState());
assertNull(state.getTransition(b));
}
@Test
public void removeTransitionShouldDoNothingWhenMappingDoesNotExistAndThisStateHasOneTransition() {
byte b = 'a';
SingleByteTransition transition = new ByteState();
state.addTransition(b, transition);
state.removeTransition((byte) 'b', transition);
assertSame(transition, state.getTransition(b));
}
@Test
public void removeTransitionShouldRemoveMappingWhenMappingExistsAndThisStateHasOneTransition() {
byte b = 'a';
SingleByteTransition transition = new ByteState();
state.addTransition(b, transition);
state.removeTransition(b, transition);
assertNull(state.getTransition(b));
}
@Test
public void removeTransitionShouldDoNothingWhenMappingDoesNotExistAndThisStateHasTwoTransitions() {
byte b1 = 'a';
byte b2 = 'b';
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
state.addTransition(b1, transition1);
state.addTransition(b2, transition2);
state.removeTransition((byte) 'c', transition1);
assertSame(transition1, state.getTransition(b1));
assertSame(transition2, state.getTransition(b2));
}
@Test
public void removeTransitionShouldRemoveMappingWhenMappingExistsAndThisStateHasTwoTransitions() {
byte b1 = 'a';
byte b2 = 'b';
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
state.addTransition(b1, transition1);
state.addTransition(b2, transition2);
state.removeTransition(b1, transition1);
assertNull(state.getTransition(b1));
assertSame(transition2, state.getTransition(b2));
}
@Test
public void removeTransitionShouldRemoveMappingWhenMappingExistsAndThisStateHasThreeTransitions() {
byte b1 = 'a';
byte b2 = 'b';
byte b3 = 'c';
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
SingleByteTransition transition3 = new ByteState();
state.addTransition(b1, transition1);
state.addTransition(b2, transition2);
state.addTransition(b3, transition3);
state.removeTransition(b1, transition1);
assertNull(state.getTransition(b1));
assertSame(transition2, state.getTransition(b2));
assertSame(transition3, state.getTransition(b3));
}
@Test
public void putTransitionForAllBytesShouldCreateExpectedMappings() {
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
state.addTransition((byte) 'a', transition1);
state.putTransitionForAllBytes(transition2);
assertSame(transition2, state.getTransition((byte) 'a'));
assertSame(transition2, state.getTransition((byte) 'b'));
}
@Test
public void addTransitionForAllBytesFromNullTransitionStoreShouldCreateExpectedMappings() {
SingleByteTransition transition1 = new ByteState();
state.addTransitionForAllBytes(transition1);
assertSame(transition1, state.getTransition((byte) 'a'));
}
@Test
public void addTransitionForAllBytesFromSingleByteTransitionEntryShouldCreateExpectedMappings() {
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
state.addTransition((byte) 'a', transition1);
state.addTransitionForAllBytes(transition2);
assertEquals(coalesce(new HashSet<>(Arrays.asList(transition1, transition2))), state.getTransition((byte) 'a'));
assertSame(transition2, state.getTransition((byte) 'b'));
}
@Test
public void addTransitionForAllBytesFromByteMapShouldCreateExpectedMappings() {
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
SingleByteTransition transition3 = new ByteState();
state.addTransition((byte) 'a', transition1);
state.addTransition((byte) 'b', transition2);
state.addTransitionForAllBytes(transition3);
assertEquals(coalesce(new HashSet<>(Arrays.asList(transition1, transition3))), state.getTransition((byte) 'a'));
assertEquals(coalesce(new HashSet<>(Arrays.asList(transition2, transition3))), state.getTransition((byte) 'b'));
assertSame(transition3, state.getTransition((byte) 'c'));
}
@Test
public void removeTransitionForAllBytesFromNullTransitionStoreShouldHaveNoEffect() {
SingleByteTransition transition1 = new ByteState();
state.removeTransitionForAllBytes(transition1);
assertNull(state.getTransition((byte) 'a'));
}
@Test
public void removeTransitionForAllBytesFromSingleByteTransitionEntryWithDifferentTransitionShouldHaveNoEffect() {
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
state.addTransition((byte) 'a', transition1);
state.removeTransitionForAllBytes(transition2);
assertSame(transition1, state.getTransition((byte) 'a'));
}
@Test
public void removeTransitionForAllBytesFromSingleByteTransitionEntryWithSameTransitionShouldRemoveTransition() {
SingleByteTransition transition1 = new ByteState();
state.addTransition((byte) 'a', transition1);
state.removeTransitionForAllBytes(transition1);
assertNull(state.getTransition((byte) 'a'));
}
@Test
public void removeTransitionForAllBytesFromByteMapWithDifferentTransitionShouldHaveNoEffect() {
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
SingleByteTransition transition3 = new ByteState();
state.addTransition((byte) 'a', transition1);
state.addTransition((byte) 'b', transition2);
state.removeTransitionForAllBytes(transition3);
assertSame(transition1, state.getTransition((byte) 'a'));
assertSame(transition2, state.getTransition((byte) 'b'));
}
@Test
public void removeTransitionForAllBytesFromByteMapWithSameTransitionShouldRemoveTransition() {
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
state.addTransition((byte) 'a', transition1);
state.addTransition((byte) 'b', transition2);
state.removeTransitionForAllBytes(transition2);
assertSame(transition1, state.getTransition((byte) 'a'));
assertNull(state.getTransition((byte) 'b'));
}
@Test
public void getShortcutsShouldReturnEmptySet() {
assertEquals(Collections.emptySet(), state.getShortcuts());
}
@Test
public void getTransitionForAllBytesWithNullTransitionStoreShouldReturnExpectedTransition() {
assertEquals(ByteMachine.EmptyByteTransition.INSTANCE, state.getTransitionForAllBytes());
}
@Test
public void getTransitionForAllBytesWithSingleByteTransitionEntryShouldReturnEmptyTransition() {
SingleByteTransition trans1 = new ByteState();
state.addTransition((byte) 'a', trans1);
assertEquals(ByteMachine.EmptyByteTransition.INSTANCE, state.getTransitionForAllBytes());
}
@Test
public void getTransitionForAllBytesWithByteMapWithSomeBytesShouldReturnEmptyTransition() {
SingleByteTransition trans1 = new ByteState();
SingleByteTransition trans2 = new ByteState();
state.addTransition((byte) 'a', trans1);
state.addTransition((byte) 'c', trans2);
assertEquals(ByteMachine.EmptyByteTransition.INSTANCE, state.getTransitionForAllBytes());
}
@Test
public void getTransitionForAllBytesWithByteMapWithAllBytesShouldReturnExpectedTransition() {
SingleByteTransition trans1 = new ByteState();
SingleByteTransition trans2 = new ByteState();
SingleByteTransition trans3 = new ByteState();
SingleByteTransition trans4 = new ByteState();
state.addTransitionForAllBytes(trans1);
state.addTransitionForAllBytes(trans2);
state.addTransitionForAllBytes(trans3);
state.addTransition((byte) 'a', trans4);
state.removeTransition((byte) 'c', trans2);
assertEquals(coalesce(new HashSet<>(Arrays.asList(trans1, trans3))), state.getTransitionForAllBytes());
}
@Test
public void getTransitionsWithNullTransitionStoreShouldReturnEmptySet() {
assertEquals(Collections.emptySet(), state.getTransitions());
}
@Test
public void getTransitionsWithSingleByteTransitionEntryShouldReturnExpectedTransition() {
SingleByteTransition trans1 = new ByteState();
state.addTransition((byte) 'a', trans1);
assertEquals(trans1, state.getTransitions());
}
@Test
public void getTransitionsWithByteMapShouldReturnExpectedTransitions() {
SingleByteTransition trans1 = new ByteState();
SingleByteTransition trans2 = new ByteState();
SingleByteTransition trans3 = new ByteState();
SingleByteTransition trans4 = new ByteState();
state.addTransitionForAllBytes(trans1);
state.addTransitionForAllBytes(trans2);
state.addTransitionForAllBytes(trans3);
state.addTransition((byte) 'a', trans4);
state.removeTransition((byte) 'c', trans2);
assertEquals(new HashSet<>(Arrays.asList(coalesce(new HashSet<>(Arrays.asList(trans1, trans3))),
coalesce(new HashSet<>(Arrays.asList(trans1, trans2, trans3))),
coalesce(new HashSet<>(Arrays.asList(trans1, trans2, trans3, trans4)))
)), state.getTransitions());
}
@Test
public void testGetCeilingsWithNullTransitionStoreShouldReturnEmptySet() {
assertEquals(Collections.emptySet(), state.getCeilings());
}
@Test
public void testGetCeilingsWithSingleByteTransitionEntryShouldReturnExpectedCeilings() {
SingleByteTransition trans1 = new ByteState();
state.addTransition((byte) 'a', trans1);
assertEquals(new HashSet<>(Arrays.asList(97, 98, 256)), state.getCeilings());
}
@Test
public void testGetCeilingsWithSingleByteTransitionEntryWithZeroIndexByteShouldReturnExpectedCeilings() {
SingleByteTransition trans1 = new ByteState();
state.addTransition((byte) 0, trans1);
assertEquals(new HashSet<>(Arrays.asList(1, 256)), state.getCeilings());
}
@Test
public void testGetCeilingsWithSingleByteTransitionEntryWith255IndexByteShouldReturnExpectedCeilings() {
SingleByteTransition trans1 = new ByteState();
state.addTransition((byte) 255, trans1);
assertEquals(new HashSet<>(Arrays.asList(255, 256)), state.getCeilings());
}
@Test
public void testGetCeilingsWithByteMapShouldReturnExpectedCeilings() {
SingleByteTransition trans1 = new ByteState();
SingleByteTransition trans2 = new ByteState();
state.addTransition((byte) 'a', trans1);
state.addTransition((byte) 'c', trans2);
assertEquals(new HashSet<>(Arrays.asList(97, 98, 99, 100, 256)), state.getCeilings());
}
@Test
public void hasIndeterminatePrefixShouldReturnExpectedBoolean() {
assertFalse(state.hasIndeterminatePrefix());
state.setIndeterminatePrefix(true);
assertTrue(state.hasIndeterminatePrefix());
}
@Test
public void hasOnlySelfReferentialTransitionShouldReturnExpectedBoolean() {
assertFalse(state.hasOnlySelfReferentialTransition());
state.putTransition((byte) 'a', state);
assertTrue(state.hasOnlySelfReferentialTransition());
state.putTransition((byte) 'b', new ByteState());
assertFalse(state.hasOnlySelfReferentialTransition());
}
}
| 4,853 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/ByteMapTest.java | package software.amazon.event.ruler;
import static software.amazon.event.ruler.CompoundByteTransition.coalesce;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class ByteMapTest {
private ByteMap map;
private SingleByteTransition trans1;
private SingleByteTransition trans2;
private SingleByteTransition trans3;
private SingleByteTransition trans4;
@Before
public void setup() {
map = new ByteMap();
trans1 = new ByteState();
trans2 = new ByteState();
trans3 = new ByteState();
trans4 = new ByteState();
}
@Test
public void testPutTransitionNonAdjacent() {
map.putTransition((byte) 'a', trans1);
map.putTransition((byte) 'c', trans2);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(5, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 97);
verifyMapEntry(it.next(), 98, trans1);
verifyMapEntry(it.next(), 99);
verifyMapEntry(it.next(), 100, trans2);
verifyMapEntry(it.next(), 256);
}
@Test
public void testPutTransitionAdjacent() {
map.putTransition((byte) 'a', trans1);
map.putTransition((byte) 'b', trans2);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(4, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 97);
verifyMapEntry(it.next(), 98, trans1);
verifyMapEntry(it.next(), 99, trans2);
verifyMapEntry(it.next(), 256);
}
@Test
public void testPutTransitionForAllBytes() {
map.putTransitionForAllBytes(trans1);
map.putTransitionForAllBytes(trans2);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(1, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 256, trans2);
}
@Test
public void testPutTransitionMinCharacter() {
map.putTransition((byte) Character.MIN_VALUE, trans1);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(2, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 1, trans1);
verifyMapEntry(it.next(), 256);
}
@Test
public void testPutTransitionMaxCharacter() {
map.putTransition((byte) Character.MAX_VALUE, trans1);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(2, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 255);
verifyMapEntry(it.next(), 256, trans1);
}
@Test
public void testPutTransitionOverwrites() {
map.putTransition((byte) 'a', trans1);
map.putTransition((byte) 'a', trans2);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(3, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 97);
verifyMapEntry(it.next(), 98, trans2);
verifyMapEntry(it.next(), 256);
}
@Test
public void testAddTransitionDoesNotOverwrite() {
map.putTransition((byte) 'a', trans1);
map.addTransition((byte) 'a', trans2);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(3, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 97);
verifyMapEntry(it.next(), 98, trans1, trans2);
verifyMapEntry(it.next(), 256);
}
@Test
public void testAddTransitionBottomOfRange() {
map.putTransitionForAllBytes(trans1);
map.addTransition((byte) 0x00, trans2);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(2, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 1, trans1, trans2);
verifyMapEntry(it.next(), 256, trans1);
}
@Test
public void testAddTransitionMiddleOfRange() {
map.putTransitionForAllBytes(trans1);
map.addTransition((byte) 'a', trans2);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(3, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 97, trans1);
verifyMapEntry(it.next(), 98, trans1, trans2);
verifyMapEntry(it.next(), 256, trans1);
}
@Test
public void testAddTransitionTopOfRange() {
map.putTransitionForAllBytes(trans1);
map.addTransition((byte) 0xFF, trans2);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(2, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 255, trans1);
verifyMapEntry(it.next(), 256, trans1, trans2);
}
@Test
public void testAddTransitionForAllBytes() {
map.putTransitionForAllBytes(trans1);
map.addTransitionForAllBytes(trans2);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(1, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 256, trans1, trans2);
}
@Test
public void testRemoveTransitionBottomOfRange() {
map.putTransitionForAllBytes(trans1);
map.removeTransition((byte) 0x00, trans1);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(2, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 1);
verifyMapEntry(it.next(), 256, trans1);
}
@Test
public void testRemoveTransitionMiddleOfRange() {
map.putTransitionForAllBytes(trans1);
map.removeTransition((byte) 'a', trans1);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(3, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 97, trans1);
verifyMapEntry(it.next(), 98);
verifyMapEntry(it.next(), 256, trans1);
}
@Test
public void testRemoveTransitionTopOfRange() {
map.putTransitionForAllBytes(trans1);
map.removeTransition((byte) 0xFF, trans1);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(2, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 255, trans1);
verifyMapEntry(it.next(), 256);
}
@Test
public void testRemoveTransitionDifferentTransitionNoEffect() {
map.putTransition((byte) 'a', trans1);
map.removeTransition((byte) 'a', trans2);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(3, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 97);
verifyMapEntry(it.next(), 98, trans1);
verifyMapEntry(it.next(), 256);
}
@Test
public void testRemoveTransitionForAllBytes() {
map.putTransitionForAllBytes(trans1);
map.removeTransitionForAllBytes(trans1);
NavigableMap<Integer, ByteTransition> nMap = map.getMap();
assertEquals(1, nMap.size());
Iterator<Map.Entry<Integer, ByteTransition>> it = nMap.entrySet().iterator();
verifyMapEntry(it.next(), 256);
}
@Test
public void testIsEmpty() {
assertTrue(map.isEmpty());
map.addTransition((byte) 'a', trans1);
assertFalse(map.isEmpty());
map.removeTransition((byte) 'a', trans1);
assertTrue(map.isEmpty());
}
@Test
public void testNumberOfTransitions() {
assertEquals(0, map.numberOfTransitions());
map.addTransition((byte) 'a', trans1);
assertEquals(1, map.numberOfTransitions());
map.addTransition((byte) 'c', trans2);
assertEquals(2, map.numberOfTransitions());
map.putTransition((byte) 'a', trans2);
assertEquals(1, map.numberOfTransitions());
map.removeTransition((byte) 'a', trans2);
assertEquals(1, map.numberOfTransitions());
map.addTransition((byte) 'c', trans1);
assertEquals(2, map.numberOfTransitions());
map.removeTransition((byte) 'c', trans2);
assertEquals(1, map.numberOfTransitions());
map.removeTransition((byte) 'c', trans1);
assertEquals(0, map.numberOfTransitions());
}
@Test
public void testHasTransition() {
assertFalse(map.hasTransition(trans1));
assertFalse(map.hasTransition(trans2));
map.addTransition((byte) 'a', trans1);
assertTrue(map.hasTransition(trans1));
assertFalse(map.hasTransition(trans2));
map.addTransition((byte) 'c', trans2);
assertTrue(map.hasTransition(trans1));
assertTrue(map.hasTransition(trans2));
map.putTransition((byte) 'a', trans2);
assertFalse(map.hasTransition(trans1));
assertTrue(map.hasTransition(trans2));
map.removeTransition((byte) 'a', trans2);
assertFalse(map.hasTransition(trans1));
assertTrue(map.hasTransition(trans2));
map.addTransition((byte) 'c', trans1);
assertTrue(map.hasTransition(trans1));
assertTrue(map.hasTransition(trans2));
map.removeTransition((byte) 'c', trans2);
assertTrue(map.hasTransition(trans1));
assertFalse(map.hasTransition(trans2));
map.removeTransition((byte) 'c', trans1);
assertFalse(map.hasTransition(trans1));
assertFalse(map.hasTransition(trans2));
}
@Test
public void testGetTransition() {
map.addTransition((byte) 'b', trans1);
assertNull(map.getTransition((byte) 'a'));
map.addTransition((byte) 'a', trans1);
assertEquals(trans1, map.getTransition((byte) 'a'));
map.addTransition((byte) 'a', trans2);
ByteTransition trans = map.getTransition((byte) 'a');
assertTrue(trans instanceof CompoundByteTransition);
Set<ByteTransition> result = new HashSet<>();
trans.expand().forEach(t -> result.add(t));
assertEquals(new HashSet<>(Arrays.asList(trans1, trans2)), result);
}
@Test
public void testGetTransitionForAllBytesAllOneTransitionExceptOneWithTwo() {
map.addTransitionForAllBytes(trans1);
map.addTransition((byte) 'a', trans2);
assertEquals(coalesce(new HashSet<>(Arrays.asList(trans1))), map.getTransitionForAllBytes());
}
@Test
public void testGetTransitionForAllBytesAllTwoTransitionsExceptOneWithOne() {
map.addTransitionForAllBytes(trans1);
map.addTransitionForAllBytes(trans2);
map.removeTransition((byte) 'a', trans2);
assertEquals(coalesce(new HashSet<>(Arrays.asList(trans1))), map.getTransitionForAllBytes());
}
@Test
public void testGetTransitionForAllBytesAllOneTransitionExceptOneWithZero() {
map.addTransitionForAllBytes(trans1);
map.removeTransition((byte) 'a', trans1);
assertEquals(ByteMachine.EmptyByteTransition.INSTANCE, map.getTransitionForAllBytes());
}
@Test
public void testGetTransitionForAllBytesAllOneTransitionExceptOneDifferent() {
map.addTransitionForAllBytes(trans1);
map.removeTransition((byte) 'a', trans1);
map.addTransition((byte) 'a', trans2);
assertEquals(ByteMachine.EmptyByteTransition.INSTANCE, map.getTransitionForAllBytes());
}
@Test
public void testGetTransitionForAllBytesAllThreeTransitionsExceptOneWithTwo() {
map.addTransitionForAllBytes(trans1);
map.addTransitionForAllBytes(trans2);
map.addTransitionForAllBytes(trans3);
map.addTransition((byte) 'a', trans4);
map.removeTransition((byte) 'c', trans2);
assertEquals(coalesce(new HashSet<>(Arrays.asList(trans1, trans3))), map.getTransitionForAllBytes());
}
@Test
public void testGetTransitions() {
map.addTransitionForAllBytes(trans1);
map.addTransitionForAllBytes(trans2);
map.addTransitionForAllBytes(trans3);
map.addTransition((byte) 'a', trans4);
map.removeTransition((byte) 'c', trans2);
assertEquals(new HashSet<>(Arrays.asList(coalesce(new HashSet<>(Arrays.asList(trans1, trans3))),
coalesce(new HashSet<>(Arrays.asList(trans1, trans2, trans3))),
coalesce(new HashSet<>(Arrays.asList(trans1, trans2, trans3, trans4)))
)), map.getTransitions()
);
}
@Test
public void testGetCeilings() {
map.addTransition((byte) 'a', trans1);
map.addTransition((byte) 'c', trans2);
assertEquals(new HashSet<>(Arrays.asList(97, 98, 99, 100, 256)), map.getCeilings());
}
@Test
public void testToString() {
map.addTransition((byte) 'a', trans1);
map.addTransition((byte) 'b', trans2);
map.addTransition((byte) 'b', trans3);
// Don't know which order the 'b' transitions will be listed, so accept either.
String toString = map.toString();
assertTrue(
toString.equals(String.format("a->ByteState/%s // b->ByteState/%s,ByteState/%s // ",
trans1.hashCode(), trans2.hashCode(), trans3.hashCode())) ||
toString.equals(String.format("a->ByteState/%s // b->ByteState/%s,ByteState/%s // ",
trans1.hashCode(), trans3.hashCode(), trans2.hashCode()))
);
}
private static void verifyMapEntry(Map.Entry<Integer, ByteTransition> entry, int ceiling,
ByteTransition ... transitions) {
assertEquals(ceiling, entry.getKey().intValue());
Set<ByteTransition> result = new HashSet<>();
if (entry.getValue() != null) {
entry.getValue().expand().forEach(t -> result.add(t));
}
assertEquals(new HashSet<>(Arrays.asList(transitions)), result);
}
} | 4,854 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/RuleCompilerTest.java | package software.amazon.event.ruler;
import com.fasterxml.jackson.core.JsonParseException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class RuleCompilerTest {
@Test
public void testBigNumbers() throws Exception {
Machine m = new Machine();
String rule = "{\n" +
" \"account\": [ 123456789012 ]\n" +
"}";
String event = "{\"account\": 123456789012 }";
m.addRule("r1", rule);
assertEquals(1, m.rulesForJSONEvent(event).size());
}
@Test
public void testPrefixEqualsIgnoreCaseCompile() {
String json = "{\"a\": [ { \"prefix\": { \"equals-ignore-case\": \"child\" } } ] }";
assertNull("Good prefix equals-ignore-case should parse", RuleCompiler.check(json));
}
@Test
public void testSuffixEqualsIgnoreCaseCompile() {
String json = "{\"a\": [ { \"suffix\": { \"equals-ignore-case\": \"child\" } } ] }";
assertNull("Good suffix equals-ignore-case should parse", RuleCompiler.check(json));
}
@Test
public void testVariantForms() throws Exception {
Machine m = new Machine();
String r1 = "{\n" +
" \"a\": [ 133.3 ]\n" +
"}";
String r2 = "{\n" +
" \"a\": [ { \"numeric\": [ \">\", 120, \"<=\", 140 ] } ]\n" +
"}";
String r3 = "{\n" +
" \"b\": [ \"192.0.2.0\" ]\n" +
"}\n";
String r4 = "{\n" +
" \"b\": [ { \"cidr\": \"192.0.2.0/24\" } ]\n" +
"}";
String event = "{\n" +
" \"a\": 133.3,\n" +
" \"b\": \"192.0.2.0\"\n" +
"}";
m.addRule("r1", r1);
m.addRule("r2", r2);
m.addRule("r3", r3);
m.addRule("r4", r4);
List<String> nr = m.rulesForJSONEvent(event);
assertEquals(4, nr.size());
}
@Test
public void testCompile() throws Exception {
String j = "[1,2,3]";
assertNotNull("Top level must be an object", RuleCompiler.check(j));
InputStream is = new ByteArrayInputStream(j.getBytes(StandardCharsets.UTF_8));
assertNotNull("Top level must be an object (bytes)", RuleCompiler.check(is));
j = "{\"a\":1}";
assertNotNull("Values must be in an array", RuleCompiler.check(j.getBytes(StandardCharsets.UTF_8)));
j = "{\"a\":[ { \"x\":2 } ]}";
assertNotNull("Array values must be primitives", RuleCompiler.check(new StringReader(j)));
j = "{ \"foo\": {}}";
assertNotNull("Objects must not be empty", RuleCompiler.check(new StringReader(j)));
j = "{ \"foo\": []}";
assertNotNull("Arrays must not be empty", RuleCompiler.check(new StringReader(j)));
j = "{\"a\":[1]}";
assertNull(RuleCompiler.check(j));
Map<String, List<Patterns>> m = RuleCompiler.compile(new ByteArrayInputStream(j.getBytes(StandardCharsets.UTF_8)));
List<Patterns> l = m.get("a");
assertEquals(2, l.size());
for (Patterns p : l) {
ValuePatterns vp = (ValuePatterns) p;
if (p.type() == MatchType.NUMERIC_EQ) {
assertEquals(ComparableNumber.generate(1.0), vp.pattern());
} else {
assertEquals("1", vp.pattern());
}
}
j = "{\"a\": [ { \"prefix\": \"child\" } ] }";
assertNull("Good prefix should parse", RuleCompiler.check(j));
j = "{\"a\": [ { \"suffix\": \"child\" } ] }";
assertNull("Good suffix should parse", RuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": \"child\" } ] }";
assertNull("Good anything-but should parse", RuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": [\"child0\",\"child1\",\"child2\"] } ] }";
assertNull("Good anything-but should parse", RuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": [111,222,333] } ] }";
assertNull("Good anything-but should parse", RuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": \"child0\" } ] }";
assertNull("Good anything-but should parse", RuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": 111 } ] }";
assertNull("Good anything-but should parse", RuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": { \"prefix\": \"foo\" } } ] }";
assertNull("Good anything-but should parse", RuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": { \"suffix\": \"foo\" } } ] }";
assertNull("Good anything-but should parse", RuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": {\"equals-ignore-case\": \"rule\" } } ] }";
assertNull("Good anything-but/ignore-case should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"anything-but\": {\"equals-ignore-case\": [\"abc\", \"123\"] } } ] }";
assertNull("Good anything-but/ignore-case should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"exactly\": \"child\" } ] }";
assertNull("Good exact-match should parse", RuleCompiler.check(j));
j = "{\"a\": [ { \"exists\": true } ] }";
assertNull("Good exists true should parse", RuleCompiler.check(j));
j = "{\"a\": [ { \"exists\": false } ] }";
assertNull("Good exists false should parse", RuleCompiler.check(j));
j = "{\"a\": [ { \"cidr\": \"10.0.0.0/8\" } ] }";
assertNull("Good CIDR should parse", RuleCompiler.check(j));
j = "{\"a\": [ { \"equals-ignore-case\": \"abc\" } ] }";
assertNull("Good equals-ignore-case should parse", JsonRuleCompiler.check(j));
j = "{\"a\": [ { \"wildcard\": \"a*b*c\" } ] }";
assertNull("Good wildcard should parse", JsonRuleCompiler.check(j));
String[] badPatternTypes = {
"{\"a\": [ { \"exactly\": 33 } ] }",
"{\"a\": [ { \"prefix\": \"child\", \"foo\": [] } ] }",
"{\"a\": [ { \"prefix\": 3 } ] }",
"{\"a\": [ { \"prefix\": [1, 2 3] } ] }",
"{\"a\": [ { \"suffix\": \"child\", \"foo\": [] } ] }",
"{\"a\": [ { \"suffix\": 3 } ] }",
"{\"a\": [ { \"suffix\": [1, 2 3] } ] }",
"{\"a\": [ { \"foo\": \"child\" } ] }",
"{\"a\": [ { \"cidr\": \"foo\" } ] }",
"{\"a\": [ { \"anything-but\": \"child\", \"foo\": [] } ] }",
"{\"a\": [ { \"anything-but\": [1, 2 3] } ] }",
"{\"a\": [ { \"anything-but\": \"child\", \"foo\": [] } ] }",
"{\"a\": [ { \"anything-but\": [\"child0\",111,\"child2\"] } ] }",
"{\"a\": [ { \"anything-but\": [1, 2 3] } ] }",
"{\"a\": [ { \"anything-but\": { \"foo\": 3 } ] }",
"{\"a\": [ { \"anything-but\": { \"prefix\": 27 } } ] }",
"{\"a\": [ { \"anything-but\": { \"prefix\": \"\" } } ] }",
"{\"a\": [ { \"anything-but\": { \"prefix\": \"foo\", \"a\":1 } } ] }",
"{\"a\": [ { \"anything-but\": { \"prefix\": \"foo\" }, \"x\": 1 } ] }",
"{\"a\": [ { \"anything-but\": { \"suffix\": 27 } } ] }",
"{\"a\": [ { \"anything-but\": { \"suffix\": \"\" } } ] }",
"{\"a\": [ { \"anything-but\": { \"suffix\": \"foo\", \"a\":1 } } ] }",
"{\"a\": [ { \"anything-but\": { \"suffix\": \"foo\" }, \"x\": 1 } ] }",
"{\"a\": [ { \"anything-but\": {\"equals-ignore-case\": [1, 2 3] } } ] }",
"{\"a\": [ { \"anything-but\": {\"equals-ignore-case\": [1, 2, 3] } } ] }", // no numbers allowed
"{\"a\": [ { \"equals-ignore-case\": 5 } ] }",
"{\"a\": [ { \"equals-ignore-case\": [ \"abc\" ] } ] }",
"{\"a\": [ { \"prefix\": { \"invalid-expression\": [ \"abc\" ] } } ] }",
"{\"a\": [ { \"prefix\": { \"equals-ignore-case\": 5 } } ] }",
"{\"a\": [ { \"prefix\": { \"equals-ignore-case\": [ \"abc\" ] } } ] }",
"{\"a\": [ { \"prefix\": { \"equals-ignore-case\": \"abc\", \"test\": \"def\" } } ] }",
"{\"a\": [ { \"prefix\": { \"equals-ignore-case\": \"abc\" }, \"test\": \"def\" } ] }",
"{\"a\": [ { \"prefix\": { \"equals-ignore-case\": [ 1, 2 3 ] } } ] }",
"{\"a\": [ { \"suffix\": { \"invalid-expression\": [ \"abc\" ] } } ] }",
"{\"a\": [ { \"suffix\": { \"equals-ignore-case\": 5 } } ] }",
"{\"a\": [ { \"suffix\": { \"equals-ignore-case\": [ \"abc\" ] } } ] }",
"{\"a\": [ { \"suffix\": { \"equals-ignore-case\": \"abc\", \"test\": \"def\" } } ] }",
"{\"a\": [ { \"suffix\": { \"equals-ignore-case\": \"abc\" }, \"test\": \"def\" } ] }",
"{\"a\": [ { \"suffix\": { \"equals-ignore-case\": [ 1, 2 3 ] } } ] }",
"{\"a\": [ { \"wildcard\": 5 } ] }",
"{\"a\": [ { \"wildcard\": [ \"abc\" ] } ] }"
};
for (String badPattern : badPatternTypes) {
assertNotNull("bad pattern shouldn't parse", RuleCompiler.check(badPattern));
}
j = "{\n"
+ " \"resources\": [\n"
+ " \"r1\",\n"
+ " \"r2\"\n"
+ " ]\n"
+ "}";
m = RuleCompiler.compile(j);
l = m.get("resources");
assertEquals(2, l.size());
ValuePatterns vp1 = (ValuePatterns) l.get(0);
ValuePatterns vp2 = (ValuePatterns) l.get(1);
assertEquals("\"r1\"", vp1.pattern());
assertEquals("\"r2\"", vp2.pattern());
/*
{
"detail-getType": [ "ec2/spot-bid-matched" ],
"detail" : {
"state": [ "in-service" ]
}
}
*/
j = "{\n"
+ " \"detail-getType\": [ \"ec2/spot-bid-matched\" ],\n"
+ " \"detail\" : { \n"
+ " \"state\": [ \"in-service\", \"dead\" ]\n"
+ " }\n"
+ "}\n";
m = RuleCompiler.compile(j);
assertEquals(2, m.size());
l = m.get("detail-getType");
vp1 = (ValuePatterns) l.get(0);
assertEquals("\"ec2/spot-bid-matched\"", vp1.pattern());
l = m.get("detail.state");
assertEquals(2, l.size());
vp1 = (ValuePatterns) l.get(0);
vp2 = (ValuePatterns) l.get(1);
assertEquals("\"in-service\"", vp1.pattern());
assertEquals("\"dead\"", vp2.pattern());
}
@Test
public void testFlattenRule() throws Exception {
final String rule = "{" +
"\"a1\": [123, \"child\", {\"numeric\": [\">\", 0, \"<=\", 5]}]," +
"\"a2\": { \"b\": {" +
"\"c1\": [" +
"{ \"suffix\": \"child\" }," +
"{ \"anything-but\": [111,222,333]}," +
"{ \"anything-but\": { \"prefix\": \"foo\"}}," +
"{ \"anything-but\": { \"suffix\": \"ing\"}}," +
"{ \"anything-but\": {\"equals-ignore-case\": \"def\" } }" +
"]," +
"\"c2\": { \"d\": { \"e\": [" +
"{ \"exactly\": \"child\" }," +
"{ \"exists\": true }," +
"{ \"cidr\": \"10.0.0.0/8\" }" +
"]}}}" +
"}}";
Map<List<String>, List<Patterns>> expected = new HashMap<>();
expected.put(Arrays.asList("a1"), Arrays.asList(
Patterns.numericEquals(123),
Patterns.exactMatch("123"),
Patterns.exactMatch("\"child\""),
Range.between(0, true, 5, false)
));
expected.put(Arrays.asList("a2", "b", "c1"), Arrays.asList(
Patterns.suffixMatch("child\""),
Patterns.anythingButNumberMatch(Stream.of(111, 222, 333).map(Double::valueOf).collect(Collectors.toSet())),
Patterns.anythingButPrefix("\"foo"),
Patterns.anythingButSuffix("ing\""),
Patterns.anythingButIgnoreCaseMatch("\"def\"")
));
expected.put(Arrays.asList("a2", "b", "c2", "d", "e"), Arrays.asList(
Patterns.exactMatch("\"child\""),
Patterns.existencePatterns(),
CIDR.cidr("10.0.0.0/8")
));
assertEquals(expected, RuleCompiler.ListBasedRuleCompiler.flattenRule(rule));
}
@Test
public void testNumericExpressions() {
String[] goods = {
"[\"=\", 3.8]", "[\"=\", 0.00000033]", "[\"=\", -4e-8]", "[\"=\", 55555]",
"[\"<\", 3.8]", "[\"<\", 0.00000033]", "[\"<\", -4e-8]", "[\"<\", 55555]",
"[\">\", 3.8]", "[\">\", 0.00000033]", "[\">\", -4e-8]", "[\">\", 55555]",
"[\"<=\", 3.8]", "[\"<=\", 0.00000033]", "[\"<=\", -4e-8]", "[\"<=\", 55555]",
"[\">=\", 3.8]", "[\">=\", 0.00000033]", "[\">=\", -4e-8]", "[\">=\", 55555]",
"[\">\", 0, \"<\", 1]", "[\">=\", 0, \"<\", 1]",
"[\">\", 0, \"<=\", 1]", "[\">=\", 0, \"<=\", 1]"
};
String[] bads = {
"[\"=\", true]", "[\"=\", 2.0e22]", "[\"=\", \"-4e-8\"]", "[\"=\"]",
"[\"<\", true]", "[\"<\", 2.0e22]", "[\"<\", \"-4e-8\"]", "[\"<\"]",
"[\">=\", true]", "[\">=\", 2.0e22]", "[\">=\", \"-4e-8\"]", "[\">=\"]",
"[\"<=\", true]", "[\"<=\", 2.0e22]", "[\"<=\", \"-4e-8\"]", "[\"<=\"]",
"[\"<>\", 1, \">\", 0]", "[\"==\", 1, \">\", 0]",
"[\"<\", 1, \">\", 0]", "[\">\", 1, \"<\", 1]",
"[\">\", 30, \"<\", 1]", "[\">\", 1, \"<\", 30, false]"
};
for (String good : goods) {
String json = "{\"x\": [{\"numeric\": " + good + "}]}";
String m = RuleCompiler.check(json);
assertNull(json + " => " + m, m);
}
for (String bad : bads) {
String json = "{\"x\": [{\"numeric\": " + bad + "}]}";
String m = RuleCompiler.check(json);
assertNotNull("Bad: " + json, m);
}
}
@Test
public void testExistsExpression() {
String[] goods = {
"true ",
" false "
};
String[] bads = {
"\"badString\"",
"\"= abc\"",
"true, \"extraKey\": \"extraValue\" "
};
for (String good : goods) {
String json = "{\"x\": [{\"exists\": " + good + "}]}";
String m = RuleCompiler.check(json);
assertNull(json + " => " + m, m);
}
for (String bad : bads) {
String json = "{\"x\": [{\"exists\": " + bad + "}]}";
String m = RuleCompiler.check(json);
assertNotNull("Bad: " + json, m);
}
}
@Test
public void testMachineWithNoRules() {
Machine machine = new Machine();
List<String> found = machine.rulesForEvent(Arrays.asList("foo", "bar"));
assertNotNull(found);
assertEquals(0, found.size());
}
@Test
public void testEnd2End() throws Exception {
Machine machine = new Machine();
String[] event = {
"account", "\"012345678901\"",
"detail-getType", "\"ec2/spot-bid-matched\"",
"detail.instanceId", "arn:aws:ec2:us-east-1::image/ami-1a2b3c4d\"",
"detail.spotInstanceRequestId", "\"eaa472d8-8422-a9bb-8888-4919fd99310\"",
"detail.state", "\"in-service\"",
"detail.requestParameters.zone", "\"us-east-1a\"",
"id", "\"cdc73f9d-aea9-11e3-9d5a-835b769c0d9c\"",
"region", "\"us-west-2\"",
"resources", "\"arn:aws:ec2:us-east-1::image/ami-1a2b3c4d\"",
"source", "\"aws.ec2\"",
"tags", "\"2015Q1",
"tags", "\"Euro-fleet\"",
"time", "\"2014-03-18T14:30:07Z\"",
"version", "\"0\"",
};
String rule1 = "{\n"
+ " \"resources\": [\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-1a2b3c4d\",\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-98765432\"\n"
+ " ]\n"
+ "}\n";
String rule2 = "{\n"
+ " \"detail-getType\": [ \"ec2/spot-bid-matched\" ],\n"
+ " \"detail\" : { \n"
+ " \"state\": [ \"in-service\" ]\n"
+ " }\n"
+ "}\n";
String rule3 = "{\n"
+ " \"tags\": [ \"Euro-fleet\", \"Asia-fleet\" ]\n"
+ "}\n";
String rule4 = "{\n"
+ " \"resources\": [\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-1a2b3c4d\",\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-98765432\"\n"
+ " ],\n"
+ " \"detail.state\": [ \"halted\", \"pending\"]\n"
+ "}\n";
String rule5 = "{\n"
+ " \"resources\": [\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-1a2b3c4d\",\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-98765432\"\n"
+ " ],\n"
+ " \"detail.request-level\": [ \"urgent\"]\n"
+ "}\n";
String rule6 = "{\n"
+ " \"detail-getType\": [ \"ec2/spot-bid-matched\" ],\n"
+ " \"detail\" : { \n"
+ " \"requestParameters\": {\n"
+ " \"zone\": [\n"
+ " \"us-east-1a\"\n"
+ " ]\n"
+ " }\n"
+ " }\n"
+ "}\n";
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
machine.addRule("rule3", rule3);
machine.addRule("rule4", rule4);
machine.addRule("rule5", rule5);
machine.addRule("rule6", rule6);
List<String> found = machine.rulesForEvent(event);
assertEquals(4, found.size());
assertTrue(found.contains("rule1"));
assertTrue(found.contains("rule2"));
assertTrue(found.contains("rule3"));
assertTrue(found.contains("rule6"));
}
@Test
public void testEndtoEndinParallel() throws Exception {
int numRules = 1000; // Number of matching rules
String rule1 = "{\n"
+ " \"source\":[\"aws.events\"],\n"
+ " \"resources\": [\n"
+ " \"arn:aws:events:ap-northeast-1:123456789012:event\"\n"
+ " ],\n"
+ " \"detail-getType\":[\"Scheduled Event\"]\n"
+ "}\n";
String rule2 = "{\n"
+ " \"resources\": [\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-1a2b3c4d\",\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-98765432\"\n"
+ " ],\n"
+ " \"detail.state\": [ \"halted\", \"pending\"]\n"
+ "}\n";
String[] event = {
"account", "\"123456789012\"",
"detail-getType", "\"Scheduled Event\"",
"detail.instanceId", "arn:aws:events:ap-northeast-1:123456789012:event\"",
"detail.spotInstanceRequestId", "\"eaa472d8-8422-a9bb-8888-4919fd99310\"",
"detail.state", "\"in-service\"",
"detail.requestParameters.zone", "\"us-east-1a\"",
"id", "\"cdc73f9d-aea9-11e3-9d5a-835b769c0d9c\"",
"region", "\"us-west-2\"",
"resources", "\"arn:aws:events:ap-northeast-1:123456789012:event\"",
"source", "\"aws.events\"",
"tags", "\"2015Q1",
"tags", "\"Euro-fleet\"",
"time", "\"2014-03-18T14:30:07Z\"",
"version", "\"0\"",
};
List<String> rules = new ArrayList<>();
// Add all rules to the machine
for (int i = 0; i < numRules; i++) {
rules.add(rule1);
}
rules.add(rule2);
List<String[]> events = new ArrayList<>();
for (int i = 0; i < numRules; i++) {
events.add(event);
}
multiThreadedTestHelper(rules, events, numRules);
}
@Test
public void testEndToEndInParallelWithDifferentEvents() throws Exception {
int numRules = 1000; // Number of matching rules
String rule1 = "{\n"
+ " \"source\":[\"aws.events\"],\n"
+ " \"resources\": [\n"
+ " \"arn:aws:events:ap-northeast-1:123456789012:event-%d\"\n"
+ " ],\n"
+ " \"detail-getType\":[\"Scheduled Event\"]\n"
+ "}\n";
String rule2 = "{\n"
+ " \"resources\": [\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-1a2b3c4d\",\n"
+ " \"arn:aws:ec2:us-east-1::image/ami-98765432\"\n"
+ " ],\n"
+ " \"detail.state\": [ \"halted\", \"pending\"]\n"
+ "}\n";
String[] event = {
"account", "\"123456789012\"",
"detail-getType", "\"Scheduled Event\"",
"detail.instanceId", "arn:aws:events:ap-northeast-1:123456789012:event\"",
"detail.spotInstanceRequestId", "\"eaa472d8-8422-a9bb-8888-4919fd99310\"",
"detail.state", "\"in-service\"",
"detail.requestParameters.zone", "\"us-east-1a\"",
"id", "\"cdc73f9d-aea9-11e3-9d5a-835b769c0d9c\"",
"region", "\"us-west-2\"",
"resources", "\"arn:aws:events:ap-northeast-1:123456789012:event-%d\"",
"source", "\"aws.events\"",
"tags", "\"2015Q1",
"tags", "\"Euro-fleet\"",
"time", "\"2014-03-18T14:30:07Z\"",
"version", "\"0\"",
};
List<String> rules = new ArrayList<>();
// Add all rules to the machine
for (int i = 0; i < numRules; i++) {
rules.add(String.format(rule1, i));
}
rules.add(rule2);
List<String[]> events = new ArrayList<>();
for (int i = 0; i < numRules; i++) {
event[17] = String.format(event[17], i);
events.add(event);
}
multiThreadedTestHelper(rules, events, 1);
}
@Test
public void testWildcardConsecutiveWildcards() throws IOException {
try {
RuleCompiler.compile("{\"key\": [{\"wildcard\": \"abc**def\"}]}");
fail("Expected JSONParseException");
} catch (JsonParseException e) {
assertEquals("Consecutive wildcard characters at pos 4\n" +
" at [Source: (String)\"{\"key\": [{\"wildcard\": \"abc**def\"}]}\"; line: 1, column: 33]",
e.getMessage());
}
}
@Test
public void testWildcardInvalidEscapeCharacter() throws IOException {
try {
RuleCompiler.compile("{\"key\": [{\"wildcard\": \"a*c\\def\"}]}");
fail("Expected JSONParseException");
} catch (JsonParseException e) {
assertEquals("Unrecognized character escape 'd' (code 100)\n" +
" at [Source: (String)\"{\"key\": [{\"wildcard\": \"a*c\\def\"}]}\"; line: 1, column: 29]",
e.getMessage());
}
}
private void multiThreadedTestHelper(List<String> rules,
List<String[]> events, int numMatchesPerEvent) throws Exception {
int numTries = 30; // Run the test several times as the race condition may be intermittent
int numThreads = 1000;
for (int j = 0; j < numTries; j++) {
Machine machine = new Machine();
CountDownLatch countDownLatch = new CountDownLatch(1);
EventMatcherThreadPool eventMatcherThreadPool = new EventMatcherThreadPool(numThreads, countDownLatch);
int i = 0;
// Add all rules to the machine
for (String rule : rules) {
String ruleName = "rule" + i++;
machine.addRule(ruleName, rule);
}
List<Future<List<String>>> futures =
events.stream().map(event -> eventMatcherThreadPool.addEventsToMatch(machine, event)).collect(Collectors.toList());
countDownLatch.countDown();
for (Future<List<String>> f : futures) {
if (f.get().size() != numMatchesPerEvent) {
fail();
}
}
eventMatcherThreadPool.close();
}
}
static class EventMatcherThreadPool {
private final ExecutorService executorService;
private final CountDownLatch countDownLatch;
EventMatcherThreadPool(int numThreads, CountDownLatch latch) {
executorService = Executors.newFixedThreadPool(numThreads);
countDownLatch = latch;
}
Future<List<String>> addEventsToMatch(Machine m, String[] event) {
return executorService.submit(new MachineRunner(m, event, countDownLatch));
}
void close() {
this.executorService.shutdown();
}
private static class MachineRunner implements Callable<List<String>> {
private final Machine machine;
private final String[] events;
private final CountDownLatch latch;
MachineRunner(Machine machine, String[] events, CountDownLatch latch) {
this.machine = machine;
this.events = events;
this.latch = latch;
}
@Override
public List<String> call() {
try {
latch.await();
} catch (InterruptedException ie) {
//
} //Latch released
return machine.rulesForEvent(events);
}
}
}
}
| 4,855 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/IntIntMapTest.java | package software.amazon.event.ruler;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Set;
public class IntIntMapTest {
@Test(expected=IllegalArgumentException.class)
public void constructor_disallowsInitialCapacityThatIsNotAPowerOfTwo() {
new IntIntMap(3);
}
@Test
public void put_replacesOriginalValue() {
IntIntMap map = new IntIntMap();
Assert.assertEquals(IntIntMap.NO_VALUE, map.put(10, 100));
Assert.assertEquals(1, map.size());
Assert.assertEquals(100, map.put(10, 200));
Assert.assertEquals(1, map.size());
}
@Test
public void put_disallowsNegativeKeys() {
IntIntMap map = new IntIntMap();
try {
map.put(-1234, 5678);
Assert.fail("expected IllegalArgumentException");
} catch (IllegalArgumentException ex) {
}
}
@Test
public void put_disallowsNegativeValues() {
IntIntMap map = new IntIntMap();
try {
map.put(1234, -5678);
Assert.fail("expected IllegalArgumentException");
} catch (IllegalArgumentException ex) {
}
}
@Test
public void get_canRetrieveValues() {
IntIntMap map = new IntIntMap();
for (int key = 0; key < 1000; key++) {
Assert.assertEquals(IntIntMap.NO_VALUE, map.put(key, key * 2));
}
for (int key = 0; key < 1000; key++) {
Assert.assertEquals(key * 2, map.get(key));
}
Assert.assertEquals(IntIntMap.NO_VALUE, map.get(1001));
}
@Test
public void remove_canRemoveValues() {
IntIntMap map = new IntIntMap();
Assert.assertEquals(IntIntMap.NO_VALUE, map.remove(0));
map.put(1234, 5678);
Assert.assertEquals(5678, map.remove(1234));
Assert.assertTrue(map.isEmpty());
}
@Test
public void iterator_returnsAllValues() {
IntIntMap map = new IntIntMap();
Map<Integer, Integer> baseline = new HashMap<>();
for (int key = 0; key < 1000; key++) {
map.put(key, key * 2);
baseline.put(key, key * 2);
}
List<IntIntMap.Entry> entries = new ArrayList<>();
map.entries().iterator().forEachRemaining(entries::add);
Assert.assertEquals(1000, entries.size());
for (IntIntMap.Entry entry : entries) {
Assert.assertEquals(map.get(entry.getKey()), entry.getValue());
Assert.assertEquals(baseline.get(entry.getKey()).intValue(), entry.getValue());
}
}
@Test
public void iterator_returnsEmptyIteratorForEmptyMap() {
IntIntMap map = new IntIntMap();
Iterator<IntIntMap.Entry> iter = map.entries().iterator();
Assert.assertFalse(iter.hasNext());
}
@Test
public void iterator_throwsNoSuchElementExceptionWhenNextIsCalledWithNoMoreElements() {
IntIntMap map = new IntIntMap();
map.put(1, 100);
Iterator<IntIntMap.Entry> iter = map.entries().iterator();
Assert.assertTrue(iter.hasNext());
IntIntMap.Entry entry = iter.next();
Assert.assertEquals(1, entry.getKey());
Assert.assertEquals(100, entry.getValue());
try {
iter.next();
Assert.fail("expected NoSuchElementException");
} catch (NoSuchElementException ex) {
// expected
}
}
@Test
public void clone_createsNewBackingTable() {
IntIntMap map = new IntIntMap();
map.put(123, 456);
IntIntMap cloneMap = (IntIntMap) map.clone();
cloneMap.put(123, 789);
Assert.assertEquals(456, map.get(123));
Assert.assertEquals(789, cloneMap.get(123));
}
@Test
public void stressTest() {
// deterministic seed to prevent unit test flakiness
long seed = 1;
Random random = new Random(seed);
// set a high load factor to increase the chances that we'll see lots of hash collisions
float loadFactor = 0.99f;
IntIntMap map = new IntIntMap(2, loadFactor);
Map<Integer, Integer> baseline = new HashMap<>();
for (int trial = 0; trial < 50; trial++) {
for (int i = 0; i < 100_000; i++) {
int key = random.nextInt(Integer.MAX_VALUE);
int value = random.nextInt(Integer.MAX_VALUE);
int mapOut = map.put(key, value);
Integer baselineOut = baseline.put(key, value);
Assert.assertEquals(baselineOut == null ? IntIntMap.NO_VALUE : baselineOut.intValue(), mapOut);
Assert.assertEquals(baseline.size(), map.size());
}
// Now remove half, randomly
Set<Integer> baselineKeys = new HashSet<>(baseline.keySet());
for (Integer key : baselineKeys) {
if (random.nextBoolean()) {
Assert.assertEquals(baseline.remove(key).intValue(), map.remove(key));
}
}
Assert.assertEquals(baseline.size(), map.size());
}
}
@Test
public void stressTest_rehash() {
// deterministic seed to prevent unit test flakiness
long seed = 1;
Random random = new Random(seed);
for (int trial = 0; trial < 100_000; trial++) {
// start the map off with the smallest possible initial capacity
IntIntMap map = new IntIntMap(1);
Map<Integer, Integer> baseline = new HashMap<>();
for (int i = 0 ; i < 16; i++) {
int key = random.nextInt(Integer.MAX_VALUE);
int value = random.nextInt(Integer.MAX_VALUE);
map.put(key, value);
baseline.put(key, value);
}
for (Integer key : baseline.keySet()) {
Assert.assertEquals(baseline.get(key).intValue(), map.get(key));
}
}
}
}
| 4,856 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/ACMachineTest.java | package software.amazon.event.ruler;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit testing a state machine is hard. Tried hand-computing a few machines
* but kept getting them wrong, the software was right. So this is really
* more of a smoke/integration test. But the coverage is quite good.
*/
public class ACMachineTest {
private String toIP(int ip) {
StringBuilder sb = new StringBuilder();
sb.append((ip >> 24) & 0xFF).append('.');
sb.append((ip >> 16) & 0xFF).append('.');
sb.append((ip >> 8) & 0xFF).append('.');
sb.append(ip & 0xFF);
return sb.toString();
}
@Test
public void CIDRTest() throws Exception {
String template = "{" +
" \"a\": \"IP\"" +
"}";
long base = 0x0A000000;
// tested by hand with much smaller starts but the runtime gets looooooooong
for (int i = 22; i < 32; i++) {
String rule = "{ " +
" \"a\": [ {\"cidr\": \"10.0.0.0/" + i + "\"} ]" +
"}";
Machine m = new Machine();
m.addRule("r", rule);
long numberThatShouldMatch = 1L << (32 - i);
// don't want to run through all of them for low values of maskbits
long windowEnd = base + numberThatShouldMatch + 16;
int matches = 0;
for (long j = base - 16; j < windowEnd; j++) {
String event = template.replace("IP", toIP((int) j));
if (m.rulesForJSONEvent(event).size() == 1) {
matches++;
}
}
assertEquals(numberThatShouldMatch, matches);
}
}
@Test
public void testIPAddressOfCIDRIsEqualToMaximumOfRange() throws Exception {
String rule1 = "{\"sourceIPAddress\": [{\"cidr\": \"220.160.153.171/31\"}]}";
String rule2 = "{\"sourceIPAddress\": [{\"cidr\": \"220.160.154.255/24\"}]}";
String rule3 = "{\"sourceIPAddress\": [{\"cidr\": \"220.160.59.225/31\"}]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
machine.addRule("rule3", rule3);
List<String> matches = machine.rulesForJSONEvent("{\"sourceIPAddress\": \"220.160.153.170\"}");
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
matches = machine.rulesForJSONEvent("{\"sourceIPAddress\": \"220.160.153.171\"}");
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
matches = machine.rulesForJSONEvent("{\"sourceIPAddress\": \"220.160.153.169\"}");
assertTrue(matches.isEmpty());
matches = machine.rulesForJSONEvent("{\"sourceIPAddress\": \"220.160.153.172\"}");
assertTrue(matches.isEmpty());
matches = machine.rulesForJSONEvent("{\"sourceIPAddress\": \"220.160.154.0\"}");
assertEquals(1, matches.size());
assertTrue(matches.contains("rule2"));
matches = machine.rulesForJSONEvent("{\"sourceIPAddress\": \"220.160.154.255\"}");
assertEquals(1, matches.size());
assertTrue(matches.contains("rule2"));
matches = machine.rulesForJSONEvent("{\"sourceIPAddress\": \"220.160.153.255\"}");
assertTrue(matches.isEmpty());
matches = machine.rulesForJSONEvent("{\"sourceIPAddress\": \"220.160.155.0\"}");
assertTrue(matches.isEmpty());
matches = machine.rulesForJSONEvent("{\"sourceIPAddress\": \"220.160.59.224\"}");
assertEquals(1, matches.size());
assertTrue(matches.contains("rule3"));
matches = machine.rulesForJSONEvent("{\"sourceIPAddress\": \"220.160.59.225\"}");
assertEquals(1, matches.size());
assertTrue(matches.contains("rule3"));
matches = machine.rulesForJSONEvent("{\"sourceIPAddress\": \"220.160.59.223\"}");
assertTrue(matches.isEmpty());
matches = machine.rulesForJSONEvent("{\"sourceIPAddress\": \"220.160.59.226\"}");
assertTrue(matches.isEmpty());
}
private static final String JSON_FROM_README = "{\n" +
" \"version\": \"0\",\n" +
" \"id\": \"ddddd4-aaaa-7777-4444-345dd43cc333\",\n" +
" \"detail-type\": \"EC2 Instance State-change Notification\",\n" +
" \"source\": \"aws.ec2\",\n" +
" \"account\": \"012345679012\",\n" +
" \"time\": \"2017-10-02T16:24:49Z\",\n" +
" \"region\": \"us-east-1\",\n" +
" \"resources\": [\n" +
" \"arn:aws:ec2:us-east-1:012345679012:instance/i-000000aaaaaa00000\"\n" +
" ],\n" +
" \"detail\": {\n" +
" \"c.count\": 5,\n" +
" \"d.count\": 3,\n" +
" \"x.limit\": 301.8,\n" +
" \"instance-id\": \"i-000000aaaaaa00000\",\n" +
" \"state\": \"running\"\n" +
" }\n" +
"}\n";
@Test
public void rulesFromREADMETest() throws Exception {
String[] rules = {
"{\n" +
" \"detail-type\": [ \"EC2 Instance State-change Notification\" ],\n" +
" \"resources\": [ \"arn:aws:ec2:us-east-1:012345679012:instance/i-000000aaaaaa00000\" ],\n" +
" \"detail\": {\n" +
" \"state\": [ \"initializing\", \"running\" ]\n" +
" }\n" +
"}",
"{\n" +
" \"time\": [ { \"prefix\": \"2017-10-02\" } ],\n" +
" \"detail\": {\n" +
" \"state\": [ { \"anything-but\": \"initializing\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"time\": [ { \"prefix\": \"2017-10-02\" } ],\n" +
" \"detail\": {\n" +
" \"state\": [ { \"suffix\": \"ing\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"detail\": {\n" +
" \"c.count\": [ { \"numeric\": [ \">\", 0, \"<=\", 5 ] } ],\n" +
" \"d.count\": [ { \"numeric\": [ \"<\", 10 ] } ],\n" +
" \"x.limit\": [ { \"numeric\": [ \"=\", 3.018e2 ] } ]\n" +
" }\n" +
"} \n",
"{\n" +
" \"detail\": {\n" +
" \"state\": [ { \"anything-but\": { \"prefix\": \"init\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"detail\": {\n" +
" \"instance-id\": [ { \"anything-but\": { \"suffix\": \"1234\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"detail\": {\n" +
" \"state\": [ { \"anything-but\": {\"equals-ignore-case\": [\"Stopped\", \"OverLoaded\"] } } ]\n" +
" }\n" +
"}"
};
for (String rule : rules) {
Machine m = new Machine();
m.addRule("r0", rule);
assertEquals(1, m.rulesForJSONEvent(JSON_FROM_README).size());
}
}
@Test
public void songsACTest() throws Exception {
String songs = "{\n" +
" \"Year\": 1966,\n" +
" \"Genres\": [" +
" { \"Pop\": true }," +
" { \"Classical\": false }" +
" ]," +
" \"Songs\": [\n" +
" {\n" +
" \"Name\": \"Paperback Writer\",\n" +
" \"Writers\": [\n" +
" { \"First\": \"John\", \"Last\": \"Lennon\" },\n" +
" { \"First\": \"Paul\", \"Last\": \"McCartney\" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"Name\": \"Paint It Black\",\n" +
" \"Writers\": [\n" +
" { \"First\": \"Mick\", \"Last\": \"Jagger\" },\n" +
" { \"First\": \"Keith\", \"Last\": \"Richards\" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}\n";
String[] rulesThatShouldMatch = {
"{\"Year\": [ 1966 ], \"Songs\": { \"Name\":[ \"Paperback Writer\" ], \"Writers\": { \"First\": [ \"Paul\" ], \"Last\":[\"McCartney\"]}}}",
"{\"Genres\": { \"Pop\": [ true ] }, \"Songs\": { \"Name\":[ \"Paint It Black\" ] }}",
"{\"Year\": [ 1966 ], \"Songs\": { \"Name\":[ \"Paint It Black\" ] }}",
"{\"Songs\": { \"Name\":[ \"Paperback Writer\" ], \"Writers\": { \"First\": [ \"Paul\" ], \"Last\":[\"McCartney\"]}}}"
};
String[] rulesThatShouldFail = {
"{\"Year\": [ 1966 ], \"Songs\": { \"Name\":[ \"Paperback Writer\" ], \"Writers\": { \"First\": [ \"Mick\" ] }}}",
"{\"Songs\": { \"Writers\": { \"First\": [ \"Mick\" ], \"Last\": [ \"McCartney\" ] }}}",
"{\"Genres\": { \"Pop\": [ true ] }, \"Songs\": { \"Writers\": { \"First\": [ \"Mick\" ], \"Last\": [ \"McCartney\" ] }}}",
};
Machine m = new Machine();
for (int i = 0; i < rulesThatShouldMatch.length; i++) {
String rule = rulesThatShouldMatch[i];
String name = String.format("r%d", i);
m.addRule(name, rule);
}
for (int i = 0; i < rulesThatShouldFail.length; i++) {
String rule = rulesThatShouldFail[i];
String name = String.format("f%d", i);
m.addRule(name, rule);
}
List<String> result = m.rulesForJSONEvent(songs);
assertEquals(rulesThatShouldMatch.length, result.size());
for (int i = 0; i < rulesThatShouldMatch.length; i++) {
String name = String.format("r%d", i);
assertTrue(result.contains(name));
}
for (int i = 0; i < rulesThatShouldMatch.length; i++) {
String name = String.format("f%d", i);
assertFalse(result.contains(name));
}
}
@Test
public void intensitiesACTest() throws Exception {
String intensities = "{\n" +
" \"lines\": [{ \n" +
" \"intensities\": [\n" +
" [\n" +
" 0.5\n" +
" ]\n" +
" ],\n" +
" \"points\": [\n" +
" [\n" +
" [\n" +
" {\"pp\" : \"index0\"},\n" +
" 483.3474497412421,\n" +
" 287.48116291799363\n" +
" ],\n" +
" [\n" +
" {\"pp\" : \"index1\"},\n" +
" 489.9999497412421,\n" +
" 299.99996291799363\n" +
" ]\n" +
" \n" +
" ]\n" +
" ]\n" +
" }]\n" +
"}";
String rule = "{\n" +
" \"lines\": \n" +
" { \n" +
" \"points\": [287.48116291799363],\n" +
" \"points\": { \n" +
" \"pp\" : [\"index0\"]\n" +
" }\n" +
" }\n" +
"}";
Machine m = new Machine();
m.addRule("r", rule);
List<String> result = m.rulesForJSONEvent(intensities);
assertEquals(1, result.size());
}
@Test
public void testSimplestPossibleMachine() throws Exception {
String rule1 = "{ \"a\" : [ 1 ] }";
String rule2 = "{ \"b\" : [ 2 ] }";
Machine machine = new Machine();
machine.addRule("r1", rule1);
machine.addRule("r2", rule2);
String event1 = "{ \"a\": 1 }";
String event2 = "{ \"b\": 2 }";
String event3 = "{ \"x\": true }";
List<String> val;
val = machine.rulesForJSONEvent(event1);
assertEquals(1, val.size());
assertEquals("r1", val.get(0));
val = machine.rulesForJSONEvent(event2);
assertEquals(1, val.size());
assertEquals("r2", val.get(0));
val = machine.rulesForJSONEvent(event3);
assertEquals(0, val.size());
}
@Test
public void testPrefixMatching() throws Exception {
String rule1 = "{ \"a\" : [ { \"prefix\": \"zoo\" } ] }";
String rule2 = "{ \"b\" : [ { \"prefix\": \"child\" } ] }";
Machine machine = new Machine();
machine.addRule("r1", rule1);
machine.addRule("r2", rule2);
String[] events = {
"{\"a\": \"zookeeper\"}",
"{\"a\": \"zoo\"}",
"{\"b\": \"childlike\"}",
"{\"b\": \"childish\"}",
"{\"b\": \"childhood\"}"
};
for (String event : events) {
List<String> rules = machine.rulesForJSONEvent(event);
assertEquals(1, rules.size());
if (event.contains("\"a\"")) {
assertEquals("r1", rules.get(0));
} else {
assertEquals("r2", rules.get(0));
}
}
machine = new Machine();
String rule3 = "{ \"a\" : [ { \"prefix\": \"al\" } ] }";
String rule4 = "{ \"a\" : [ \"albert\" ] }";
machine.addRule("r3", rule3);
machine.addRule("r4", rule4);
String e2 = "{ \"a\": \"albert\"}";
List<String> rules = machine.rulesForJSONEvent(e2);
assertEquals(2, rules.size());
}
@Test
public void testPrefixEqualsIgnoreCase() throws Exception {
String rule1 = "{ \"a\" : [ { \"prefix\": { \"equals-ignore-case\" : \"zoo\" } } ] }";
String rule2 = "{ \"b\" : [ { \"prefix\": { \"equals-ignore-case\" : \"child\" } } ] }";
Machine machine = new Machine();
machine.addRule("r1", rule1);
machine.addRule("r2", rule2);
String[] events = {
"{\"a\": \"zOokeeper\"}",
"{\"a\": \"Zoo\"}",
"{\"b\": \"cHildlike\"}",
"{\"b\": \"chIldish\"}",
"{\"b\": \"childhood\"}"
};
for (String event : events) {
List<String> rules = machine.rulesForJSONEvent(event);
assertEquals(1, rules.size());
if (event.contains("\"a\"")) {
assertEquals("r1", rules.get(0));
} else {
assertEquals("r2", rules.get(0));
}
}
machine = new Machine();
String rule3 = "{ \"a\" : [ { \"prefix\": { \"equals-ignore-case\" : \"al\" } } ] }";
String rule4 = "{ \"a\" : [ \"ALbert\" ] }";
machine.addRule("r3", rule3);
machine.addRule("r4", rule4);
String e2 = "{ \"a\": \"ALbert\"}";
List<String> rules = machine.rulesForJSONEvent(e2);
assertEquals(2, rules.size());
}
@Test
public void testSuffixEqualsIgnoreCase() throws Exception {
String rule1 = "{ \"a\" : [ { \"suffix\": { \"equals-ignore-case\" : \"eper\" } } ] }";
String rule2 = "{ \"b\" : [ { \"suffix\": { \"equals-ignore-case\" : \"hood\" } } ] }";
Machine machine = new Machine();
machine.addRule("r1", rule1);
machine.addRule("r2", rule2);
String[] events = {
"{\"a\": \"zookeePer\"}",
"{\"a\": \"Gatekeeper\"}",
"{\"b\": \"hOod\"}",
"{\"b\": \"parenthOod\"}",
"{\"b\": \"brotherhood\"}",
"{\"b\": \"childhOoD\"}"
};
for (String event : events) {
List<String> rules = machine.rulesForJSONEvent(event);
assertEquals(1, rules.size());
if (event.contains("\"a\"")) {
assertEquals("r1", rules.get(0));
} else {
assertEquals("r2", rules.get(0));
}
}
machine = new Machine();
String rule3 = "{ \"a\" : [ { \"suffix\": { \"equals-ignore-case\" : \"ert\" } } ] }";
String rule4 = "{ \"a\" : [ \"AlbeRT\" ] }";
machine.addRule("r3", rule3);
machine.addRule("r4", rule4);
String e2 = "{ \"a\": \"AlbeRT\"}";
List<String> rules = machine.rulesForJSONEvent(e2);
assertEquals(2, rules.size());
}
@Test
public void testSuffixEqualsIgnoreCaseChineseMatch() throws Exception {
Machine m = new Machine();
String rule = "{\n" +
" \"status\": {\n" +
" \"weatherText\": [{\"suffix\": \"统治者\"}]\n" +
" }\n" +
"}";
String eventStr ="{\n" +
" \"status\": {\n" +
" \"weatherText\": \"事件统治者\",\n" +
" \"pm25\": 23\n" +
" }\n" +
"}";
m.addRule("r1", rule);
List<String> matchRules = m.rulesForJSONEvent(eventStr);
assertEquals(1, matchRules.size());
}
@Test
public void testSuffixChineseMatch() throws Exception {
Machine m = new Machine();
String rule = "{\n" +
" \"status\": {\n" +
" \"weatherText\": [{\"suffix\": \"统治者\"}]\n" +
" }\n" +
"}";
String eventStr ="{\n" +
" \"status\": {\n" +
" \"weatherText\": \"事件统治者\",\n" +
" \"pm25\": 23\n" +
" }\n" +
"}";
m.addRule("r1", rule);
List<String> matchRules = m.rulesForJSONEvent(eventStr);
assertEquals(1, matchRules.size());
}
@Test
public void testCityLotsProblemLines() throws Exception {
String eJSON = "{" +
" \"geometry\": {\n" +
" \"coordinates\": [ -122.4286089609642, 37.795818585593523 ],\n" +
" \"type\": \"Polygon\"\n" +
" },\n" +
" \"properties\": {\n" +
" \"BLKLOT\": \"0567002\",\n" +
" \"BLOCK_NUM\": \"0567\",\n" +
" \"FROM_ST\": \"2521\",\n" +
" \"LOT_NUM\": \"002\",\n" +
" \"MAPBLKLOT\": \"0567002\",\n" +
" \"ODD_EVEN\": \"O\",\n" +
" \"STREET\": \"OCTAVIA\",\n" +
" \"ST_TYPE\": \"ST\",\n" +
" \"TO_ST\": \"2521\"\n" +
" }\n" +
"}\n";
String rule = "{" +
" \"properties\": {" +
" \"FROM_ST\": [ \"2521\" ]" +
" },\n" +
" \"geometry\": {\n" +
" \"type\": [ \"Polygon\" ]" +
" }" +
"}";
Machine machine = new Machine();
machine.addRule("R1", rule);
List<String> r = machine.rulesForJSONEvent(eJSON);
assertEquals(1, r.size());
assertEquals("R1", r.get(0));
}
private void setRules(Machine machine) {
List<Rule> rules = new ArrayList<>();
Rule rule;
rule = new Rule("R1");
rule.setKeys("beta", "alpha", "gamma");
rule.setExactMatchValues("2", "1", "3");
rules.add(rule);
rule = new Rule("R2");
rule.setKeys("alpha", "foo", "bar");
rule.setExactMatchValues("1", "\"v23\"", "\"v22\"");
rules.add(rule);
rule = new Rule("R3");
rule.setKeys("inner", "outer", "upper");
rule.setExactMatchValues("\"i0\"", "\"i1\"", "\"i2\"");
rules.add(rule);
rule = new Rule("R4");
rule.setKeys("d1", "d2");
rule.setExactMatchValues("\"v1\"", "\"v2\"");
rules.add(rule);
rule = new Rule("R5-super");
rule.setKeys("r5-k1", "r5-k2", "r5-k3");
rule.setExactMatchValues("\"r5-v1\"", "\"r5-v2\"", "\"r5-v3\"");
rules.add(rule);
rule = new Rule("R5-prefix");
rule.setKeys("r5-k1", "r5-k2");
rule.setExactMatchValues("\"r5-v1\"", "\"r5-v2\"");
rules.add(rule);
rule = new Rule("R5-suffix");
rule.setKeys("r5-k2", "r5-k3");
rule.setExactMatchValues("\"r5-v2\"", "\"r5-v3\"");
rules.add(rule);
rule = new Rule("R6");
List<Patterns> x15_25 = new ArrayList<>();
x15_25.add(Patterns.exactMatch("15"));
x15_25.add(Patterns.exactMatch("25"));
rule.addMulti(x15_25);
rule.setKeys("x1", "x7");
rule.setExactMatchValues("11", "50");
rules.add(rule);
rule = new Rule("R7");
rule.setKeys("r5-k1");
rule.setPatterns(Patterns.prefixMatch("\"r5"));
rules.add(rule);
for (Rule r : rules) {
machine.addPatternRule(r.name, r.fields);
}
}
private List<TestEvent> createEvents() {
List<TestEvent> events = new ArrayList<>();
TestEvent e;
// match an event exactly
e = new TestEvent("alpha", "1", "beta", "2", "gamma", "3");
e.setExpected("R1");
events.add(e);
// extras between all the fields, should still match
e = new TestEvent("0", "\"\"", "alpha", "1", "arc", "\"xx\"", "beta", "2", "gamma", "3", "zoo", "\"keeper\"");
e.setExpected("R1");
events.add(e);
// fail on value
e = new TestEvent("alpha", "1", "beta", "3", "gamma", "3");
events.add(e);
// fire two rules
e = new TestEvent("alpha", "1", "beta", "2", "gamma", "3", "inner", "\"i0\"", "outer", "\"i1\"", "upper", "\"i2\"");
e.setExpected("R1", "R3");
events.add(e);
// one rule inside another
e = new TestEvent("alpha", "1", "beta", "2", "d1", "\"v1\"", "d2", "\"v2\"", "gamma", "3");
e.setExpected("R1", "R4");
events.add(e);
// two rules in a funny way
e = new TestEvent("0", "\"\"", "alpha", "1", "arc", "\"xx\"", "bar", "\"v22\"", "beta", "2", "foo", "\"v23\"", "gamma", "3",
"zoo", "\"keeper\"");
e.setExpected("R1", "R2");
events.add(e);
// match prefix rule
e = new TestEvent("r5-k1", "\"r5-v1\"", "r5-k2", "\"r5-v2\"");
e.setExpected("R5-prefix", "R7");
events.add(e);
// match 3 rules
e = new TestEvent("r5-k1", "\"r5-v1\"", "r5-k2", "\"r5-v2\"", "r5-k3", "\"r5-v3\"");
e.setExpected("R5-prefix", "R5-super", "R5-suffix", "R7");
events.add(e);
// single state with two branches
e = new TestEvent("zork", "\"max\"", "x1", "11", "x6", "15", "x7", "50");
e.setExpected("R6");
events.add(e);
e = new TestEvent("x1", "11", "x6", "25", "foo", "\"bar\"", "x7", "50");
e.setExpected("R6");
events.add(e);
// extras between all the fields, should still match
e = new TestEvent("0", "\"\"", "alpha", "1", "arc", "\"xx\"", "beta", "2", "gamma", "3", "zoo", "\"keeper\"");
e.setExpected("R1");
events.add(e);
// fail on value
e = new TestEvent("alpha", "1", "beta", "3", "gamma", "3");
events.add(e);
// fire two rules
e = new TestEvent("alpha", "1", "beta", "2", "gamma", "3", "inner", "\"i0\"", "outer", "\"i1\"", "upper", "\"i2\"");
e.setExpected("R1", "R3");
events.add(e);
// one rule inside another
e = new TestEvent("alpha", "1", "beta", "2", "d1", "\"v1\"", "d2", "\"v2\"", "gamma", "3");
e.setExpected("R1", "R4");
events.add(e);
// two rules in a funny way
e = new TestEvent("0", "\"\"", "alpha", "1", "arc", "\"xx\"", "bar", "\"v22\"", "beta", "2", "foo", "\"v23\"", "gamma", "3",
"zoo", "\"keeper\"");
e.setExpected("R1", "R2");
events.add(e);
// match prefix rule
e = new TestEvent("r5-k1", "\"r5-v1\"", "r5-k2", "\"r5-v2\"");
e.setExpected("R5-prefix", "R7");
events.add(e);
// match 3 rules
e = new TestEvent("r5-k1", "\"r5-v1\"", "r5-k2", "\"r5-v2\"", "r5-k3", "\"r5-v3\"");
e.setExpected("R5-prefix", "R5-super", "R5-suffix", "R7");
events.add(e);
// single state with two branches
e = new TestEvent("zork", "\"max\"", "x1", "11", "x6", "15", "x7", "50");
e.setExpected("R6");
events.add(e);
e = new TestEvent("x1", "11", "x6", "25", "foo", "\"bar\"", "x7", "50");
e.setExpected("R6");
events.add(e);
return events;
}
@Test
public void testBuild() throws Exception {
Machine machine = new Machine();
setRules(machine);
assertNotNull(machine);
List<TestEvent> events = createEvents();
for (TestEvent event : events) {
singleEventTest(machine, event);
}
}
private void singleEventTest(Machine machine, TestEvent event) throws Exception {
List<String> actual = machine.rulesForJSONEvent(event.toString());
if (event.mExpectedRules.isEmpty()) {
assertTrue(actual.isEmpty());
} else {
for (String expected : event.mExpectedRules) {
assertTrue("Event " + event + "\n did not match rule '" + expected + "'", actual.contains(expected));
actual.remove(expected);
}
if (!actual.isEmpty()) {
fail("Event " + event + "\n rule " + actual.size() + " extra rules: " + actual.get(0));
}
}
}
private static class TestEvent {
private final List<String> mExpectedRules = new ArrayList<>();
private final String jsonString;
TestEvent(String... tokens) {
StringBuilder sb = new StringBuilder("{");
for (int i = 0; i < tokens.length; i += 2) {
if (i > 0) {
sb.append(',');
}
sb.append('"').append(tokens[i]).append("\":").append(tokens[i + 1]);
}
sb.append('}');
jsonString = sb.toString();
}
void setExpected(String... rules) {
Collections.addAll(mExpectedRules, rules);
}
@Override
public String toString() {
return jsonString;
}
}
private static class Rule {
String name;
final Map<String, List<Patterns>> fields = new HashMap<>();
private String[] keys;
Rule(String name) {
this.name = name;
}
void setKeys(String... keys) {
this.keys = keys;
}
void setExactMatchValues(String... values) {
for (int i = 0; i < values.length; i++) {
final List<Patterns> valList = new ArrayList<>();
valList.add(Patterns.exactMatch(values[i]));
fields.put(keys[i], valList);
}
}
void setPatterns(Patterns... values) {
for (int i = 0; i < values.length; i++) {
final List<Patterns> valList = new ArrayList<>();
valList.add((values[i]));
fields.put(keys[i], valList);
}
}
void addMulti(List<Patterns> vals) {
fields.put("x6", vals);
}
}
@Test
public void addRuleOriginalAPI() throws Exception {
Machine machine = new Machine();
String rule1 = "{ \"f1\": [ \"x\", \"y\"], \"f2\": [1,2]}";
String rule2 = "{ \"f1\": [\"foo\", \"bar\"] }";
machine.addRule("r1", rule1);
machine.addRule("r2", rule2);
String event1 = "{ \"f1\": \"x\", \"f2\": 1 }";
String event2 = "{ \"f1\": \"foo\" }";
List<String> l = machine.rulesForJSONEvent(event1);
assertEquals(1, l.size());
assertEquals("r1", l.get(0));
l = machine.rulesForJSONEvent(event2);
assertEquals(1, l.size());
assertEquals("r2", l.get(0));
}
@Test
public void twoRulesSamePattern() throws Exception {
Machine machine = new Machine();
String json = "{\"detail\":{\"testId\":[\"foo\"]}}";
machine.addRule("rule1", json);
machine.addRule("rule2", new StringReader(json));
machine.addRule("rule3", json.getBytes(StandardCharsets.UTF_8));
machine.addRule("rule4", new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));
String e = "{ \"detail\": { \"testId\": \"foo\"}}";
List<String> strings = machine.rulesForJSONEvent(e);
assertEquals(4, strings.size());
}
@Test
public void twoRulesSamePattern2() throws Exception {
Machine machine = new Machine();
List<Rule> rules = new ArrayList<>();
Rule rule;
rule = new Rule("R1");
rule.setKeys("a", "c", "b");
rule.setExactMatchValues("1", "3", "2");
rules.add(rule);
rule = new Rule("R2");
rule.setKeys("a", "b", "c");
rule.setExactMatchValues("1", "2", "3");
rules.add(rule);
for (Rule r : rules) {
machine.addPatternRule(r.name, r.fields);
}
TestEvent e = new TestEvent("0", "\"\"", "a", "1", "b", "2", "c", "3", "gamma", "3", "zoo", "\"keeper\"");
e.setExpected("R1", "R2");
List<String> actual = machine.rulesForJSONEvent(e.toString());
assertEquals(2, actual.size());
}
@Test
public void dynamicAddRules() throws Exception {
Machine machine = new Machine();
TestEvent e = new TestEvent("0", "\"\"", "a", "11", "b", "21", "c", "31", "gamma", "41", "zoo", "\"keeper\"");
Rule rule;
Rule rule1;
Rule rule2;
Rule rule3;
rule = new Rule("R1");
rule.setKeys("a", "b","c");
rule.setExactMatchValues("11", "21","31");
//test whether duplicated rule could be added
machine.addPatternRule(rule.name, rule.fields);
machine.addPatternRule(rule.name, rule.fields);
machine.addPatternRule(rule.name, rule.fields);
rule1 = new Rule("R1");
rule1.setKeys("a", "b","zoo");
rule1.setExactMatchValues("11", "21","\"keeper\"");
machine.addPatternRule(rule1.name, rule1.fields);
List<String> actual1 = machine.rulesForJSONEvent(e.toString());
assertEquals(1, actual1.size());
rule2 = new Rule("R2-1");
rule2.setKeys("a", "c", "b");
rule2.setExactMatchValues("11", "31", "21");
machine.addPatternRule(rule2.name, rule2.fields);
List<String> actual2 = machine.rulesForJSONEvent(e.toString());
assertEquals(2, actual2.size());
rule3 = new Rule("R2-2");
rule3.setKeys("gamma", "zoo");
rule3.setExactMatchValues("41", "\"keeper\"");
machine.addPatternRule(rule3.name, rule3.fields);
List<String> actual3 = machine.rulesForJSONEvent(e.toString());
assertEquals(3, actual3.size());
}
/**
* Incrementally build Rule R1 by different namevalues, observing new state and rules created
* Decrementally delete rule R1 by pointed namevalues, observing state and rules
* which is not used have been removed.
*/
@Test
public void dynamicDeleteRules() throws Exception {
Machine machine = new Machine();
TestEvent e = new TestEvent("0", "\"\"", "a", "11", "b", "21", "c", "31", "gamma", "41", "zoo", "\"keeper\"");
Rule rule;
Rule rule1;
rule = new Rule("R1");
rule.setKeys("a", "b", "c");
rule.setExactMatchValues("11", "21", "31");
machine.addPatternRule(rule.name, rule.fields);
List<String> actual = machine.rulesForJSONEvent(e.toString());
assertEquals(1, actual.size());
rule1 = new Rule("R1");
rule1.setKeys("a", "b","gamma");
rule1.setExactMatchValues("11", "21","41");
machine.addPatternRule(rule1.name, rule1.fields);
List<String> actual1 = machine.rulesForJSONEvent(e.toString());
assertEquals(1, actual1.size());
// delete R1 subset with rule.fields
machine.deletePatternRule(rule.name, rule.fields);
List<String> actual2 = machine.rulesForJSONEvent(e.toString());
assertEquals(1, actual2.size());
// delete R1 subset with rule1 fields, after this step,
// the machine will become empty as if no rule was added before.
machine.deletePatternRule(rule1.name, rule1.fields);
List<String> actual3 = machine.rulesForJSONEvent(e.toString());
assertEquals(0, actual3.size());
}
/**
* Setup thread pools with 310 threads inside, among them, 300 threads are calling rulesForJSONEvent(),
* 10 threads are adding rule. the test is designed to add rules and match rules operation handled in parallel,
* observe rulesForJSONEvent whether could work well while there is new rule keeping added dynamically in parallel.
* Keep same event call rulesForJSONEvent() in parallel, expect to see more and more rules will be matched
* aligned with more and more new rules added.
* In this test:
* We created 100 rules with 100 key/val pair (each rule use one key/val), we created one "global" event by using
* those 100 key/val pairs. this event should match out all those 100 rules since they are added.
* So if we keep using this event query machine while adding 100 rules in parallel, we should see the output of
* number of matched rules by rulesForJSONEvent keep increasing from 0 to 100, then stabilize returning 100 for
* all of following rulesForJSONEvent().
*/
@Test
public void testMultipleThreadReadAddRule() throws Exception {
Machine machine = new Machine();
List<String> event = new ArrayList<>();
List <Rule> rules = new ArrayList<>();
for (int i = 0; i< 100; i++) {
event.add(String.format("key-%03d",i));
event.add(String.format("\"val-%03d\"",i));
}
StringBuilder sb = new StringBuilder("{");
for (int i = 0; i < event.size(); i += 2) {
if (i > 0) {
sb.append(',');
}
sb.append('"').append(event.get(i)).append("\":").append(event.get(i+1));
}
sb.append('}');
String eString = sb.toString();
for (int j = 0, i = 0; j<200 && i<100; j+=2,i++) {
Rule rule = new Rule("R-" + i);
rule.setKeys(event.get(j));
rule.setExactMatchValues(event.get(j+1));
rules.add(rule);
}
CountDownLatch latch = new CountDownLatch(1);
class AddRuleRunnable implements Runnable {
private final int i;
private AddRuleRunnable(int i) {
this.i = i;
}
@Override
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
Rule rule = rules.get(i);
machine.addPatternRule(rule.name,rule.fields);
}
}
class MatchRuleRunnable implements Runnable {
@Override
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
int i = 0;
int n;
// this thread only return when match out 100 rules 100 times.
try {
while (i < 100) {
List<String> actual = machine.rulesForJSONEvent(eString);
// the number of matched rules will keep growing from 0 till to 100
n = actual.size();
if (n == 100) {
i++;
}
}
} catch (Exception e) {
System.err.println("OUCH: " + e.getMessage());
}
}
}
ExecutorService execW = Executors.newFixedThreadPool(10);
ExecutorService execR = Executors.newFixedThreadPool(300);
for(int i = 0; i < 100; i++) {
execW.execute(new AddRuleRunnable(i));
}
for(int i = 0; i < 300; i++) {
execR.execute(new MatchRuleRunnable());
}
// release threads to let them work
latch.countDown();
execW.shutdown();
execR.shutdown();
try {
execW.awaitTermination(5, TimeUnit.MINUTES);
execR.awaitTermination(5, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
List<String> actual = machine.rulesForJSONEvent(eString);
assertEquals(100, actual.size());
}
@Test
public void testMultipleThreadReadDeleteRule() throws Exception {
Machine machine = new Machine();
List<String> event = new ArrayList<>();
List <Rule> rules = new ArrayList<>();
for (int i = 0; i< 100; i++) {
event.add(String.format("key-%03d",i));
event.add(String.format("\"val-%03d\"",i));
}
StringBuilder sb = new StringBuilder("{");
for (int i = 0; i < event.size(); i += 2) {
if (i > 0) {
sb.append(',');
}
sb.append('"').append(event.get(i)).append("\":").append(event.get(i+1));
}
sb.append('}');
String eString = sb.toString();
// first add 100 rules into machine.
for (int j = 0, i = 0; j<200 && i<100; j+=2,i++) {
Rule rule = new Rule("R-" + i);
rule.setKeys(event.get(j));
rule.setExactMatchValues(event.get(j+1));
rules.add(rule);
machine.addPatternRule(rule.name,rule.fields);
}
CountDownLatch latch = new CountDownLatch(1);
class DeleteRuleRunnable implements Runnable {
private final int i;
private DeleteRuleRunnable(int i) {
this.i = i;
}
@Override
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
Rule rule = rules.get(i);
machine.deletePatternRule(rule.name,rule.fields);
}
}
class MatchRuleRunnable implements Runnable {
@Override
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
int i = 0;
int n;
// this thread only return when match out 100 rules 100 times.
while (i < 100) {
try {
List<String> actual = machine.rulesForJSONEvent(eString);
// the number of matched rules will keep growing from 0 till to 100
n = actual.size();
if (n == 0) {
i++;
}
} catch (Exception e) {
fail("OUCH bad event: " + eString);
}
}
}
}
ExecutorService execW = Executors.newFixedThreadPool(10);
ExecutorService execR = Executors.newFixedThreadPool(300);
for(int i = 0; i < 100; i++) {
execW.execute(new DeleteRuleRunnable(i));
}
for(int i = 0; i < 300; i++) {
execR.execute(new MatchRuleRunnable());
}
// release threads to let them work
latch.countDown();
execW.shutdown();
execR.shutdown();
try {
execW.awaitTermination(5, TimeUnit.MINUTES);
execR.awaitTermination(5, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
List<String> actual = machine.rulesForJSONEvent(eString);
assertEquals(0, actual.size());
}
@Test
public void testFunkyDelete() throws Exception {
String rule = "{ \"foo\": { \"bar\": [ 23 ] }}";
Machine cut = new Machine();
// add the rule, ensure it matches
cut.addRule("r1", rule);
String event = "{ \"foo\": {\"bar\": 23 }}";
assertEquals(1, cut.rulesForJSONEvent(event).size());
// delete the rule, no match
cut.deleteRule("r1", rule);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertTrue(cut.isEmpty());
// add it back, it matches
cut.addRule("r1", rule);
assertEquals(1, cut.rulesForJSONEvent(event).size());
// delete it but with the wrong name. Should be a no-op
cut.deleteRule("r2", rule);
assertEquals(1, cut.rulesForJSONEvent(event).size());
assertFalse(cut.isEmpty());
// delete it but with the correct name. Should be no match
cut.deleteRule("r1", rule);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertTrue(cut.isEmpty());
}
@Test
public void testFunkyDelete1() throws Exception {
String rule = "{ \"foo\": { \"bar\": [ 23, 45 ] }}";
String rule1 = "{ \"foo\": { \"bar\": [ 23 ] }}";
String rule2 = "{ \"foo\": { \"bar\": [ 45 ] }}";
String rule3 = "{ \"foo\": { \"bar\": [ 44, 45, 46 ] }}";
String rule4 = "{ \"foo\": { \"bar\": [ 44, 46, 47 ] }}";
String rule5 = "{ \"foo\": { \"bar\": [ 23, 44, 45, 46, 47 ] }}";
Machine cut = new Machine();
// add the rule, ensure it matches
cut.addRule("r1", rule);
String event = "{ \"foo\": { \"bar\":23 }}";
String event1 = "{ \"foo\": { \"bar\": 45 }}";
assertEquals(1, cut.rulesForJSONEvent(event).size());
assertEquals(1, cut.rulesForJSONEvent(event1).size());
// delete partial rule 23, partial match
cut.deleteRule("r1", rule1);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertEquals(1, cut.rulesForJSONEvent(event1).size());
// delete partial rule 45, no match
cut.deleteRule("r1", rule2);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertEquals(0, cut.rulesForJSONEvent(event1).size());
assertTrue(cut.isEmpty());
// add it back, it matches
cut.addRule("r1", rule);
assertEquals(1, cut.rulesForJSONEvent(event).size());
assertEquals(1, cut.rulesForJSONEvent(event1).size());
// delete rule3, partially delete 45, 44 and 46 are not existing will be ignored,
// so should only match 23
cut.deleteRule("r1", rule3);
assertEquals(1, cut.rulesForJSONEvent(event).size());
assertEquals(0, cut.rulesForJSONEvent(event1).size());
// delete rule then should match nothing ...
cut.deleteRule("r1", rule);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertEquals(0, cut.rulesForJSONEvent(event1).size());
assertTrue(cut.isEmpty());
// add it back, it matches
cut.addRule("r1", rule);
assertEquals(1, cut.rulesForJSONEvent(event).size());
assertEquals(1, cut.rulesForJSONEvent(event1).size());
// delete rule4, as rule4 has nothing related with other rule, machine should do nothing.
cut.deleteRule("r1", rule4);
assertEquals(1, cut.rulesForJSONEvent(event).size());
assertEquals(1, cut.rulesForJSONEvent(event1).size());
// delete all
cut.deleteRule("r1", rule5);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertEquals(0, cut.rulesForJSONEvent(event1).size());
assertTrue(cut.isEmpty());
}
@Test
public void testRangeDeletion() throws Exception {
String rule = "{\"x\": [{\"numeric\": [\">=\", 0, \"<\", 1000000000]}]}";
Machine cut = new Machine();
// add the rule, ensure it matches
cut.addRule("r1", rule);
String event = "{\"x\": 111111111.111111111}";
String event1 = "{\"x\": 1000000000}";
assertEquals(1, cut.rulesForJSONEvent(event).size());
assertEquals(0, cut.rulesForJSONEvent(event1).size());
// delete partial rule 23, partial match
cut.deleteRule("r1", rule);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertEquals(0, cut.rulesForJSONEvent(event1).size());
assertTrue(cut.isEmpty());
// test multiple key/value rule
rule = "{\n" +
"\"m\": [\"abc\"],\n" +
"\"x\": [\n" +
"{\n" +
"\"numeric\": [\">\", 0, \"<\", 30]\n" +
"},\n" +
"{\n" +
"\"numeric\": [\">\", 100, \"<\", 120]\n" +
"}\n" +
"],\n" +
"\"n\": [\"efg\"]\n" +
"}";
cut.addRule("r2", rule);
event = "{\"m\": \"abc\", \"n\": \"efg\", \"x\": 23 }";
event1 = "{\"m\": \"abc\", \"n\": \"efg\", \"x\": 110 }";
assertEquals(1, cut.rulesForJSONEvent(event).size());
assertEquals(1, cut.rulesForJSONEvent(event1).size());
cut.deleteRule("r2", rule);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertEquals(0, cut.rulesForJSONEvent(event1).size());
assertTrue(cut.isEmpty());
}
@Test
public void deleteRule() throws Exception {
String rule = "{ \"foo\": { \"bar\": [ \"ab\", \"cd\" ] }}";
Machine cut = new Machine();
// add the rule, ensure it matches
cut.addRule("r1", rule);
String event = "{ \"foo\": {\"bar\": \"ab\" }}";
String event1 = "{ \"foo\": {\"bar\": \"cd\" }}";
String event2 = "{ \"foo\": {\"bar\": [\"ab\", \"cd\" ]}}";
assertEquals(1, cut.rulesForJSONEvent(event).size());
assertEquals(1, cut.rulesForJSONEvent(event1).size());
assertEquals(1, cut.rulesForJSONEvent(event2).size());
Map<String, List<String>> namevals = new HashMap<>();
// delete partial rule 23, partial match
namevals.put("foo.bar", Collections.singletonList("\"ab\""));
cut.deleteRule("r1", namevals);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertEquals(1, cut.rulesForJSONEvent(event1).size());
assertEquals(1, cut.rulesForJSONEvent(event2).size());
namevals.put("foo.bar", Collections.singletonList("\"cd\""));
cut.deleteRule("r1", namevals);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertEquals(0, cut.rulesForJSONEvent(event1).size());
assertEquals(0, cut.rulesForJSONEvent(event2).size());
}
@Test
public void WHEN_RuleForJsonEventIsPresented_THEN_ItIsMatched() throws Exception {
final Machine rulerMachine = new Machine();
rulerMachine.addRule( "test-rule", "{ \"type\": [\"Notification\"] }" );
String event = " { \n" +
" \"signature\": \"JYFVGfee...\", \n" +
" \"signatureVersion\": 1, \n" +
" \"signingCertUrl\": \"https://sns.us-east-1.amazonaws.com/SimpleNotificationService-1234.pem\",\n" +
" \"subscribeUrl\": \"arn:aws:sns:us-east-1:108960525716:cw-to-sns-to-slack\",\n" +
" \"topicArn\": \"arn:aws:sns:us-east-1:108960525716:cw-to-sns-to-slack\",\n" +
" \"type\":\"Notification\"\n" +
" }\n";
List<String> foundRules = rulerMachine.rulesForJSONEvent(event);
assertTrue(foundRules.contains("test-rule"));
}
@Test
public void OneEventWithDuplicatedKeyButDifferentValueMatchRules() throws Exception {
Machine cut = new Machine();
String rule1 = "{ \"foo\": { \"bar\": [ \"ab\" ] }}";
String rule2 = "{ \"foo\": { \"bar\": [ \"cd\" ] }}";
// add the rule, ensure it matches
cut.addRule("r1", rule1);
cut.addRule("r2", rule2);
String event = "{ \"foo\": { \"bar\": \"ab\" }}";//{ "foo.bar", "\"ab\"" };
String event1 = "{ \"foo\": { \"bar\": \"cd\" }}";//{ "foo.bar", "\"cd\"" };
String event2 = "{ \"foo\": { \"bar\": [ \"ab\", \"cd\" ]}}";//{ "foo.bar", "\"ab\"", "foo.bar", "\"cd\"" };
assertEquals(1, cut.rulesForJSONEvent(event).size());
assertEquals(1, cut.rulesForJSONEvent(event1).size());
assertEquals(2, cut.rulesForJSONEvent(event2).size());
Map<String, List<String>> namevals = new HashMap<>();
// delete partial rule 23, partial match
namevals.put("foo.bar", Collections.singletonList("\"ab\""));
cut.deleteRule("r1", namevals);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertEquals(1, cut.rulesForJSONEvent(event1).size());
assertEquals(1, cut.rulesForJSONEvent(event2).size());
namevals.put("foo.bar", Collections.singletonList("\"cd\""));
cut.deleteRule("r2", namevals);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertEquals(0, cut.rulesForJSONEvent(event1).size());
assertEquals(0, cut.rulesForJSONEvent(event2).size());
}
@Test
public void OneRuleMadeByTwoConditions() throws Exception {
Machine cut = new Machine();
String condition1 = "{\n" +
"\"A\" : [ \"on\" ],\n" +
"\"C\" : [ \"on\" ],\n" +
"\"D\" : [ \"off\" ]\n" +
"}";
String condition2 = "{\n" +
"\"B\" : [\"on\" ],\n" +
"\"C\" : [\"on\" ],\n" +
"\"D\" : [\"off\" ]\n" +
"}";
// add the rule, ensure it matches
cut.addRule("AlarmRule1", condition1);
cut.addRule("AlarmRule1", condition2);
String event = "{\"A\": \"on\", \"C\": \"on\", \"D\": \"off\"}"; //{ "A", "\"on\"", "C", "\"on\"", "D", "\"off\"" };
String event1 = "{\"B\":\"on\", \"C\":\"on\", \"D\":\"off\"}";// { "B", "\"on\"", "C", "\"on\"", "D", "\"off\"" };
String event2 = "{\"A\":\"on\",\"B\":\"on\",\"C\":\"on\", \"D\": \"on\"}";// { "A", "\"on\"", "B", "\"on\"", "C", "\"on\"", "D", "\"on\"" };
String event3 = "{\"A\":\"on\",\"B\":\"on\",\"C\":\"on\", \"D\":\"off\"}"; //{ "A", "\"on\"", "B", "\"on\"", "C", "\"on\"", "D", "\"off\"" };
assertEquals(1, cut.rulesForJSONEvent(event).size());
assertEquals(1, cut.rulesForJSONEvent(event1).size());
assertEquals(0, cut.rulesForJSONEvent(event2).size());
assertEquals(1, cut.rulesForJSONEvent(event3).size());
cut.deleteRule("AlarmRule1", condition1);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertEquals(1, cut.rulesForJSONEvent(event1).size());
assertEquals(0, cut.rulesForJSONEvent(event2).size());
assertEquals(1, cut.rulesForJSONEvent(event3).size());
cut.deleteRule("AlarmRule1", condition2);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertEquals(0, cut.rulesForJSONEvent(event1).size());
assertEquals(0, cut.rulesForJSONEvent(event2).size());
assertEquals(0, cut.rulesForJSONEvent(event3).size());
}
@Test
public void testNumericMatch() throws Exception {
String rule = "{\n" +
"\"a\": [ { \"numeric\": [ \"=\", 0 ] } ],\n" +
"\"b\": [ { \"numeric\": [ \"<\", 0 ] } ],\n" +
"\"c\": [ { \"numeric\": [ \"<=\", 0 ] } ],\n" +
"\"x\": [ { \"numeric\": [ \">\", 0 ] } ],\n" +
"\"y\": [ { \"numeric\": [ \">=\", 0 ] } ],\n" +
"\"z\": [ { \"numeric\": [ \">\", 0, \"<\", 1 ] } ]\n" +
"}";
Machine cut = new Machine();
// add the rule, ensure it matches
cut.addRule("r1", rule);
String eventJSON = "{\n" +
"\"a\": [0],\n" +
"\"b\": [-0.1],\n" +
"\"c\": [0],\n" +
"\"x\": [1],\n" +
"\"y\": [0],\n" +
"\"z\": [0.1]\n" +
"}";
assertEquals(1, cut.rulesForJSONEvent(eventJSON).size());
// delete partial rule
cut.deleteRule("r1", rule);
assertEquals(0, cut.rulesForJSONEvent(eventJSON).size());
assertTrue(cut.isEmpty());
}
@Test
public void testAnythingButDeletion() throws Exception {
String rule = "{\n" +
"\"a\": [ { \"anything-but\": [ \"dad0\",\"dad1\",\"dad2\" ] } ],\n" +
"\"b\": [ { \"anything-but\": [ 111, 222, 333 ] } ],\n" +
"\"c\": [ { \"anything-but\": \"dad0\" } ],\n" +
"\"d\": [ { \"anything-but\": 111 } ],\n" +
"\"z\": [ { \"numeric\": [ \">\", 0, \"<\", 1 ] } ]\n" +
"}";
Machine cut = new Machine();
// add the rule, ensure it matches
cut.addRule("r1", rule);
String event = "{" +
" \"a\": \"child1\",\n" +
" \"b\": \"444\",\n" +
" \"c\": \"child1\",\n" +
" \"d\": \"444\",\n" +
" \"z\": 0.001 \n" +
"}\n";
String event1 = "{" +
" \"a\": \"dad4\",\n" +
" \"b\": 444,\n" +
" \"c\": \"child1\",\n" +
" \"d\": \"444\",\n" +
" \"z\": 0.001 \n" +
"}\n";
assertEquals(1, cut.rulesForJSONEvent(event).size());
assertEquals(1, cut.rulesForJSONEvent(event1).size());
// delete partial rule 23, partial match
cut.deleteRule("r1", rule);
assertEquals(0, cut.rulesForJSONEvent(event).size());
assertEquals(0, cut.rulesForJSONEvent(event1).size());
assertTrue(cut.isEmpty());
}
@Test
public void testAnythingButSuffix() throws Exception {
String rule = "{\n" +
"\"a\": [ { \"anything-but\": {\"suffix\": \"$\"} } ]\n" +
"}";
Machine machine = new Machine();
machine.addRule("r1", rule);
String event1 = "{" +
" \"a\": \"value$\"\n" +
"}\n";
String event2 = "{" +
" \"a\": \"notvalue\"\n" +
"}\n";
String event3 = "{" +
" \"a\": \"$notvalue\"\n" +
"}\n";
assertEquals(0, machine.rulesForJSONEvent(event1).size());
assertEquals(1, machine.rulesForJSONEvent(event2).size());
assertEquals(1, machine.rulesForJSONEvent(event3).size());
}
@Test
public void testAnythingButEqualsIgnoreCase() throws Exception {
String rule = "{\n" +
"\"a\": [ { \"anything-but\": {\"equals-ignore-case\": [\"yes\", \"please\"] } } ],\n" +
"\"b\": [ { \"anything-but\": {\"equals-ignore-case\": \"no\" } } ]\n" +
"}";
Machine machine = new Machine();
machine.addRule("r1", rule);
String event1 = "{" +
" \"a\": \"value\",\n" +
" \"b\": \"nothing\"\n" +
"}\n";
String event2 = "{" +
" \"a\": \"YES\",\n" +
" \"b\": \"nothing\"\n" +
"}\n";
String event3 = "{" +
" \"a\": \"yEs\",\n" +
" \"b\": \"nothing\"\n" +
"}\n";
String event4 = "{" +
" \"a\": \"pLease\",\n" +
" \"b\": \"nothing\"\n" +
"}\n";
String event5 = "{" +
" \"a\": \"PLEASE\",\n" +
" \"b\": \"nothing\"\n" +
"}\n";
String event6 = "{" +
" \"a\": \"please\",\n" +
" \"b\": \"nothing\"\n" +
"}\n";
String event7 = "{" +
" \"a\": \"please\",\n" +
" \"b\": \"no\"\n" +
"}\n";
String event8 = "{" +
" \"a\": \"please\",\n" +
" \"b\": \"No\"\n" +
"}\n";
String event9 = "{" +
" \"a\": \"please\",\n" +
" \"b\": \"No!\"\n" +
"}\n";
assertEquals(1, machine.rulesForJSONEvent(event1).size());
assertEquals(0, machine.rulesForJSONEvent(event2).size());
assertEquals(0, machine.rulesForJSONEvent(event3).size());
assertEquals(0, machine.rulesForJSONEvent(event4).size());
assertEquals(0, machine.rulesForJSONEvent(event5).size());
assertEquals(0, machine.rulesForJSONEvent(event6).size());
assertEquals(0, machine.rulesForJSONEvent(event7).size());
assertEquals(0, machine.rulesForJSONEvent(event8).size());
assertEquals(0, machine.rulesForJSONEvent(event9).size());
}
@Test
public void testACWithExistFalseRule() throws Exception {
// exists:false on leaf node of "interfaceName"
String rule1 = "{\n" +
" \"requestContext\": {\n" +
" \"taskInstances\": {\n" +
" \"taskInstanceState\": [\n" +
" \"ACTIVE\"\n" +
" ],\n" +
" \"provider\": {\n" +
" \"id\": [\n" +
" \"XXXXXXXXXXXX\"\n" +
" ]\n" +
" },\n" +
" \"resources\": {\n" +
" \"additionalContext\": {\n" +
" \"capabilityInterfaces\": {\n" +
" \"interfaceName\": [\n" +
" {\n" +
" \"exists\": false\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
// exists:false on leaf node of "abc"
String rule2 = "{\n" +
" \"requestContext\": {\n" +
" \"taskInstances\": {\n" +
" \"taskInstanceState\": [\n" +
" \"ACTIVE\"\n" +
" ],\n" +
" \"provider\": {\n" +
" \"id\": [\n" +
" \"XXXXXXXXXXXX\"\n" +
" ]\n" +
" },\n" +
" \"resources\": {\n" +
" \"additionalContext\": {\n" +
" \"capabilityInterfaces\": {\n" +
" \"abc\": [\n" +
" {\n" +
" \"exists\": false\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
// event1 should be able to match above 2 rules because of first element in array taskInstances
String event1 = "{\n" +
" \"requestContext\": {\n" +
" \"taskInstances\": [\n" +
" {\n" +
" \"taskInstanceId\": \"id1\",\n" +
" \"taskInstanceState\": \"ACTIVE\",\n" +
" \"provider\": {\n" +
" \"id\": \"XXXXXXXXXXXX\",\n" +
" \"type\": \"XXXXXXXX\"\n" +
" },\n" +
" \"resources\": [\n" +
" {\n" +
" \"legacyFocusCategory\": \"XXXXXFocus\",\n" +
" \"endpointIdentifier\": {\n" +
" \"type\": \"XXXIdentifier\",\n" +
" \"MaskedNumber\": \"XXXXXXXXXX\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"taskInstanceId\": \"id1\",\n" +
" \"taskInstanceState\": \"InACTIVE\",\n" +
" \"provider\": {\n" +
" \"id\": \"SomeRandom\",\n" +
" \"type\": \"XXXXXXXX\"\n" +
" },\n" +
" \"resources\": [\n" +
" {\n" +
" \"legacyFocusCategory\": \"XXXXXFocus\",\n" +
" \"endpointIdentifier\": {\n" +
" \"type\": \"XXXIdentifier\",\n" +
" \"MaskedNumber\": \"XXXXXXXXXXXX\"\n" +
" },\n" +
" \"additionalContext\": {\n" +
" \"capabilityInterfaces\": [\n" +
" {\n" +
" \"interfaceName\": \"Dummy.DummyDumDum\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
// event2 should only match the second rule because additionalContext.capabilityInterfaces.interfaceName exists.
String event2 = "{\n" +
" \"requestContext\": {\n" +
" \"taskInstances\": [\n" +
" {\n" +
" \"taskInstanceId\": \"id1\",\n" +
" \"taskInstanceState\": \"ACTIVE\",\n" +
" \"provider\": {\n" +
" \"id\": \"XXXXXXXXXXXX\",\n" +
" \"type\": \"XXXXXXXX\"\n" +
" },\n" +
" \"resources\": [\n" +
" {\n" +
" \"legacyFocusCategory\": \"XXXXXFocus\",\n" +
" \"endpointIdentifier\": {\n" +
" \"type\": \"XXXIdentifier\",\n" +
" \"MaskedNumber\": \"XXXXXXXXXX\"\n" +
" },\n" +
" \"additionalContext\": {\n" +
" \"capabilityInterfaces\": [\n" +
" {\n" +
" \"interfaceName\": \"XXXX.XXXXXXXXXXXXXX\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"taskInstanceId\": \"id1\",\n" +
" \"taskInstanceState\": \"InACTIVE\",\n" +
" \"provider\": {\n" +
" \"id\": \"SomeRandom\",\n" +
" \"type\": \"XXXXXXXX\"\n" +
" },\n" +
" \"resources\": [\n" +
" {\n" +
" \"legacyFocusCategory\": \"XXXXXFocus\",\n" +
" \"endpointIdentifier\": {\n" +
" \"type\": \"XXXIdentifier\",\n" +
" \"MaskedNumber\": \"XXXXXXXXXXXX\"\n" +
" },\n" +
" \"additionalContext\": {\n" +
" \"capabilityInterfaces\": [\n" +
" {\n" +
" \"interfaceName\": \"XXXX.XXXXXXXXXXXXXX\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
Machine cut = new Machine();
// add the rule, ensure it matches
cut.addRule("r1", rule1);
cut.addRule("r2", rule2);
assertEquals(2, cut.rulesForJSONEvent(event1).size());
List<String> matchedRules = cut.rulesForJSONEvent(event2);
assertEquals(1, matchedRules.size());
assertEquals("r2", matchedRules.get(0));
}
@Test
public void testExists() throws Exception {
String rule1 = "{\"abc\": [{\"exists\": false}]}";
String rule2 = "{\"abc\": [{\"exists\": true}]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event1 = "{\"abc\": \"xyz\"}";
String event2 = "{\"xyz\": \"abc\"}";
List<String> matches = machine.rulesForJSONEvent(event1);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule2"));
matches = machine.rulesForJSONEvent(event2);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testAddAndDeleteTwoRulesSamePattern() throws Exception {
final Machine machine = new Machine();
String event = "{\n" +
" \"x\": \"y\"\n" +
"}";
String rule1 = "{\n" +
" \"x\": [ \"y\" ]\n" +
"}";
String rule2 = "{\n" +
" \"x\": [ \"y\" ]\n" +
"}";
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
List<String> found = machine.rulesForJSONEvent(event);
assertEquals(2, found.size());
assertTrue(found.contains("rule1"));
assertTrue(found.contains("rule2"));
machine.deleteRule("rule1", rule1);
found = machine.rulesForJSONEvent(event);
assertEquals(1, found.size());
machine.deleteRule("rule2", rule2);
found = machine.rulesForJSONEvent(event);
assertEquals(0, found.size());
assertTrue(machine.isEmpty());
}
@Test
public void testAddAndDeleteTwoRulesSameCaseInsensitivePatternEqualsIgnoreCase() throws Exception {
final Machine machine = new Machine();
String event = "{\n" +
" \"x\": \"y\"\n" +
"}";
String rule1 = "{\n" +
" \"x\": [ { \"equals-ignore-case\": \"y\" } ]\n" +
"}";
String rule2 = "{\n" +
" \"x\": [ { \"equals-ignore-case\": \"Y\" } ]\n" +
"}";
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
List<String> found = machine.rulesForJSONEvent(event);
assertEquals(2, found.size());
assertTrue(found.contains("rule1"));
assertTrue(found.contains("rule2"));
machine.deleteRule("rule1", rule1);
found = machine.rulesForJSONEvent(event);
assertEquals(1, found.size());
machine.deleteRule("rule2", rule2);
found = machine.rulesForJSONEvent(event);
assertEquals(0, found.size());
assertTrue(machine.isEmpty());
}
@Test
public void testAddAndDeleteTwoRulesSameCaseInsensitivePatternPrefixEqualsIgnoreCase() throws Exception {
final Machine machine = new Machine();
String event = "{\n" +
" \"x\": \"yay\"\n" +
"}";
String rule1 = "{\n" +
" \"x\": [ { \"prefix\": { \"equals-ignore-case\": \"y\" } } ]\n" +
"}";
String rule2 = "{\n" +
" \"x\": [ { \"prefix\": { \"equals-ignore-case\": \"Y\" } } ]\n" +
"}";
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
List<String> found = machine.rulesForJSONEvent(event);
assertEquals(2, found.size());
assertTrue(found.contains("rule1"));
assertTrue(found.contains("rule2"));
machine.deleteRule("rule1", rule1);
found = machine.rulesForJSONEvent(event);
assertEquals(1, found.size());
machine.deleteRule("rule2", rule2);
found = machine.rulesForJSONEvent(event);
assertEquals(0, found.size());
assertTrue(machine.isEmpty());
}
@Test
public void testAddAndDeleteTwoRulesSameCaseInsensitivePatternSuffixEqualsIgnoreCase() throws Exception {
final Machine machine = new Machine();
String event = "{\n" +
" \"x\": \"yay\"\n" +
"}";
String rule1 = "{\n" +
" \"x\": [ { \"suffix\": { \"equals-ignore-case\": \"y\" } } ]\n" +
"}";
String rule2 = "{\n" +
" \"x\": [ { \"suffix\": { \"equals-ignore-case\": \"Y\" } } ]\n" +
"}";
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
List<String> found = machine.rulesForJSONEvent(event);
assertEquals(2, found.size());
assertTrue(found.contains("rule1"));
assertTrue(found.contains("rule2"));
machine.deleteRule("rule1", rule1);
found = machine.rulesForJSONEvent(event);
assertEquals(1, found.size());
machine.deleteRule("rule2", rule2);
found = machine.rulesForJSONEvent(event);
assertEquals(0, found.size());
assertTrue(machine.isEmpty());
}
@Test
public void testDuplicateKeyLastOneWins() throws Exception {
final Machine machine = new Machine();
String event1 = "{\n" +
" \"x\": \"y\"\n" +
"}";
String event2 = "{\n" +
" \"x\": \"z\"\n" +
"}";
String rule1 = "{\n" +
" \"x\": [ \"y\" ],\n" +
" \"x\": [ \"z\" ]\n" +
"}";
machine.addRule("rule1", rule1);
List<String> found = machine.rulesForJSONEvent(event1);
assertEquals(0, found.size());
found = machine.rulesForJSONEvent(event2);
assertEquals(1, found.size());
assertTrue(found.contains("rule1"));
}
@Test
public void testSharedNameState() throws Exception {
// "bar" will be the first key (alphabetical)
String rule1 = "{\"foo\":[\"a\"], \"bar\":[\"x\", \"y\"]}";
String rule2 = "{\"foo\":[\"a\", \"b\"], \"bar\":[\"x\"]}";
String rule3 = "{\"foo\":[\"a\", \"b\"], \"bar\":[\"y\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
machine.addRule("rule3", rule3);
String event = "{" +
"\"foo\": \"a\"," +
"\"bar\": \"x\"" +
"}";
// Ensure rule3 does not piggyback on rule1's shared NameState accessed by both "x" and "y" for "bar"
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(2, matches.size());
assertTrue(matches.contains("rule1"));
assertTrue(matches.contains("rule2"));
}
@Test
public void testRuleDeletionFromSharedNameState() throws Exception {
// "bar" will be the first key (alphabetical) and both rules have a match on "x", leading to a shared NameState
String rule1 = "{\"foo\":[\"a\"], \"bar\":[\"x\", \"y\"]}";
String rule2 = "{\"foo\":[\"b\"], \"bar\":[\"x\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event1 = "{" +
"\"foo\": \"a\"," +
"\"bar\": \"x\"" +
"}";
String event2 = "{" +
"\"foo\": \"a\"," +
"\"bar\": \"y\"" +
"}";
List<String> matches = machine.rulesForJSONEvent(event1);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
matches = machine.rulesForJSONEvent(event2);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
// Shared NameState will remain as it is used by rule1
machine.deleteRule("rule2", rule2);
matches = machine.rulesForJSONEvent(event1);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
matches = machine.rulesForJSONEvent(event2);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
// "y" also leads to the shared NameState. The shared NameState will get extended by rule2's "foo" field. By
// checking that only events with a "bar" of "y" and not a "bar" of "x", we verify that no remnants of the
// original rule2 were left in the shared NameState.
String rule2b = "{\"foo\":[\"a\"], \"bar\":[\"y\"]}";
machine.addRule("rule2", rule2b);
matches = machine.rulesForJSONEvent(event1);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
matches = machine.rulesForJSONEvent(event2);
assertEquals(2, matches.size());
assertTrue(matches.contains("rule1"));
assertTrue(matches.contains("rule2"));
}
@Test
public void testPrefixRuleDeletionFromSharedNameState() throws Exception {
// "bar", "foo", "zoo" will be the key order (alphabetical)
String rule1 = "{\"zoo\":[\"1\"], \"foo\":[\"a\"], \"bar\":[\"x\"]}";
String rule2 = "{\"foo\":[\"a\"], \"bar\":[\"x\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"zoo\": \"1\"," +
"\"foo\": \"a\"," +
"\"bar\": \"x\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(2, matches.size());
assertTrue(matches.contains("rule1"));
assertTrue(matches.contains("rule2"));
// Delete rule2, which is a subpath/prefix of rule1, and ensure full path still exists for rule1 to match
machine.deleteRule("rule2", rule2);
matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testDifferentValuesFromOrRuleBothGoThroughSharedNameState() throws Exception {
// "bar", "foo", "zoo" will be the key order (alphabetical)
String rule1 = "{\"foo\":[\"a\"], \"bar\":[\"x\", \"y\"]}";
String rule2 = "{\"zoo\":[\"1\"], \"bar\":[\"x\"]}";
String rule2b = "{\"foo\":[\"a\"], \"bar\":[\"y\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
machine.addRule("rule2", rule2b);
String event = "{" +
"\"foo\": \"a\"," +
"\"bar\": \"x\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testDifferentValuesFromExplicitOrRuleBothGoThroughSharedNameState() throws Exception {
// "bar", "foo", "zoo" will be the key order (alphabetical)
String rule1 = "{\"foo\":[\"a\"], \"bar\":[\"x\", \"y\"]}";
String rule2 = "{\"$or\":[{\"zoo\":[\"1\"], \"bar\":[\"x\"]}, {\"foo\":[\"a\"], \"bar\":[\"y\"]}]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"foo\": \"a\"," +
"\"bar\": \"x\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testRuleIsSingleItemSubsetOfOtherRule() throws Exception {
// Second rule added pertains to same field as first rule but has a subset of the allowed values.
String rule1 = "{\"foo\": [\"a\", \"b\", \"c\"]}";
String rule2 = "{\"foo\": [\"b\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"foo\": \"a\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testRuleIsMultipleItemSubsetOfOtherRule() throws Exception {
// Second rule added pertains to same field as first rule but has a subset of the allowed values.
String rule1 = "{\"foo\": [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"]}";
String rule2 = "{\"foo\": [\"b\", \"d\", \"f\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"foo\": \"e\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testRuleIsSingleItemSubsetOfOtherRuleWithPrecedingKey() throws Exception {
// Second rule added pertains to same field as first rule but has a subset of the allowed values.
String rule1 = "{\"bar\": [\"1\"], \"foo\": [\"a\", \"b\", \"c\"]}";
String rule2 = "{\"bar\": [\"1\"], \"foo\": [\"b\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"bar\": \"1\"," +
"\"foo\": \"a\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testRuleIsMultipleItemSubsetOfOtherRuleWithPrecedingKey() throws Exception {
// Second rule added pertains to same field as first rule but has a subset of the allowed values.
String rule1 = "{\"bar\": [\"1\"], \"foo\": [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"]}";
String rule2 = "{\"bar\": [\"1\"], \"foo\": [\"b\", \"d\", \"f\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"bar\": \"1\"," +
"\"foo\": \"e\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testRuleIsSingleItemSubsetOfOtherRuleWithFollowingKey() throws Exception {
// Second rule added pertains to same field as first rule but has a subset of the allowed values.
String rule1 = "{\"zoo\": [\"1\"], \"foo\": [\"a\", \"b\", \"c\"]}";
String rule2 = "{\"zoo\": [\"1\"], \"foo\": [\"b\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"zoo\": \"1\"," +
"\"foo\": \"a\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testRuleIsMultipleItemSubsetOfOtherRuleWithFollowingKey() throws Exception {
// Second rule added pertains to same field as first rule but has a subset of the allowed values.
String rule1 = "{\"zoo\": [\"1\"], \"foo\": [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"]}";
String rule2 = "{\"zoo\": [\"1\"], \"foo\": [\"b\", \"d\", \"f\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"zoo\": \"1\"," +
"\"foo\": \"e\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testExistsFalseAsFinalKeyAfterSharedNameState() throws Exception {
// Second rule added uses same NameState for bar, but then has a final key, foo, that must not exist.
String rule1 = "{\"bar\": [\"a\", \"b\"]}";
String rule2 = "{\"bar\": [\"b\"], \"foo\": [{\"exists\": false}]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"bar\": \"a\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testExistsTrueAsFinalKeyAfterSharedNameState() throws Exception {
// Second rule added uses same NameState for bar, but then has a final key, foo, that must exist.
String rule1 = "{\"bar\": [\"a\", \"b\"]}";
String rule2 = "{\"bar\": [\"b\"], \"foo\": [{\"exists\": true}]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"bar\": \"a\"," +
"\"foo\": \"1\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testExistsFalseNameStateSharedWithSpecificValueMatch() throws Exception {
// First rule adds a NameState for exists=false. Second rule will use this same NameState and add a value of "1"
// to it. Third rule will now use this same shared NameState as well due to its value of "1".
String rule1 = "{\"foo\": [\"a\"], \"bar\": [{\"exists\": false}]}";
String rule2 = "{\"foo\": [\"b\"], \"bar\": [{\"exists\": false}, \"1\"]}";
String rule3 = "{\"foo\": [\"a\"], \"bar\": [\"1\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
machine.addRule("rule3", rule3);
String event = "{" +
"\"foo\": \"a\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testExistsTrueNameStateSharedWithSpecificValueMatch() throws Exception {
// First rule adds a NameState for exists=true. Second rule will use this same NameState and add a value of "1"
// to it. Third rule will now use this same shared NameState as well due to its value of "1".
String rule1 = "{\"foo\": [\"a\"], \"bar\": [{\"exists\": true}]}";
String rule2 = "{\"foo\": [\"b\"], \"bar\": [{\"exists\": true}, \"1\"]}";
String rule3 = "{\"foo\": [\"a\"], \"bar\": [\"1\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
machine.addRule("rule3", rule3);
String event = "{" +
"\"foo\": \"a\"," +
"\"bar\": \"1\"" +
"}";
// Only rule1 and rule3 should match
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(2, matches.size());
assertTrue(matches.contains("rule1"));
assertTrue(matches.contains("rule3"));
}
@Test
public void testInitialSharedNameStateWithTwoMustNotExistsIsTerminalForOnlyOne() throws Exception {
// Initial NameState has two different (bar and foo) exists=false patterns. One is terminal, whereas the other
// leads to another NameState with another key (zoo).
String rule1 = "{\"bar\": [{\"exists\": false}]}";
String rule2 = "{\"foo\": [{\"exists\": false}], \"zoo\": [\"a\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"zoo\": \"a\"" +
"}";
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(2, matches.size());
assertTrue(matches.contains("rule1"));
assertTrue(matches.contains("rule2"));
}
@Test
public void testSharedNameStateForMultipleAnythingButPatterns() throws Exception {
// Every event will match this rule because any bar that is "a" cannot also be "b".
String rule1 = "{\"bar\": [{\"anything-but\": \"a\"}, {\"anything-but\": \"b\"}]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
String event = "{\"bar\": \"b\"}";
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testSharedNameStateWithTwoSubRulesDifferingAtFirstNameState() throws Exception {
// Two different sub-rules here with a NameState after bar and after foo: (bar=1, foo=a) and (bar=2, foo=a).
String rule1 = "{\"$or\": [{\"bar\": [\"1\"]}, {\"bar\": [\"2\"]}]," +
"\"foo\": [\"a\"] }";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
String event = "{\"bar\": \"2\"," +
"\"foo\": \"a\"}";
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testInitialSharedNameStateAlreadyExistsWithNonLeadingValue() throws Exception {
// When rule2 is added, a NameState will already exist for bar=b. Adding bar=a will lead to a new initial
// NameState, and then the existing NameState for bar=b will be encountered.
String rule1 = "{\"bar\" :[\"b\"], \"foo\": [\"c\"]}";
String rule2 = "{\"bar\": [\"a\", \"b\"], \"foo\": [\"c\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{\"bar\": \"a\"," +
"\"foo\": \"c\"}";
List<String> matches = machine.rulesForJSONEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule2"));
}
}
| 4,857 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/SubRuleContextTest.java | package software.amazon.event.ruler;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class SubRuleContextTest {
@Test
public void testGenerate() {
SubRuleContext.Generator generatorA = new SubRuleContext.Generator();
SubRuleContext contextA1 = generatorA.generate();
SubRuleContext contextA2 = generatorA.generate();
SubRuleContext.Generator generatorB = new SubRuleContext.Generator();
SubRuleContext contextB1 = generatorB.generate();
SubRuleContext contextB2 = generatorB.generate();
SubRuleContext contextB3 = generatorB.generate();
SubRuleContext contextA3 = generatorA.generate();
double expected1 = -Double.MAX_VALUE;
double expected2 = Math.nextUp(expected1);
double expected3 = Math.nextUp(expected2);
assertTrue(expected1 < expected2);
assertTrue(expected2 < expected3);
assertTrue(expected1 == contextA1.getId());
assertTrue(expected1 == contextB1.getId());
assertTrue(expected2 == contextA2.getId());
assertTrue(expected2 == contextB2.getId());
assertTrue(expected3 == contextA3.getId());
assertTrue(expected3 == contextB3.getId());
}
@Test
public void testEquals() {
SubRuleContext.Generator generatorA = new SubRuleContext.Generator();
SubRuleContext contextA1 = generatorA.generate();
SubRuleContext contextA2 = generatorA.generate();
SubRuleContext.Generator generatorB = new SubRuleContext.Generator();
SubRuleContext contextB1 = generatorB.generate();
assertTrue(contextA1.equals(contextB1));
assertFalse(contextA2.equals(contextB1));
}
@Test
public void testHashCode() {
SubRuleContext.Generator generatorA = new SubRuleContext.Generator();
SubRuleContext contextA1 = generatorA.generate();
SubRuleContext contextA2 = generatorA.generate();
SubRuleContext.Generator generatorB = new SubRuleContext.Generator();
SubRuleContext contextB1 = generatorB.generate();
assertEquals(contextA1.hashCode(), contextB1.hashCode());
assertNotEquals(contextA2.hashCode(), contextB1.hashCode());
}
} | 4,858 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/PatternsTest.java | package software.amazon.event.ruler;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class PatternsTest {
@Test
public void WHEN_MatcherIsInitialized_THEN_GettersWork() {
ValuePatterns cut = Patterns.exactMatch("foo");
assertEquals("foo", cut.pattern());
assertEquals(MatchType.EXACT, cut.type());
}
@Test
public void WHEN_Different_Patterns_Call_Pattern_Then_Work() {
List<Patterns> patternsList = new ArrayList<>();
patternsList.add(Patterns.absencePatterns());
patternsList.add(Patterns.existencePatterns());
patternsList.add(Patterns.anythingButMatch(Stream.of("a", "b").collect(Collectors.toSet())));
patternsList.add(Patterns.anythingButMatch(1.23));
patternsList.add(Patterns.exactMatch("ab"));
patternsList.add(Patterns.numericEquals(1.23));
patternsList.add(Patterns.prefixMatch("abc"));
patternsList.add(Patterns.suffixMatch("zyx"));
patternsList.add(Patterns.equalsIgnoreCaseMatch("hElLo"));
patternsList.add(Patterns.wildcardMatch("wild*card"));
patternsList.add(Range.between(1.1, true, 2.2, false));
String [] expect = {
null,
null,
null,
null,
"ab",
"11C37937F344B0",
"abc",
"xyz",
"hElLo",
"wild*card",
null
};
for(int i = 0; i < expect.length; i++) {
assertEquals(expect[i], patternsList.get(i).pattern());
}
}
} | 4,859 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/CompoundByteTransitionTest.java | package software.amazon.event.ruler;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashSet;
import static software.amazon.event.ruler.CompoundByteTransition.coalesce;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class CompoundByteTransitionTest {
@Test
public void testCoalesceEmptyList() {
assertNull(coalesce(new HashSet<>(Arrays.asList())));
}
@Test
public void testCoalesceOneElement() {
ByteState state = new ByteState();
assertEquals(state, coalesce(new HashSet<>(Arrays.asList(state))));
}
@Test
public void testCoalesceManyElements() {
ByteState state1 = new ByteState();
ByteState state2 = new ByteState();
ByteTransition result = coalesce(new HashSet<>(Arrays.asList(state1, state2)));
assertTrue(result instanceof CompoundByteTransition);
assertEquals(new HashSet<>(Arrays.asList(state1, state2)), result.expand());
}
@Test
public void testExpandDeterminatePrefixComesBeforeIndeterminatePrefix() {
ByteState state1 = new ByteState();
state1.setIndeterminatePrefix(true);
ByteState state2 = new ByteState();
state2.setIndeterminatePrefix(false);
ByteTransition result = coalesce(new HashSet<>(Arrays.asList(state1, state2)));
assertTrue(result instanceof CompoundByteTransition);
assertEquals(new HashSet<>(Arrays.asList(state2, state1)), result.expand());
}
@Test
public void testExpandCompositeNextStateDeterminatePrefixComesBeforeCompositeNextStateIndeterminatePrefix() {
ByteState state1 = new ByteState();
state1.setIndeterminatePrefix(true);
CompositeByteTransition composite1 = new CompositeByteTransition(state1, null);
ByteState state2 = new ByteState();
state2.setIndeterminatePrefix(false);
CompositeByteTransition composite2 = new CompositeByteTransition(state2, null);
ByteTransition result = coalesce(new HashSet<>(Arrays.asList(composite1, composite2)));
assertTrue(result instanceof CompoundByteTransition);
assertEquals(new HashSet<>(Arrays.asList(composite2, composite1)), result.expand());
}
@Test
public void testExpandDeterminatePrefixComesBeforeNullNextByteState() {
CompositeByteTransition composite1 = new CompositeByteTransition(null, null);
ByteState state2 = new ByteState();
state2.setIndeterminatePrefix(false);
ByteTransition result = coalesce(new HashSet<>(Arrays.asList(composite1, state2)));
assertTrue(result instanceof CompoundByteTransition);
assertEquals(new HashSet<>(Arrays.asList(state2, composite1)), result.expand());
}
@Test
public void testGetNextByteStateReturnsNullWhenNextByteStatesAreAllNull() {
CompositeByteTransition composite1 = new CompositeByteTransition(null, null);
CompositeByteTransition composite2 = new CompositeByteTransition(null, null);
ByteTransition result = coalesce(new HashSet<>(Arrays.asList(composite1, composite2)));
assertTrue(result instanceof CompoundByteTransition);
assertNull(result.getNextByteState());
}
@Test
public void testGetNextByteStateReturnsTransitionWithNonNullNextByteState() {
CompositeByteTransition composite1 = new CompositeByteTransition(null, null);
ByteState state2 = new ByteState();
state2.setIndeterminatePrefix(true);
CompositeByteTransition composite2 = new CompositeByteTransition(state2, null);
ByteTransition result = coalesce(new HashSet<>(Arrays.asList(composite1, composite2)));
assertTrue(result instanceof CompoundByteTransition);
assertEquals(state2, result.getNextByteState());
}
@Test
public void testGetNextByteStateReturnsTransitionWithNextByteStateHavingDeterminatePrefix() {
ByteState state1 = new ByteState();
state1.setIndeterminatePrefix(true);
CompositeByteTransition composite1 = new CompositeByteTransition(state1, null);
ByteState state2 = new ByteState();
state2.setIndeterminatePrefix(false);
CompositeByteTransition composite2 = new CompositeByteTransition(state2, null);
ByteTransition result = coalesce(new HashSet<>(Arrays.asList(composite1, composite2)));
assertTrue(result instanceof CompoundByteTransition);
assertEquals(state2, result.getNextByteState());
}
@Test
public void testSetNextByteState() {
ByteState state = new ByteState();
CompoundByteTransition compound = coalesce(new HashSet<>(Arrays.asList(new ByteState(), new ByteState())));
assertSame(state, compound.setNextByteState(state));
}
@Test
public void testGetMatches() {
ByteMatch match1 = new ByteMatch(Patterns.exactMatch("a"), new NameState());
ByteMatch match2 = new ByteMatch(Patterns.exactMatch("b"), new NameState());
ByteMatch match3 = new ByteMatch(Patterns.exactMatch("c"), new NameState());
ByteMatch match4 = new ByteMatch(Patterns.exactMatch("d"), new NameState());
ByteMatch match5 = new ByteMatch(Patterns.exactMatch("d"), new NameState());
// The shortcut gets match3. Expect this one to be excluded from CompoundByteTransition's getMatches.
ShortcutTransition shortcut = new ShortcutTransition();
shortcut.setMatch(match3);
// ByteState will accomplish nothing.
ByteState state = new ByteState();
// The composite gets match4.
CompositeByteTransition composite = new CompositeByteTransition(null, match4);
ByteTransition result = coalesce(new HashSet<>(Arrays.asList(
match1, match2, shortcut, state, composite, match5)));
assertTrue(result instanceof CompoundByteTransition);
assertEquals(new HashSet<>(Arrays.asList(match1, match2, match4, match5)), result.getMatches());
}
@Test
public void testGetShortcuts() {
ByteState state = new ByteState();
ShortcutTransition shortcut = new ShortcutTransition();
assertEquals(new HashSet<>(Arrays.asList(shortcut)),
coalesce(new HashSet<>(Arrays.asList(state, shortcut))).getShortcuts());
}
@Test
public void testGetTransition() {
SingleByteTransition transition1 = new ByteState();
SingleByteTransition transition2 = new ByteState();
SingleByteTransition transition3 = new ByteState();
SingleByteTransition transition4 = new ByteState();
ByteState state1 = new ByteState();
state1.addTransition((byte) 'a', transition1);
state1.addTransition((byte) 'b', transition2);
ByteState state2 = new ByteState();
state2.addTransition((byte) 'b', transition3);
state2.addTransition((byte) 'b', transition4);
ByteTransition compound = coalesce(new HashSet<>(Arrays.asList(state1, state2)));
assertTrue(compound instanceof CompoundByteTransition);
assertNull(compound.getTransition((byte) 'c'));
assertEquals(transition1, compound.getTransition((byte) 'a'));
ByteTransition result = compound.getTransition((byte) 'b');
assertTrue(result instanceof CompoundByteTransition);
assertEquals(new HashSet<>(Arrays.asList(transition2, transition3, transition4)), result.expand());
}
@Test
public void testGetTransitionForNextByteStates() {
SingleByteTransition state = new ByteState();
ByteState compositeState = new ByteState();
SingleByteTransition composite = new CompositeByteTransition(compositeState,
new ByteMatch(Patterns.exactMatch("a"), new NameState()));
assertEquals(coalesce(new HashSet<>(Arrays.asList(state, compositeState))),
coalesce(new HashSet<>(Arrays.asList(state, composite))).getTransitionForNextByteStates());
}
@Test
public void testGetTransitions() {
SingleByteTransition state1 = new ByteState();
SingleByteTransition state2 = new ByteState();
SingleByteTransition state3 = new ByteState();
SingleByteTransition state4 = new ByteState();
ByteState state5 = new ByteState();
state5.addTransition((byte) 'a', state1);
state5.addTransition((byte) 'b', state2);
ByteState state6 = new ByteState();
state6.addTransition((byte) 'a', state3);
ByteState state7 = new ByteState();
state7.addTransition((byte) 'z', state4);
assertEquals(new HashSet<>(Arrays.<ByteTransition>asList(coalesce(new HashSet<>(Arrays.asList(state1, state3))),
state2,
state4
)), coalesce(new HashSet<>(Arrays.asList(state5, state6, state7))).getTransitions());
}
@Test
public void testEquals() {
SingleByteTransition state1 = new ByteState();
SingleByteTransition state2 = new ByteState();
SingleByteTransition state3 = new ByteState();
assertTrue(coalesce(new HashSet<>(Arrays.asList(state1, state2))).equals(
coalesce(new HashSet<>(Arrays.asList(state1, state2)))
));
assertFalse(coalesce(new HashSet<>(Arrays.asList(state1, state2))).equals(
coalesce(new HashSet<>(Arrays.asList(state1, state3)))
));
assertFalse(coalesce(new HashSet<>(Arrays.asList(state1, state2))).equals(
coalesce(new HashSet<>(Arrays.asList(state1, state2, state3)))
));
assertFalse(coalesce(new HashSet<>(Arrays.asList(state1, state2))).equals(
coalesce(new HashSet<>(Arrays.asList(state1)))
));
assertFalse(coalesce(new HashSet<>(Arrays.asList(state1, state2))).equals(new Object()));
}
@Test
public void testHashCode() {
SingleByteTransition state1 = new ByteState();
SingleByteTransition state2 = new ByteState();
assertEquals(coalesce(new HashSet<>(Arrays.asList(state1, state2))).hashCode(),
coalesce(new HashSet<>(Arrays.asList(state1, state2))).hashCode()
);
assertNotEquals(coalesce(new HashSet<>(Arrays.asList(state1, state2))).hashCode(),
coalesce(new HashSet<>(Arrays.asList(state1))).hashCode()
);
}
}
| 4,860 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/SingleStateNameMatcherTest.java | package software.amazon.event.ruler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
public class SingleStateNameMatcherTest {
private SingleStateNameMatcher nameMatcher = new SingleStateNameMatcher();
private final NameState nameState = new NameState();
@Before
public void setup() {
nameMatcher.addPattern(Patterns.absencePatterns(), nameState);
}
@After
public void teardown() {
nameMatcher.deletePattern(Patterns.absencePatterns());
}
@Test
public void testInsertingSamePatternTwice_returnsThePreviouslyAddedNameState() {
NameState anotherNameState = new NameState();
NameState state = nameMatcher.addPattern(Patterns.absencePatterns(), anotherNameState);
assertThat(state, is(equalTo(nameState)));
}
@Test
public void testInsertingNewStateAfterDeletingState_acceptsNewState() {
nameMatcher.deletePattern(Patterns.absencePatterns());
NameState anotherNameState = new NameState();
NameState state = nameMatcher.addPattern(Patterns.absencePatterns(), anotherNameState);
assertThat(state, is(equalTo(anotherNameState)));
}
@Test
public void testDeletingNameStateFromEmptyMatcher_HasNoEffect() {
nameMatcher.deletePattern(Patterns.absencePatterns());
assertThat(nameMatcher.isEmpty(), is(true));
// delete same state again
nameMatcher.deletePattern(Patterns.absencePatterns());
}
@Test
public void testFindPattern() {
NameState state = nameMatcher.findPattern(Patterns.absencePatterns());
assertThat(state, is(equalTo(nameState)));
nameMatcher.deletePattern(Patterns.absencePatterns());
state = nameMatcher.findPattern(Patterns.absencePatterns());
assertThat(state, is(nullValue()));
}
} | 4,861 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/SetOperationsTest.java | package software.amazon.event.ruler;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static software.amazon.event.ruler.SetOperations.intersection;
public class SetOperationsTest {
@Test
public void testIntersection() {
Set<String> set1 = new HashSet<>(Arrays.asList("a", "b", "c"));
Set<String> set2 = new HashSet<>(Arrays.asList("b", "c", "d"));
Set<String> result = new HashSet<>();
intersection(set1, set2, result);
assertEquals(new HashSet<>(Arrays.asList("b", "c")), result);
}
@Test
public void testIntersectionDifferentResultType() {
String indexString = "abcd";
Set<String> set1 = new HashSet<>(Arrays.asList("a", "b", "c"));
Set<String> set2 = new HashSet<>(Arrays.asList("b", "c", "d"));
Set<Integer> result = new HashSet<>();
intersection(set1, set2, result, s -> indexString.indexOf(s));
assertEquals(new HashSet<>(Arrays.asList(1, 2)), result);
}
}
| 4,862 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/MachineComplexityEvaluatorTest.java | package software.amazon.event.ruler;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import static software.amazon.event.ruler.PermutationsGenerator.generateAllPermutations;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* For each test, for illustrative purposes, I will provide one input string that results in the maximum number of
* matching wildcard rule prefixes. Note there may be other input strings that achieve the same number of matching
* wildcard rule prefixes. However, there are no input strings that result in a higher number of wildcard rule prefixes
* (try to find one if you'd like).
*/
public class MachineComplexityEvaluatorTest {
private static final int MAX_COMPLEXITY = 100;
private MachineComplexityEvaluator evaluator;
@Before
public void setup() {
evaluator = new MachineComplexityEvaluator(MAX_COMPLEXITY);
}
@Test
public void testEvaluateOnlyWildcard() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("*"));
// "a" is matched by 1 wildcard prefix: "*"
assertEquals(1, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateOnlyWildcardWithExactMatch() {
// "abc" is matched by 1 wildcard prefix: "*"
testPatternPermutations(1, Patterns.wildcardMatch("*"),
Patterns.exactMatch("abc"));
}
@Test
public void testEvaluateOnlyWildcardWithWildcardMatch() {
// "abc" is matched by 3 wildcard prefixes: "*", "ab*", "ab*c"
testPatternPermutations(3, Patterns.wildcardMatch("*"),
Patterns.wildcardMatch("ab*c"));
}
@Test
public void testEvaluateWildcardPatternWithoutWildcards() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("abc"));
// "abc" is matched by 1 wildcard prefix: "abc"
assertEquals(1, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateOneWildcardLeadingCharTwoTrailingCharactersDifferent() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("*ab"));
// "ab" is matched by 2 wildcard prefixes: "*", "*ab"
assertEquals(2, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateOneWildcardLeadingCharTwoTrailingCharactersEqual() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("*aa"));
// "ab" is matched by 3 wildcard prefixes: "*", "*a", "*aa"
assertEquals(3, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateOneWildcardSecondLastChar() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("a*b"));
// "ab" is matched by 2 wildcard prefixes: "a*", "a*b"
assertEquals(2, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateOneWildcardTrailingChar() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("aa*"));
// "aa" is matched by 2 wildcard prefixes: "aa", "aa*"
assertEquals(2, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateOneWildcardNormalPositionTwoTrailingCharactersDifferent() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("a*bc"));
// "ab" is matched by 2 wildcard prefixes: "a*", "a*b"
assertEquals(2, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateOneWildcardNormalPositionTwoTrailingCharactersEqual() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("a*bb"));
// "abb" is matched by 3 wildcard prefixes: "a*", "a*b", "a*bb"
assertEquals(3, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateOneWildcardNormalPositionThreeTrailingCharactersDifferent() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("a*bcb"));
// "abcb" is matched by 3 wildcard prefixes: "a*", "a*b", "a*bcb"
assertEquals(3, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateOneWildcardNormalPositionThreeTrailingCharactersEqual() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("a*bbb"));
// "abbb" is matched by 4 wildcard prefixes: "a*", "a*b", "a*bb", "a*bbb"
assertEquals(4, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateTwoWildcardsLeadingCharAndNormalPosition() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("*ab*ad"));
// "aba" is matched by 4 wildcard prefixes: "*", "*a", "*ab*", "*ab*a"
assertEquals(4, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateTwoWildcardsLeadingCharAndSecondLastChar() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("*ab*d"));
// "abd" is matched by 3 wildcard prefixes: "*", "*ab*", "*ab*d"
assertEquals(3, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateTwoWildcardsLeadingCharAndTrailingChar() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("*aba*"));
// "aba" is matched by 4 wildcard prefixes: "*", "*a", "*aba", "*aba*"
assertEquals(4, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateTwoWildcardsBothNormalPositionTwoTrailingCharactersEqual() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("a*b*bb"));
// "abbb" is matched by 5 wildcard prefixes: "a*", "a*b", "a*b*", "a*b*b", "a*b*bb"
assertEquals(5, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateTwoWildcardsBothNormalPositionTwoTrailingCharactersDifferent() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("a*b*cb"));
// "abcb" is matched by 4 wildcard prefixes: "a*", "a*b", "a*b*", "a*b*cb"
assertEquals(4, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateTwoWildcardsBothNormalPositionTwoTrailingCharactersDifferentLastCharUnique() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("a*b*cd"));
// "abcd" is matched by 3 wildcard prefixes: "a*", "a*b*", "a*b*cd"
assertEquals(3, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateTwoWildcardsNormalPositionAndSecondLastChar() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("a*b*b"));
// "abb" is matched by 4 wildcard prefixes: "a*", "a*b", "a*b*", "a*b*b"
assertEquals(4, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateTwoWildcardsNormalPositionAndTrailingChar() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("a*bb*"));
// "abb" is matched by 4 wildcard prefixes: "a*", "a*b", "a*bb", "a*bb*"
assertEquals(4, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateTwoWildcardsThirdLastCharAndTrailingChar() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("ab*b*"));
// "abb" is matched by 3 wildcard prefixes: "ab*", "ab*b", "ab*b*"
assertEquals(3, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateTwoWildcardsNoCommonPrefix() {
// "xxx" is matched by 3 wildcard prefixes: "x*", "x*x", "x*xx"
testPatternPermutations(3, Patterns.wildcardMatch("ab*c"),
Patterns.wildcardMatch("x*xx"));
}
@Test
public void testEvaluateTwoWildcardsBothLeadingOneIsPrefixOfOther() {
// "abc" is matched by 4 wildcard prefixes: "*", "*abc", "*", "*abc"
testPatternPermutations(4, Patterns.wildcardMatch("*abc"),
Patterns.wildcardMatch("*abcde"));
}
@Test
public void testEvaluateTwoWildcardsBothNormalPosition() {
// "abcd" is matched by 4 wildcard prefixes: "a*", "a*bcd", "ab*", "ab*cd"
testPatternPermutations(4, Patterns.wildcardMatch("a*bcd"),
Patterns.wildcardMatch("ab*cd"));
}
@Test
public void testEvaluateTwoWildcardsBothNormalPositionOneIsPrefixOfOther() {
// "ab" is matched by 4 wildcard prefixes: "a*", "a*b", "a*", "a*b"
testPatternPermutations(4, Patterns.wildcardMatch("a*bc"),
Patterns.wildcardMatch("a*bcde"));
}
@Test
public void testEvaluateTwoWildcardsBothNormalPositionAllSameCharacter() {
// "aaaa" is matched by 7 wildcard prefixes: "a*", "a*a", "a*aa", "a*aaa", "aa*", "aa*a", "aa*aa"
testPatternPermutations(7, Patterns.wildcardMatch("a*aaa"),
Patterns.wildcardMatch("aa*aa"));
}
@Test
public void testEvaluateTwoWildcardsOneNormalPositionAndOneSecondLastCharacter() {
// "abc" is matched by 4 wildcard prefixes: "a*", "a*bc", "abc", "abc*"
testPatternPermutations(4, Patterns.wildcardMatch("a*bc"),
Patterns.wildcardMatch("abc*d"));
}
@Test
public void testEvaluateTwoWildcardsOneNormalPositionAndOneSecondLastCharacterAllSameCharacter() {
// "aaaa" is matched by 6 wildcard prefixes: "a*", "a*a", "a*aa", "a*aaa", "aaa*", "aaa*a"
testPatternPermutations(6, Patterns.wildcardMatch("a*aaa"),
Patterns.wildcardMatch("aaa*a"));
}
@Test
public void testEvaluateTwoWildcardsOneNormalPositionAndOneSecondLastCharacterAllSameCharacterButLast() {
// "aaa" is matched by 5 wildcard prefixes: "a*", "a*a", "a*aa", "aaa", "aaa*"
testPatternPermutations(5, Patterns.wildcardMatch("a*aax"),
Patterns.wildcardMatch("aaa*x"));
}
@Test
public void testEvaluateTwoWildcardsOneNormalPositionAndOneTrailing() {
// "abc" is matched by 4 wildcard prefixes: "a*", "a*bc", "abc", "abc*"
testPatternPermutations(4, Patterns.wildcardMatch("a*bc"),
Patterns.wildcardMatch("abc*"));
}
@Test
public void testEvaluateTwoWildcardsOneNormalPositionAndOneTrailingAllSameCharacter() {
// "aaa" is matched by 5 wildcard prefixes: "a*", "a*a", "a*aa", "aaa", "aaa*"
testPatternPermutations(5, Patterns.wildcardMatch("a*aa"),
Patterns.wildcardMatch("aaa*"));
}
@Test
public void testEvaluateTwoWildcardsBothTrailingCharOneIsPrefixOfOther() {
// "abc" is matched by 3 wildcard prefixes: "abc", "abc*", "abc"
testPatternPermutations(3, Patterns.wildcardMatch("abc*"),
Patterns.wildcardMatch("abcde*"));
}
@Test
public void testEvaluateThreeWildcardsTransitionFromSameState() {
// "ab" is matched by 6 wildcard prefixes: "ab", "ab*", "ab", "ab*", "ab", "ab*"
testPatternPermutations(6, Patterns.wildcardMatch("ab*cd"),
Patterns.wildcardMatch("ab*wx"),
Patterns.wildcardMatch("ab*yz"));
}
@Test
public void testEvaluateFourWildcardsLeadingCharNormalPositionThirdLastCharAndTrailingChar() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("*ab*b*b*"));
// "abbbab" is matched by 7 wildcard prefixes: "*", "*ab", "*ab*", "*ab*b", "*ab*b*", "*ab*b*b", "*ab*b*b*"
assertEquals(7, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateLongSequenceofWildcards() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("*a*a*a*a*a*a*a*a*"));
// "aaaaaaaa" is matched by all 17 wildcard prefixes
assertEquals(17, machine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateOneWildcardLeadingCharWithExactMatch() {
// "abc" is matched by 2 wildcard prefixes: "*", "*abc"
testPatternPermutations(2, Patterns.wildcardMatch("*abc"),
Patterns.exactMatch("abc"));
}
@Test
public void testEvaluateOneWildcardNormalPositionWithExactMatch() {
// "abc" is matched by 2 wildcard prefixes: "a*", "a*bc"
testPatternPermutations(2, Patterns.wildcardMatch("a*bc"),
Patterns.exactMatch("abc"));
}
@Test
public void testEvaluateOneWildcardSecondLastCharWithExactMatch() {
// "abc" is matched by 2 wildcard prefixes: "ab*", "ab*c"
testPatternPermutations(2, Patterns.wildcardMatch("ab*c"),
Patterns.exactMatch("abc"));
}
@Test
public void testEvaluateOneWildcardTrailingCharWithExactMatch() {
// "abc" is matched by 2 wildcard prefixes: "abc", "abc*"
testPatternPermutations(2, Patterns.wildcardMatch("abc*"),
Patterns.exactMatch("abc"));
}
@Test
public void testEvaluateOneWildcardTrailingCharWithLongerExactMatch() {
// "abc" is matched by 2 wildcard prefixes: "abc", "abc*"
testPatternPermutations(2, Patterns.wildcardMatch("abc*"),
Patterns.exactMatch("abcde"));
}
@Test
public void testEvaluateOneWildcardTrailingCharWithLongerExactMatchPrefixMatchAndEqualsIgnoreCaseMatch() {
// "abc" is matched by 2 wildcard prefixes: "abc", "abc*"
testPatternPermutations(2, Patterns.wildcardMatch("abc*"),
Patterns.exactMatch("abcde"),
Patterns.prefixMatch("abcde"),
Patterns.equalsIgnoreCaseMatch("ABCDE"));
}
@Test
public void testEvaluateOneWildcardTrailingCharWithVaryingLengthExactMatchPrefixMatchAndEqualsIgnoreCaseMatch() {
// "abc" is matched by 2 wildcard prefixes: "abc", "abc*"
testPatternPermutations(2, Patterns.wildcardMatch("abc*"),
Patterns.exactMatch("abcde"),
Patterns.prefixMatch("abcdef"),
Patterns.equalsIgnoreCaseMatch("ABCDEFG"));
}
@Test
public void testEvaluateExistencePatternHasNoEffect() {
// "ab" is matched by 2 wildcard prefixes: "ab", "ab*"
testPatternPermutations(2, Patterns.wildcardMatch("ab*c"),
Patterns.exactMatch("abc"),
Patterns.existencePatterns());
}
@Test
public void testEvaluateJustExactMatches() {
testPatternPermutations(0, Patterns.exactMatch("abc"),
Patterns.exactMatch("abcde"));
}
@Test
public void testEvaluateDuplicateWildcardPatterns() {
// "abc" is matched by 2 wildcard prefixes: "ab*", "ab*c" (duplicate patterns do not duplicate prefix count)
testPatternPermutations(2, Patterns.wildcardMatch("ab*c"),
Patterns.wildcardMatch("ab*c"));
}
@Test
public void testEvaluateWordEndingInSameLetterThatFollowsWildcard() {
// "FeatureFeature" is matched by 10 wildcard prefixes: "F*", "F*e", "F*eature", "F*eatureFeature", "Fe*",
// "Fe*ature", "Fe*atureFeature", "Fea*", "Fea*ture",
// "Fea*tureFeature"
testPatternPermutations(10, Patterns.wildcardMatch("F*eatureFeature"),
Patterns.wildcardMatch("Fe*atureFeature"),
Patterns.wildcardMatch("Fea*tureFeature"));
}
@Test
public void testEvaluateNestedMachinesViaNextNameStates() throws Exception {
Machine machine = new Machine();
machine.addRule("name", "{" +
"\"abc\": [ { \"prefix\": \"a\" }, \"abcdef\", { \"suffix\": \"z\" } ]," +
"\"def\": [ { \"prefix\": \"b\" }, { \"wildcard\": \"a*a*a*a*a*a*\" }, { \"suffix\": \"c\" } ]," +
"\"ghi\": [ { \"prefix\": \"a\" }, \"abcdef\", { \"suffix\": \"z\" } ]" +
"}");
assertEquals(11, machine.evaluateComplexity(evaluator));
}
/**
* I'm not going to try to determine the maximum complexity input string. This is here just to demonstrate that this
* set of rules, which has proven problematic for Quamina in the past, is handled ok by Ruler.
*/
@Test
public void testEvaluateQuaminaExploder() {
ByteMachine machine = new ByteMachine();
machine.addPattern(Patterns.wildcardMatch("aahed*"));
machine.addPattern(Patterns.wildcardMatch("aal*ii"));
machine.addPattern(Patterns.wildcardMatch("aargh*"));
machine.addPattern(Patterns.wildcardMatch("aarti*"));
machine.addPattern(Patterns.wildcardMatch("a*baca"));
machine.addPattern(Patterns.wildcardMatch("*abaci"));
machine.addPattern(Patterns.wildcardMatch("a*back"));
machine.addPattern(Patterns.wildcardMatch("ab*acs"));
machine.addPattern(Patterns.wildcardMatch("abaf*t"));
machine.addPattern(Patterns.wildcardMatch("*abaka"));
machine.addPattern(Patterns.wildcardMatch("ab*amp"));
machine.addPattern(Patterns.wildcardMatch("a*band"));
machine.addPattern(Patterns.wildcardMatch("*abase"));
machine.addPattern(Patterns.wildcardMatch("abash*"));
machine.addPattern(Patterns.wildcardMatch("abas*k"));
machine.addPattern(Patterns.wildcardMatch("ab*ate"));
machine.addPattern(Patterns.wildcardMatch("aba*ya"));
machine.addPattern(Patterns.wildcardMatch("abbas*"));
machine.addPattern(Patterns.wildcardMatch("abbed*"));
machine.addPattern(Patterns.wildcardMatch("ab*bes"));
machine.addPattern(Patterns.wildcardMatch("abbey*"));
machine.addPattern(Patterns.wildcardMatch("*abbot"));
machine.addPattern(Patterns.wildcardMatch("ab*cee"));
machine.addPattern(Patterns.wildcardMatch("abea*m"));
machine.addPattern(Patterns.wildcardMatch("abe*ar"));
machine.addPattern(Patterns.wildcardMatch("a*bele"));
machine.addPattern(Patterns.wildcardMatch("a*bers"));
machine.addPattern(Patterns.wildcardMatch("abet*s"));
machine.addPattern(Patterns.wildcardMatch("*abhor"));
machine.addPattern(Patterns.wildcardMatch("abi*de"));
machine.addPattern(Patterns.wildcardMatch("a*bies"));
machine.addPattern(Patterns.wildcardMatch("*abled"));
assertEquals(45, machine.evaluateComplexity(evaluator));
}
/**
* This test verifies that complexity evaluation caps out at 100. This test also indirectly verifies, by having
* reasonable runtime, that a full traversal for the worst-case input is not performed. Otherwise, we'd be looking
* at runtime of O(n^2) where n=140,000.
*/
@Test
public void testEvaluateBeyondMaxComplexity() throws InterruptedException {
Timer timer = new Timer();
ByteMachine machine = new ByteMachine();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 10000; i++) {
builder.append("F*e*a*t*u*r*e*");
}
machine.addPattern(Patterns.wildcardMatch(builder.toString()));
// Start a complexity evaluation task.
final int[] complexity = { -1 };
TimerTask evaluationTask = new TimerTask() {
@Override
public void run() {
complexity[0] = machine.evaluateComplexity(evaluator);
}
};
timer.schedule(evaluationTask, 0);
// Start a timeout task that will fail the test if complexity evaluation takes over 60 seconds.
final boolean[] timedOut = { false };
TimerTask timeoutTask = new TimerTask() {
@Override
public void run() {
timedOut[0] = true;
}
};
timer.schedule(timeoutTask, 60000);
// Wait either for complexity evaluation to finish or for timeout to occur.
while (complexity[0] == -1 && !timedOut[0]) {
Thread.sleep(10);
}
if (timedOut[0]) {
fail("Complexity evaluation took over 60 seconds");
}
assertEquals(MAX_COMPLEXITY, complexity[0]);
// Cancel the timeoutTask in case it hasn't run yet.
timeoutTask.cancel();
}
private void testPatternPermutations(int expectedComplexity, Patterns ... patterns) {
ByteMachine machine = new ByteMachine();
List<Patterns[]> patternPermutations = generateAllPermutations(patterns);
for (Patterns[] patternPermutation : patternPermutations) {
for (Patterns pattern : patternPermutation) {
machine.addPattern(pattern);
}
assertEquals(expectedComplexity, machine.evaluateComplexity(evaluator));
for (Patterns pattern : patternPermutation) {
machine.deletePattern(pattern);
}
assertTrue(machine.isEmpty());
}
}
}
| 4,863 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/NameStateWithPatternTest.java | package software.amazon.event.ruler;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class NameStateWithPatternTest {
@Test
public void testNullNameState() {
try {
new NameStateWithPattern(null, Patterns.existencePatterns());
fail("Expected NullPointerException");
} catch (NullPointerException e) { }
}
@Test
public void testNullPattern() {
// null pattern is allowed due to the case that the NameState is the starting state of a Machine.
new NameStateWithPattern(new NameState(), null);
}
@Test
public void testGetters() {
NameState nameState = new NameState();
Patterns pattern = Patterns.exactMatch("abc");
NameStateWithPattern nameStateWithPattern = new NameStateWithPattern(nameState, pattern);
assertSame(nameState, nameStateWithPattern.getNameState());
assertSame(pattern, nameStateWithPattern.getPattern());
}
@Test
public void testEquals() {
NameState nameState1 = new NameState();
NameState nameState2 = new NameState();
Patterns pattern1 = Patterns.exactMatch("abc");
Patterns pattern2 = Patterns.exactMatch("def");
assertTrue(new NameStateWithPattern(nameState1, pattern1).equals(
new NameStateWithPattern(nameState1, pattern1)));
assertFalse(new NameStateWithPattern(nameState1, pattern1).equals(
new NameStateWithPattern(nameState2, pattern1)));
assertFalse(new NameStateWithPattern(nameState1, pattern1).equals(
new NameStateWithPattern(nameState1, pattern2)));
}
@Test
public void testHashCode() {
NameState nameState1 = new NameState();
NameState nameState2 = new NameState();
Patterns pattern1 = Patterns.exactMatch("abc");
Patterns pattern2 = Patterns.exactMatch("def");
assertEquals(new NameStateWithPattern(nameState1, pattern1).hashCode(),
new NameStateWithPattern(nameState1, pattern1).hashCode());
assertNotEquals(new NameStateWithPattern(nameState1, pattern1).hashCode(),
new NameStateWithPattern(nameState2, pattern1).hashCode());
assertNotEquals(new NameStateWithPattern(nameState1, pattern1).hashCode(),
new NameStateWithPattern(nameState1, pattern2).hashCode());
}
} | 4,864 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/ByteMatchTest.java | package software.amazon.event.ruler;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
public class ByteMatchTest {
private ByteMatch match;
@Before
public void setUp() {
match = new ByteMatch(Patterns.exactMatch("abc"), new NameState());
}
@Test
public void getNextByteStateShouldReturnNull() {
SingleByteTransition nextState = match.getNextByteState();
assertNull(nextState);
}
@Test
public void setNextByteStateShouldReturnThisMatchWhenGivenNextStateIsNull() {
ByteTransition transition = match.setNextByteState(null);
assertSame(match, transition);
}
@Test
public void setNextByteStateShouldReturnNewCompositeTransitionWhenGivenNextStateIsNotNull() {
ByteState nextState = new ByteState();
ByteTransition transition = match.setNextByteState(nextState);
assertTrue(transition instanceof CompositeByteTransition);
assertSame(nextState, transition.getNextByteState());
assertEquals(match, transition.getMatches());
}
@Test
public void getMatchShouldReturnThisMatch() {
ByteMatch actualMatch = match.getMatch();
assertEquals(match, actualMatch);
}
@Test
public void getMatchesShouldReturnThisMatch() {
assertEquals(match, match.getMatches());
}
@Test
public void setMatchShouldReturnNullWhenGivenMatchIsNull() {
assertNull(match.setMatch(null));
}
@Test
public void setMatchShouldReturnGivenMatchWhenGivenMatchIsNotNull() {
ByteMatch newMatch = new ByteMatch(Patterns.exactMatch("xyz"), new NameState());
ByteTransition transition = match.setMatch(newMatch);
assertSame(newMatch, transition);
}
@Test
public void expandShouldReturnMatch() {
assertEquals(match, match.expand());
}
@Test
public void hasIndeterminatePrefixShouldReturnFalse() {
assertFalse(match.hasIndeterminatePrefix());
}
@Test
public void getTransitionShouldReturnNull() {
assertNull(match.getTransition((byte) 'a'));
}
@Test
public void getTransitionForAllBytesShouldReturnNull() {
assertNull(match.getTransitionForAllBytes());
}
@Test
public void getTransitionsShouldReturnEmptySet() {
assertEquals(Collections.emptySet(), match.getTransitions());
}
@Test
public void getShortcutsShouldReturnEmptySet() {
assertEquals(Collections.emptySet(), match.getShortcuts());
}
@Test
public void isMatchTransShouldReturnTrue() {
assertTrue(match.isMatchTrans());
}
@Test
public void WHEN_MatchIsInitialized_THEN_GettersWork() {
NameState ns = new NameState();
ByteMatch cut = new ByteMatch(Patterns.anythingButMatch("foo"), ns);
assertEquals(ns, cut.getNextNameState());
assertEquals(Patterns.anythingButMatch("foo"), cut.getPattern());
}
} | 4,865 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/CompositeByteTransitionTest.java | package software.amazon.event.ruler;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class CompositeByteTransitionTest {
private ByteState nextState;
private ByteMatch match;
private CompositeByteTransition compositeTransition;
@Before
public void setUp() {
nextState = new ByteState();
match = new ByteMatch(Patterns.exactMatch("abc"), new NameState());
compositeTransition = new CompositeByteTransition(nextState, match);
}
@Test
public void getNextByteStateShouldReturnSetNextState() {
assertSame(nextState, compositeTransition.getNextByteState());
}
@Test
public void setNextByteStateShouldReturnSetMatchWhenGivenNextStateIsNull() {
ByteTransition transition = compositeTransition.setNextByteState(null);
assertSame(match, transition);
}
@Test
public void setNextByteStateShouldReturnThisCompositeTransitionWhenGivenNextStateIsNotNull() {
compositeTransition = new CompositeByteTransition(null, match);
ByteState nextState = new ByteState();
ByteTransition transition = compositeTransition.setNextByteState(nextState);
assertSame(compositeTransition, transition);
assertSame(nextState, transition.getNextByteState());
}
@Test
public void getMatchShouldReturnSetMatch() {
assertSame(match, compositeTransition.getMatch());
}
@Test
public void getMatchesShouldReturnMatch() {
assertEquals(match, compositeTransition.getMatches());
}
@Test
public void setMatchShouldReturnSetNextStateWhenGivenMatchIsNull() {
ByteTransition transition = compositeTransition.setMatch(null);
assertSame(nextState, transition);
}
@Test
public void setMatchShouldReturnThisCompositeTransitionWhenGivenMatchIsNotNull() {
ByteMatch match = new ByteMatch(Patterns.exactMatch("xyz"), new NameState());
SingleByteTransition transition = compositeTransition.setMatch(match);
assertSame(compositeTransition, transition);
assertSame(match, transition.getMatch());
}
@Test
public void getTransitionForAllBytesShouldReturnNull() {
assertNull(compositeTransition.getTransitionForAllBytes());
}
@Test
public void getTransitionsShouldReturnEmptySet() {
assertEquals(Collections.emptySet(), compositeTransition.getTransitions());
}
@Test
public void getShortcutsShouldReturnEmptySet() {
assertEquals(Collections.emptySet(), compositeTransition.getShortcuts());
}
@Test
public void isMatchTransShouldReturnTrue() {
assertTrue(compositeTransition.isMatchTrans());
}
@Test
public void expandShouldReturnComposite() {
assertEquals(compositeTransition, compositeTransition.expand());
}
@Test
public void hasIndeterminatePrefixShouldReturnResultFromNextState() {
nextState.setIndeterminatePrefix(false);
assertFalse(compositeTransition.hasIndeterminatePrefix());
nextState.setIndeterminatePrefix(true);
assertTrue(compositeTransition.hasIndeterminatePrefix());
nextState.setIndeterminatePrefix(false);
assertFalse(compositeTransition.hasIndeterminatePrefix());
}
@Test
public void hasIndeterminatePrefixShouldReturnFalseIfNoNextState() {
compositeTransition = new CompositeByteTransition(null, match);
assertFalse(compositeTransition.hasIndeterminatePrefix());
}
}
| 4,866 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/ArrayMembershipTest.java | package software.amazon.event.ruler;
import org.junit.Test;
import static org.junit.Assert.*;
public class ArrayMembershipTest {
@Test
public void WHenARoleIsPutThenItIsRetrieved() {
ArrayMembership cut = new ArrayMembership();
int[] indices = { 3, 8, 800000, 77};
for (int index : indices) {
assertEquals(-1, cut.getMembership(index));
}
for (int index : indices) {
cut.putMembership(index, index + 27);
assertEquals(index + 27, cut.getMembership(index));
assertEquals(-1, cut.getMembership(index + 1));
assertFalse(cut.isEmpty());
}
}
private void checkWanted(int[][] wanted, ArrayMembership membership) {
for (int[] pair : wanted) {
assertEquals(String.format("%d/%d", pair[0], pair[1]), pair[1], membership.getMembership(pair[0]));
membership.deleteMembership(pair[0]);
}
assertTrue("Extra memberships", membership.isEmpty());
}
private ArrayMembership fromPairs(int[][] pairs) {
ArrayMembership am = new ArrayMembership();
for (int[] pair : pairs) {
am.putMembership(pair[0], pair[1]);
}
return am;
}
@Test
public void WHEN_MembershipsAreCompared_THEN_TheyAreMergedProperly() {
ArrayMembership empty = new ArrayMembership();
int[][] sofar = {
{0, 0},
{2, 1},
{4, 2},
{6, 8}
};
int[][] fieldWithNoConflict = {
{3, 33}
};
int[][] fieldConflictingWithPreviousField = {
{3, 44}
};
int[][] wanted1 = {
{0, 0},
{2, 1},
{3, 33},
{4, 2},
{6, 8}
};
int[][] fieldWithConflict = {
{2, 2}
};
ArrayMembership result;
result = ArrayMembership.checkArrayConsistency(empty, fromPairs(fieldWithNoConflict));
checkWanted(fieldWithNoConflict, result);
result = ArrayMembership.checkArrayConsistency(fromPairs(sofar), empty);
checkWanted(sofar, result);
result = ArrayMembership.checkArrayConsistency(fromPairs(sofar), fromPairs(fieldWithNoConflict));
checkWanted(wanted1, result);
result = ArrayMembership.checkArrayConsistency(fromPairs(fieldWithNoConflict), fromPairs(sofar));
checkWanted(wanted1, result);
result = ArrayMembership.checkArrayConsistency(fromPairs(sofar), fromPairs(fieldWithConflict));
assertNull(result);
result = ArrayMembership.checkArrayConsistency(fromPairs(fieldWithConflict), fromPairs(sofar));
assertNull(result);
result = ArrayMembership.checkArrayConsistency(fromPairs(sofar), fromPairs(sofar));
checkWanted(sofar, result);
result = ArrayMembership.checkArrayConsistency(fromPairs(sofar), fromPairs(fieldWithNoConflict));
assert result != null;
result = ArrayMembership.checkArrayConsistency(result, fromPairs(fieldConflictingWithPreviousField));
assertNull(result);
}
} | 4,867 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/MachineTest.java | package software.amazon.event.ruler;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit testing a state machine is hard. Tried hand-computing a few machines
* but kept getting them wrong, the software was right. So this is really
* more of a smoke/integration test. But the coverage is quite good.
*/
public class MachineTest {
private String toIP(int ip) {
StringBuilder sb = new StringBuilder();
sb.append((ip >> 24) & 0xFF).append('.');
sb.append((ip >> 16) & 0xFF).append('.');
sb.append((ip >> 8) & 0xFF).append('.');
sb.append(ip & 0xFF);
return sb.toString();
}
@Test
public void CIDRTest() throws Exception {
String template = "{" +
" \"a\": \"IP\"" +
"}";
long base = 0x0A000000;
// tested by hand with much smaller starts but the runtime gets looooooooong
for (int i = 22; i < 32; i++) {
String rule = "{ " +
" \"a\": [ {\"cidr\": \"10.0.0.0/" + i + "\"} ]" +
"}";
Machine m = new Machine();
m.addRule("r", rule);
long numberThatShouldMatch = 1L << (32 - i);
// don't want to run through all of them for low values of maskbits
long windowEnd = base + numberThatShouldMatch + 16;
int matches = 0;
for (long j = base - 16; j < windowEnd; j++) {
String event = template.replace("IP", toIP((int) j));
if (m.rulesForEvent(event).size() == 1) {
matches++;
}
}
assertEquals(numberThatShouldMatch, matches);
}
}
@Test
public void testIPAddressOfCIDRIsEqualToMaximumOfRange() throws Exception {
String rule1 = "{\"sourceIPAddress\": [{\"cidr\": \"220.160.153.171/31\"}]}";
String rule2 = "{\"sourceIPAddress\": [{\"cidr\": \"220.160.154.255/24\"}]}";
String rule3 = "{\"sourceIPAddress\": [{\"cidr\": \"220.160.59.225/31\"}]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
machine.addRule("rule3", rule3);
List<String> matches = machine.rulesForEvent("{\"sourceIPAddress\": \"220.160.153.170\"}");
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
matches = machine.rulesForEvent("{\"sourceIPAddress\": \"220.160.153.171\"}");
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
matches = machine.rulesForEvent("{\"sourceIPAddress\": \"220.160.153.169\"}");
assertTrue(matches.isEmpty());
matches = machine.rulesForEvent("{\"sourceIPAddress\": \"220.160.153.172\"}");
assertTrue(matches.isEmpty());
matches = machine.rulesForEvent("{\"sourceIPAddress\": \"220.160.154.0\"}");
assertEquals(1, matches.size());
assertTrue(matches.contains("rule2"));
matches = machine.rulesForEvent("{\"sourceIPAddress\": \"220.160.154.255\"}");
assertEquals(1, matches.size());
assertTrue(matches.contains("rule2"));
matches = machine.rulesForEvent("{\"sourceIPAddress\": \"220.160.153.255\"}");
assertTrue(matches.isEmpty());
matches = machine.rulesForEvent("{\"sourceIPAddress\": \"220.160.155.0\"}");
assertTrue(matches.isEmpty());
matches = machine.rulesForEvent("{\"sourceIPAddress\": \"220.160.59.224\"}");
assertEquals(1, matches.size());
assertTrue(matches.contains("rule3"));
matches = machine.rulesForEvent("{\"sourceIPAddress\": \"220.160.59.225\"}");
assertEquals(1, matches.size());
assertTrue(matches.contains("rule3"));
matches = machine.rulesForEvent("{\"sourceIPAddress\": \"220.160.59.223\"}");
assertTrue(matches.isEmpty());
matches = machine.rulesForEvent("{\"sourceIPAddress\": \"220.160.59.226\"}");
assertTrue(matches.isEmpty());
}
@Test
public void testSimplestPossibleMachine() throws Exception {
String rule1 = "{ \"a\" : [ 1 ] }";
String rule2 = "{ \"b\" : [ 2 ] }";
Machine machine = new Machine();
machine.addRule("r1", rule1);
machine.addRule("r2", rule2);
String[] event1 = { "a", "1" };
String[] event2 = { "b", "2" };
String[] event3 = { "x", "true" };
List<String> val;
val = machine.rulesForEvent(event1);
assertEquals(1, val.size());
assertEquals("r1", val.get(0));
val = machine.rulesForEvent(event2);
assertEquals(1, val.size());
assertEquals("r2", val.get(0));
val = machine.rulesForEvent(event3);
assertEquals(0, val.size());
}
@Test
public void testPrefixMatching() throws Exception {
String rule1 = "{ \"a\" : [ { \"prefix\": \"zoo\" } ] }";
String rule2 = "{ \"b\" : [ { \"prefix\": \"child\" } ] }";
Machine machine = new Machine();
machine.addRule("r1", rule1);
machine.addRule("r2", rule2);
String[][] events = {
{"a", "\"zookeeper\""},
{"a", "\"zoo\""},
{"b", "\"childlike\""},
{"b", "\"childish\""},
{"b", "\"childhood\""}
};
for (String[] event : events) {
List<String> rules = machine.rulesForEvent(event);
assertEquals(1, rules.size());
if ("a".equals(event[0])) {
assertEquals("r1", rules.get(0));
} else {
assertEquals("r2", rules.get(0));
}
}
machine = new Machine();
String rule3 = "{ \"a\" : [ { \"prefix\": \"al\" } ] }";
String rule4 = "{ \"a\" : [ \"albert\" ] }";
machine.addRule("r3", rule3);
machine.addRule("r4", rule4);
String[] e2 = { "a", "\"albert\""};
List<String> rules = machine.rulesForEvent(e2);
assertEquals(2, rules.size());
}
@Test
public void testSuffixMatching() throws Exception {
String rule1 = "{ \"a\" : [ { \"suffix\": \"er\" } ] }";
String rule2 = "{ \"b\" : [ { \"suffix\": \"txt\" } ] }";
Machine machine = new Machine();
machine.addRule("r1", rule1);
machine.addRule("r2", rule2);
String[] events = {
"{\"a\" : \"zookeeper\"}",
"{\"b\" : \"amazon.txt\"}",
"{\"a\" : \"checker\"}",
"{\"b\" : \"Texttxt\"}",
"{\"a\" : \"er\"}",
"{\"b\" : \"txt\"}"
};
int i = 0;
for (String event : events) {
List<String> rules = machine.rulesForJSONEvent(event);
assertEquals(1, rules.size());
if (i++ % 2 == 0) {
assertEquals("r1", rules.get(0));
} else {
assertEquals("r2", rules.get(0));
}
}
machine.deleteRule("r2", rule2);
i = 0;
for (String event : events) {
List<String> rules = machine.rulesForJSONEvent(event);
if (i++ % 2 == 0) {
assertEquals(1, rules.size());
} else {
assertEquals(0, rules.size());
}
}
machine.deleteRule("r1", rule1);
assertTrue(machine.isEmpty());
}
@Test
public void testEqualsIgnoreCaseMatching() throws Exception {
Machine machine = new Machine();
String rule1 = "{ \"a\" : [ { \"equals-ignore-case\": \"aBc\" } ] }";
String rule2 = "{ \"b\" : [ { \"equals-ignore-case\": \"XyZ\" } ] }";
String rule3 = "{ \"b\" : [ { \"equals-ignore-case\": \"xyZ\" } ] }";
machine.addRule("r1", rule1);
machine.addRule("r2", rule2);
machine.addRule("r3", rule3);
assertEquals(Arrays.asList("r1"), machine.rulesForJSONEvent("{\"a\" : \"abc\"}"));
assertEquals(new HashSet<>(Arrays.asList("r2", "r3")),
new HashSet<>(machine.rulesForJSONEvent("{\"b\" : \"XYZ\"}")));
assertEquals(Arrays.asList("r1"), machine.rulesForJSONEvent("{\"a\" : \"AbC\"}"));
assertTrue(machine.rulesForJSONEvent("{\"b\" : \"xyzz\"}").isEmpty());
assertTrue(machine.rulesForJSONEvent("{\"a\" : \"aabc\"}").isEmpty());
assertTrue(machine.rulesForJSONEvent("{\"b\" : \"ABCXYZ\"}").isEmpty());
machine.deleteRule("r3", rule3);
assertEquals(Arrays.asList("r2"), machine.rulesForJSONEvent("{\"b\" : \"XYZ\"}"));
machine.deleteRule("r1", rule1);
machine.deleteRule("r2", rule2);
assertTrue(machine.isEmpty());
}
@Test
public void testWildcardMatching() throws Exception {
Machine machine = new Machine();
String rule1 = "{ \"a\" : [ { \"wildcard\": \"*bc\" } ] }";
String rule2 = "{ \"b\" : [ { \"wildcard\": \"d*f\" } ] }";
String rule3 = "{ \"b\" : [ { \"wildcard\": \"d*ff\" } ] }";
String rule4 = "{ \"c\" : [ { \"wildcard\": \"xy*\" } ] }";
String rule5 = "{ \"c\" : [ { \"wildcard\": \"xy*\" } ] }";
String rule6 = "{ \"d\" : [ { \"wildcard\": \"12*4*\" } ] }";
machine.addRule("r1", rule1);
machine.addRule("r2", rule2);
machine.addRule("r3", rule3);
machine.addRule("r4", rule4);
machine.addRule("r5", rule5);
machine.addRule("r6", rule6);
assertEquals(Arrays.asList("r1"), machine.rulesForJSONEvent("{\"a\" : \"bc\"}"));
assertEquals(Arrays.asList("r1"), machine.rulesForJSONEvent("{\"a\" : \"abc\"}"));
assertEquals(Arrays.asList("r2"), machine.rulesForJSONEvent("{\"b\" : \"dexef\"}"));
assertEquals(new HashSet<>(Arrays.asList("r2", "r3")),
new HashSet<>(machine.rulesForJSONEvent("{\"b\" : \"dexeff\"}")));
assertEquals(new HashSet<>(Arrays.asList("r4", "r5")),
new HashSet<>(machine.rulesForJSONEvent("{\"c\" : \"xyzzz\"}")));
assertEquals(Arrays.asList("r6"), machine.rulesForJSONEvent("{\"d\" : \"12345\"}"));
assertTrue(machine.rulesForJSONEvent("{\"c\" : \"abc\"}").isEmpty());
assertTrue(machine.rulesForJSONEvent("{\"a\" : \"xyz\"}").isEmpty());
assertTrue(machine.rulesForJSONEvent("{\"c\" : \"abcxyz\"}").isEmpty());
assertTrue(machine.rulesForJSONEvent("{\"b\" : \"ef\"}").isEmpty());
assertTrue(machine.rulesForJSONEvent("{\"b\" : \"de\"}").isEmpty());
assertTrue(machine.rulesForJSONEvent("{\"d\" : \"1235\"}").isEmpty());
machine.deleteRule("r5", rule5);
assertEquals(Arrays.asList("r4"), machine.rulesForJSONEvent("{\"c\" : \"xy\"}"));
machine.deleteRule("r1", rule1);
machine.deleteRule("r2", rule2);
machine.deleteRule("r3", rule3);
machine.deleteRule("r4", rule4);
machine.deleteRule("r6", rule6);
assertTrue(machine.isEmpty());
}
@Test
public void testCityLotsProblemLines() throws Exception {
String[] e = {
"geometry.coordinates", "-122.42860896096424",
"geometry.coordinates", "37.795818585593523",
"geometry.cordinates", "0.0",
"geometry.type", "\"Polygon\"",
"properties.BLKLOT", "\"0567002\"",
"properties.BLOCK_NUM", "\"0567\"",
"properties.FROM_ST", "\"2521\"",
"properties.LOT_NUM", "\"002\"",
"properties.MAPBLKLOT", "\"0567002\"",
"properties.ODD_EVEN", "\"O\"",
"properties.STREET", "\"OCTAVIA\"",
"properties.ST_TYPE", "\"ST\"",
"properties.TO_ST", "\"2521\"",
"type", ""
};
String eJSON = "{" +
" \"geometry\": {\n" +
" \"coordinates\": [ -122.4286089609642, 37.795818585593523 ],\n" +
" \"type\": \"Polygon\"\n" +
" },\n" +
" \"properties\": {\n" +
" \"BLKLOT\": \"0567002\",\n" +
" \"BLOCK_NUM\": \"0567\",\n" +
" \"FROM_ST\": \"2521\",\n" +
" \"LOT_NUM\": \"002\",\n" +
" \"MAPBLKLOT\": \"0567002\",\n" +
" \"ODD_EVEN\": \"O\",\n" +
" \"STREET\": \"OCTAVIA\",\n" +
" \"ST_TYPE\": \"ST\",\n" +
" \"TO_ST\": \"2521\"\n" +
" }\n" +
"}\n";
String rule = "{" +
" \"properties\": {" +
" \"FROM_ST\": [ \"2521\" ]" +
" },\n" +
" \"geometry\": {\n" +
" \"type\": [ \"Polygon\" ]" +
" }" +
"}";
Machine machine = new Machine();
machine.addRule("R1", rule);
List<String> r = machine.rulesForEvent(e);
assertEquals(1, r.size());
assertEquals("R1", r.get(0));
List<String> eFromJ = Event.flatten(eJSON);
r = machine.rulesForEvent(eFromJ);
assertEquals(1, r.size());
assertEquals("R1", r.get(0));
}
@Test
public void testExistencePatternsLifecycle() throws Exception {
String rule1 = "rule1";
Map<String, List<Patterns>> r1 = new HashMap<>();
List<Patterns> existsPattern = new ArrayList<>();
existsPattern.add(Patterns.existencePatterns());
r1.put("a", existsPattern);
List<Patterns> exactPattern = new ArrayList<>();
exactPattern.add(Patterns.exactMatch("\"b_val\""));
r1.put("b", exactPattern);
String rule2 = "rule2";
Map<String, List<Patterns>> r2 = new HashMap<>();
List<Patterns> absencePatterns = new ArrayList<>();
absencePatterns.add(Patterns.absencePatterns());
r2.put("c", absencePatterns);
List<Patterns> numericalPattern = new ArrayList<>();
numericalPattern.add(Patterns.numericEquals(3));
r2.put("d", numericalPattern);
String rule3 = "rule3";
Map<String, List<Patterns>> r3 = new HashMap<>();
List<Patterns> exactPattern_r3 = new ArrayList<>();
exactPattern_r3.add(Patterns.exactMatch("\"1\""));
r3.put("a", exactPattern_r3);
TestEvent event1 = new TestEvent("a", "\"1\"", "b", "\"b_val\"");
TestEvent event2 = new TestEvent("a", "\"1\"", "b", "\"b_val\"", "d", "3");
TestEvent event3 = new TestEvent("a", "\"1\"", "b", "\"b_val\"", "c", "\"c_val\"", "d", "3");
String jsonEvent1 = "{ \"a\": \"1\", \"b\": \"b_val\" }";
String jsonEvent2 = "{ \"a\": \"1\", \"b\": \"b_val\", \"d\" : 3 }";
String jsonEvent3 = "{ \"a\": \"1\", \"b\": \"b_val\", \"c\" : \"c_val\", \"d\" : 3}";
Machine machine = new Machine();
machine.addPatternRule(rule1, r1);
event1.setExpected(rule1);
event2.setExpected(rule1);
event3.setExpected(rule1);
singleEventTest(machine, event1);
singleEventTestForRulesForJSONEvent(machine, jsonEvent1, event1);
singleEventTest(machine, event2);
singleEventTestForRulesForJSONEvent(machine, jsonEvent2, event2);
singleEventTest(machine, event3);
singleEventTestForRulesForJSONEvent(machine, jsonEvent3, event3);
machine.addPatternRule(rule2, r2);
event2.setExpected(rule2);
singleEventTest(machine, event1);
singleEventTestForRulesForJSONEvent(machine, jsonEvent1, event1);
singleEventTest(machine, event2);
singleEventTestForRulesForJSONEvent(machine, jsonEvent2, event2);
singleEventTest(machine, event3);
singleEventTestForRulesForJSONEvent(machine, jsonEvent3, event3);
machine.addPatternRule(rule3, r3);
event1.setExpected(rule3);
event2.setExpected(rule3);
event3.setExpected(rule3);
singleEventTest(machine, event1);
singleEventTestForRulesForJSONEvent(machine, jsonEvent1, event1);
singleEventTest(machine, event2);
singleEventTestForRulesForJSONEvent(machine, jsonEvent2, event2);
singleEventTest(machine, event3);
singleEventTestForRulesForJSONEvent(machine, jsonEvent3, event3);
machine.deletePatternRule(rule1, r1);
event1.clearExpected(rule1);
event2.clearExpected(rule1);
event3.clearExpected(rule1);
singleEventTest(machine, event1);
singleEventTestForRulesForJSONEvent(machine, jsonEvent1, event1);
singleEventTest(machine, event2);
singleEventTestForRulesForJSONEvent(machine, jsonEvent2, event2);
singleEventTest(machine, event3);
singleEventTestForRulesForJSONEvent(machine, jsonEvent3, event3);
machine.deletePatternRule(rule2, r2);
event1.clearExpected(rule2);
event2.clearExpected(rule2);
event3.clearExpected(rule2);
singleEventTest(machine, event1);
singleEventTestForRulesForJSONEvent(machine, jsonEvent1, event1);
singleEventTest(machine, event2);
singleEventTestForRulesForJSONEvent(machine, jsonEvent2, event2);
singleEventTest(machine, event3);
singleEventTestForRulesForJSONEvent(machine, jsonEvent3, event3);
machine.deletePatternRule(rule3, r3);
event1.clearExpected(rule3);
event2.clearExpected(rule3);
event3.clearExpected(rule3);
singleEventTest(machine, event1);
singleEventTestForRulesForJSONEvent(machine, jsonEvent1, event1);
singleEventTest(machine, event2);
singleEventTestForRulesForJSONEvent(machine, jsonEvent2, event2);
singleEventTest(machine, event3);
singleEventTestForRulesForJSONEvent(machine, jsonEvent3, event3);
assertTrue(machine.isEmpty());
}
@Test
public void matchRulesWithExistencePatternAndMatchOnExistenceByte() throws Exception {
String rule1 = "rule1";
Map<String, List<Patterns>> r1 = new HashMap<>();
List<Patterns> existsPattern = new ArrayList<>();
existsPattern.add(Patterns.existencePatterns());
r1.put("a", existsPattern);
String rule2 = "rule2";
Map<String, List<Patterns>> r2 = new HashMap<>();
List<Patterns> exactPattern = new ArrayList<>();
exactPattern.add(Patterns.exactMatch("\"Y\""));
r2.put("b", exactPattern);
String rule3 = "rule3";
Map<String, List<Patterns>> r3 = new HashMap<>();
List<Patterns> exactPattern_r3 = new ArrayList<>();
exactPattern_r3.add(Patterns.exactMatch("\"YES\""));
r3.put("c", exactPattern_r3);
String jsonEvent = "{\"a\": \"1\", \"b\": \"Y\", \"c\": \"YES\"}";
TestEvent event = new TestEvent("a", "\"1\"", "b", "\"Y\"", "c", "\"YES\"");
Machine machine = new Machine();
machine.addPatternRule(rule1, r1);
event.setExpected(rule1);
singleEventTest(machine, event);
singleEventTestForRulesForJSONEvent(machine, jsonEvent, event);
machine.addPatternRule(rule2, r2);
event.setExpected(rule2);
singleEventTest(machine, event);
singleEventTestForRulesForJSONEvent(machine, jsonEvent, event);
machine.addPatternRule(rule3, r3);
event.setExpected(rule3);
singleEventTest(machine, event);
singleEventTestForRulesForJSONEvent(machine, jsonEvent, event);
machine.deletePatternRule(rule3, r3);
event.clearExpected(rule3);
singleEventTest(machine, event);
singleEventTestForRulesForJSONEvent(machine, jsonEvent, event);
machine.deletePatternRule(rule2, r2);
event.clearExpected(rule2);
singleEventTest(machine, event);
singleEventTestForRulesForJSONEvent(machine, jsonEvent, event);
machine.deletePatternRule(rule1, r1);
event.clearExpected(rule1);
singleEventTest(machine, event);
singleEventTestForRulesForJSONEvent(machine, jsonEvent, event);
assertTrue(machine.isEmpty());
}
@Test
public void matchRuleWithExistencePatternAtEnd_andMatchesAtEventAfterAllFieldsHaveExhausted() throws Exception {
String rule1 = "rule1";
Map<String, List<Patterns>> r1 = new HashMap<>();
List<Patterns> exactPattern = new ArrayList<>();
exactPattern.add(Patterns.exactMatch("\"Y\""));
r1.put("a", exactPattern);
List<Patterns> greaterPattern = new ArrayList<>();
greaterPattern.add(Range.greaterThan(10));
r1.put("b", greaterPattern);
List<Patterns> existsPattern = new ArrayList<>();
existsPattern.add(Patterns.existencePatterns());
r1.put("c", existsPattern);
List<Patterns> absencePattern = new ArrayList<>();
absencePattern.add(Patterns.absencePatterns());
r1.put("d", absencePattern);
String jsonEvent = "{\"a\": \"Y\", \"b\": 20, \"c\": \"YES\"}";
TestEvent event = new TestEvent("a", "\"Y\"", "b", "20", "c", "\"YES\"");
Machine machine = new Machine();
machine.addPatternRule(rule1, r1);
event.setExpected(rule1);
singleEventTest(machine, event);
singleEventTestForRulesForJSONEvent(machine, jsonEvent, event);
}
private void setRules(Machine machine) {
List<Rule> rules = new ArrayList<>();
Rule rule;
rule = new Rule("R1");
rule.setKeys("beta", "alpha", "gamma");
rule.setExactMatchValues("2", "1", "3");
rules.add(rule);
rule = new Rule("R2");
rule.setKeys("alpha", "foo", "bar");
rule.setExactMatchValues("1", "\"v23\"", "\"v22\"");
rules.add(rule);
rule = new Rule("R3");
rule.setKeys("inner", "outer", "upper");
rule.setExactMatchValues("\"i0\"", "\"i1\"", "\"i2\"");
rules.add(rule);
rule = new Rule("R4");
rule.setKeys("d1", "d2");
rule.setExactMatchValues("\"v1\"", "\"v2\"");
rules.add(rule);
rule = new Rule("R5-super");
rule.setKeys("r5-k1", "r5-k2", "r5-k3");
rule.setExactMatchValues("\"r5-v1\"", "\"r5-v2\"", "\"r5-v3\"");
rules.add(rule);
rule = new Rule("R5-prefix");
rule.setKeys("r5-k1", "r5-k2");
rule.setExactMatchValues("\"r5-v1\"", "\"r5-v2\"");
rules.add(rule);
rule = new Rule("R5-suffix");
rule.setKeys("r5-k2", "r5-k3");
rule.setExactMatchValues("\"r5-v2\"", "\"r5-v3\"");
rules.add(rule);
rule = new Rule("R6");
List<Patterns> x15_25 = new ArrayList<>();
x15_25.add(Patterns.exactMatch("15"));
x15_25.add(Patterns.exactMatch("25"));
rule.addMulti(x15_25);
rule.setKeys("x1", "x7");
rule.setExactMatchValues("11", "50");
rules.add(rule);
rule = new Rule("R7");
rule.setKeys("r5-k1");
rule.setPatterns(Patterns.prefixMatch("\"r5"));
rules.add(rule);
for (Rule r : rules) {
machine.addPatternRule(r.name, r.fields);
}
}
private List<TestEvent> createEvents() {
List<TestEvent> events = new ArrayList<>();
TestEvent e;
// match an event exactly
e = new TestEvent("alpha", "1", "beta", "2", "gamma", "3");
e.setExpected("R1");
events.add(e);
// extras between all the fields, should still match
e = new TestEvent("0", "", "alpha", "1", "arc", "xx", "beta", "2", "gamma", "3", "zoo", "keeper");
e.setExpected("R1");
events.add(e);
// fail on value
e = new TestEvent("alpha", "1", "beta", "3", "gamma", "3");
events.add(e);
// fire two rules
e = new TestEvent("alpha", "1", "beta", "2", "gamma", "3", "inner", "\"i0\"", "outer", "\"i1\"", "upper", "\"i2\"");
e.setExpected("R1", "R3");
events.add(e);
// one rule inside another
e = new TestEvent("alpha", "1", "beta", "2", "d1", "\"v1\"", "d2", "\"v2\"", "gamma", "3");
e.setExpected("R1", "R4");
events.add(e);
// two rules in a funny way
e = new TestEvent("0", "", "alpha", "1", "arc", "xx", "bar", "\"v22\"", "beta", "2", "foo", "\"v23\"", "gamma", "3",
"zoo", "keeper");
e.setExpected("R1", "R2");
events.add(e);
// match prefix rule
e = new TestEvent("r5-k1", "\"r5-v1\"", "r5-k2", "\"r5-v2\"");
e.setExpected("R5-prefix", "R7");
events.add(e);
// match 3 rules
e = new TestEvent("r5-k1", "\"r5-v1\"", "r5-k2", "\"r5-v2\"", "r5-k3", "\"r5-v3\"");
e.setExpected("R5-prefix", "R5-super", "R5-suffix", "R7");
events.add(e);
// single state with two branches
e = new TestEvent("zork", "max", "x1", "11", "x6", "15", "x7", "50");
e.setExpected("R6");
events.add(e);
e = new TestEvent("x1", "11", "x6", "25", "foo", "bar", "x7", "50");
e.setExpected("R6");
events.add(e);
// extras between all the fields, should still match
e = new TestEvent("0", "", "alpha", "1", "arc", "xx", "beta", "2", "gamma", "3", "zoo", "keeper");
e.setExpected("R1");
events.add(e);
// fail on value
e = new TestEvent("alpha", "1", "beta", "3", "gamma", "3");
events.add(e);
// fire two rules
e = new TestEvent("alpha", "1", "beta", "2", "gamma", "3", "inner", "\"i0\"", "outer", "\"i1\"", "upper", "\"i2\"");
e.setExpected("R1", "R3");
events.add(e);
// one rule inside another
e = new TestEvent("alpha", "1", "beta", "2", "d1", "\"v1\"", "d2", "\"v2\"", "gamma", "3");
e.setExpected("R1", "R4");
events.add(e);
// two rules in a funny way
e = new TestEvent("0", "", "alpha", "1", "arc", "xx", "bar", "\"v22\"", "beta", "2", "foo", "\"v23\"", "gamma", "3",
"zoo", "keeper");
e.setExpected("R1", "R2");
events.add(e);
// match prefix rule
e = new TestEvent("r5-k1", "\"r5-v1\"", "r5-k2", "\"r5-v2\"");
e.setExpected("R5-prefix", "R7");
events.add(e);
// match 3 rules
e = new TestEvent("r5-k1", "\"r5-v1\"", "r5-k2", "\"r5-v2\"", "r5-k3", "\"r5-v3\"");
e.setExpected("R5-prefix", "R5-super", "R5-suffix", "R7");
events.add(e);
// single state with two branches
e = new TestEvent("zork", "max", "x1", "11", "x6", "15", "x7", "50");
e.setExpected("R6");
events.add(e);
e = new TestEvent("x1", "11", "x6", "25", "foo", "bar", "x7", "50");
e.setExpected("R6");
events.add(e);
return events;
}
@Test
public void testBuild() {
Machine machine = new Machine();
setRules(machine);
assertNotNull(machine);
List<TestEvent> events = createEvents();
for (TestEvent event : events) {
singleEventTest(machine, event);
}
}
private void singleEventTest(Machine machine, TestEvent event) {
List<String> actual = machine.rulesForEvent(event.mTokens);
if (event.mExpectedRules.isEmpty()) {
assertTrue(actual.isEmpty());
} else {
for (String expected : event.mExpectedRules) {
assertTrue("Event " + event + "\n did not match rule '" + expected + "'", actual.contains(expected));
actual.remove(expected);
}
if (!actual.isEmpty()) {
fail("Event " + event + "\n rule " + actual.size() + " extra rules: " + actual.get(0));
}
}
}
private void singleEventTestForRulesForJSONEvent(Machine machine, String eventJson, TestEvent event) throws Exception {
List<String> actual = machine.rulesForJSONEvent(eventJson);
if (event.mExpectedRules.isEmpty()) {
assertTrue(actual.isEmpty());
} else {
for (String expected : event.mExpectedRules) {
assertTrue("Event " + event + "\n did not match rule '" + expected + "'", actual.contains(expected));
actual.remove(expected);
}
if (!actual.isEmpty()) {
fail("Event " + event + "\n rule " + actual.size() + " extra rules: " + actual.get(0));
}
}
}
private static class TestEvent {
private String[] mTokens;
private final List<String> mExpectedRules = new ArrayList<>();
TestEvent(String... tokens) {
mTokens = tokens;
}
void setExpected(String... rules) {
Collections.addAll(mExpectedRules, rules);
}
void clearExpected(String... rules) {
Arrays.stream(rules).forEach(mExpectedRules::remove);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Tokens: ");
for (String token : mTokens) {
sb.append(token).append(" / ");
}
sb.append(" Expected: ");
for (String expected : mExpectedRules) {
sb.append(expected).append(" / ");
}
sb.append("\n");
return sb.toString();
}
}
private static class Rule {
String name;
final Map<String, List<Patterns>> fields = new HashMap<>();
private String[] keys;
Rule(String name) {
this.name = name;
}
void setKeys(String... keys) {
this.keys = keys;
}
void setExactMatchValues(String... values) {
for (int i = 0; i < values.length; i++) {
final List<Patterns> valList = new ArrayList<>();
valList.add(Patterns.exactMatch(values[i]));
fields.put(keys[i], valList);
}
}
void setPatterns(Patterns... values) {
for (int i = 0; i < values.length; i++) {
final List<Patterns> valList = new ArrayList<>();
valList.add((values[i]));
fields.put(keys[i], valList);
}
}
void addMulti(List<Patterns> vals) {
fields.put("x6", vals);
}
}
@Test
public void addRuleOriginalAPI() {
Machine machine = new Machine();
Map<String, List<String>> map1 = new HashMap<>();
Map<String, List<String>> map2 = new HashMap<>();
List<String> s1 = asList("x", "y");
List<String> s2 = asList("1", "2");
List<String> s3 = asList("foo", "bar");
map1.put("f1", s1);
map1.put("f2", s2);
map2.put("f1", s3);
machine.addRule("r1", map1);
machine.addRule("r2", map2);
String[] event1 = { "f1", "x", "f2", "1" };
String[] event2 = { "f1", "foo" };
List<String> l = machine.rulesForEvent(event1);
assertEquals(1, l.size());
assertEquals("r1", l.get(0));
l = machine.rulesForEvent(event2);
assertEquals(1, l.size());
assertEquals("r2", l.get(0));
}
@Test
public void twoRulesSamePattern() throws IOException {
Machine machine = new Machine();
String json = "{\"detail\":{\"testId\":[\"foo\"]}}";
machine.addRule("rule1", json);
machine.addRule("rule2", new StringReader(json));
machine.addRule("rule3", json.getBytes(StandardCharsets.UTF_8));
machine.addRule("rule4", new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));
List<String> event = new ArrayList<>();
event.add("detail.testId");
event.add("\"foo\"");
List<String> strings = machine.rulesForEvent(event);
assertEquals(4, strings.size());
}
@Test
public void twoRulesSamePattern2() {
Machine machine = new Machine();
List<Rule> rules = new ArrayList<>();
Rule rule;
rule = new Rule("R1");
rule.setKeys("a", "c", "b");
rule.setExactMatchValues("1", "3", "2");
rules.add(rule);
rule = new Rule("R2");
rule.setKeys("a", "b", "c");
rule.setExactMatchValues("1", "2", "3");
rules.add(rule);
for (Rule r : rules) {
machine.addPatternRule(r.name, r.fields);
}
TestEvent e = new TestEvent("0", "", "a", "1", "b", "2", "c", "3", "gamma", "3", "zoo", "keeper");
e.setExpected("R1", "R2");
List<String> actual = machine.rulesForEvent(e.mTokens);
assertEquals(2, actual.size());
}
@Test
public void dynamicAddRules() {
Machine machine = new Machine();
TestEvent e = new TestEvent("0", "", "a", "11", "b", "21", "c", "31", "gamma", "41", "zoo", "keeper");
Rule rule;
Rule rule1;
Rule rule2;
Rule rule3;
rule = new Rule("R1");
rule.setKeys("a", "b", "c");
rule.setExactMatchValues("11", "21", "31");
//test whether duplicated rule could be added
machine.addPatternRule(rule.name, rule.fields);
machine.addPatternRule(rule.name, rule.fields);
machine.addPatternRule(rule.name, rule.fields);
rule1 = new Rule("R1");
rule1.setKeys("a", "b", "zoo");
rule1.setExactMatchValues("11", "21", "keeper");
machine.addPatternRule(rule1.name, rule1.fields);
List<String> actual1 = machine.rulesForEvent(e.mTokens);
assertEquals(1, actual1.size());
rule2 = new Rule("R2-1");
rule2.setKeys("a", "c", "b");
rule2.setExactMatchValues("11", "31", "21");
machine.addPatternRule(rule2.name, rule2.fields);
List<String> actual2 = machine.rulesForEvent(e.mTokens);
assertEquals(2, actual2.size());
rule3 = new Rule("R2-2");
rule3.setKeys("gamma", "zoo");
rule3.setExactMatchValues("41", "keeper");
machine.addPatternRule(rule3.name, rule3.fields);
List<String> actual3 = machine.rulesForEvent(e.mTokens);
assertEquals(3, actual3.size());
}
/**
* Incrementally build Rule R1 by different namevalues, observing new state and rules created
* Decrementally delete rule R1 by pointed namevalues, observing state and rules
* which is not used have been removed.
*/
@Test
public void dynamicDeleteRules() {
Machine machine = new Machine();
TestEvent e = new TestEvent("0", "", "a", "11", "b", "21", "c", "31", "gamma", "41", "zoo", "keeper");
Rule rule;
Rule rule1;
rule = new Rule("R1");
rule.setKeys("a", "b", "c");
rule.setExactMatchValues("11", "21", "31");
machine.addPatternRule(rule.name, rule.fields);
List<String> actual = machine.rulesForEvent(e.mTokens);
assertEquals(1, actual.size());
rule1 = new Rule("R1");
rule1.setKeys("a", "b", "gamma");
rule1.setExactMatchValues("11", "21", "41");
machine.addPatternRule(rule1.name, rule1.fields);
List<String> actual1 = machine.rulesForEvent(e.mTokens);
assertEquals(1, actual1.size());
// delete R1 subset with rule.fields
machine.deletePatternRule(rule.name, rule.fields);
List<String> actual2 = machine.rulesForEvent(e.mTokens);
assertEquals(1, actual2.size());
// delete R1 subset with rule1 fields, after this step,
// the machine will become empty as if no rule was added before.
machine.deletePatternRule(rule1.name, rule1.fields);
List<String> actual3 = machine.rulesForEvent(e.mTokens);
assertEquals(0, actual3.size());
}
/**
* Setup thread pools with 310 threads inside, among them, 300 threads are calling rulesForEvent(),
* 10 threads are adding rule. the test is designed to add rules and match rules operation handled in parallel,
* observe rulesForEvent whether could work well while there is new rule keeping added dynamically in parallel.
* Keep same event call rulesForEvent() in parallel, expect to see more and more rules will be matched
* aligned with more and more new rules added.
* In this test:
* We created 100 rules with 100 key/val pair (each rule use one key/val), we created one "global" event by using
* those 100 key/val pairs. this event should match out all those 100 rules since they are added.
* So if we keep using this event query machine while adding 100 rules in parallel, we should see the output of
* number of matched rules by rulesForEvent keep increasing from 0 to 100, then stabilize returning 100 for
* all of following rulesForEvent().
*/
@Test
public void testMultipleThreadReadAddRule() {
Machine machine = new Machine();
List<String> event = new ArrayList<>();
List<Rule> rules = new ArrayList<>();
for (int i = 0; i< 100; i++) {
event.add(String.format("key-%03d",i));
event.add(String.format("val-%03d",i));
}
for (int j = 0, i = 0; j<200 && i<100; j+=2,i++) {
Rule rule = new Rule("R-" + i);
rule.setKeys(event.get(j));
rule.setExactMatchValues(event.get(j+1));
rules.add(rule);
}
CountDownLatch latch = new CountDownLatch(1);
class AddRuleRunnable implements Runnable {
private final int i;
private AddRuleRunnable(int i) {
this.i = i;
}
@Override
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
Rule rule = rules.get(i);
machine.addPatternRule(rule.name,rule.fields);
}
}
class MatchRuleRunnable implements Runnable {
@Override
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
int i = 0;
int n;
// this thread only return when match out 100 rules 100 times.
while (i < 100) {
List<String> actual = machine.rulesForEvent(event);
// the number of matched rules will keep growing from 0 till to 100
n = actual.size();
if (n == 100) {
i++;
}
}
}
}
ExecutorService execW = Executors.newFixedThreadPool(10);
ExecutorService execR = Executors.newFixedThreadPool(300);
for(int i = 0; i < 100; i++) {
execW.execute(new AddRuleRunnable(i));
}
for(int i = 0; i < 300; i++) {
execR.execute(new MatchRuleRunnable());
}
// release threads to let them work
latch.countDown();
execW.shutdown();
execR.shutdown();
try {
execW.awaitTermination(5, TimeUnit.MINUTES);
execR.awaitTermination(5, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
List<String> actual = machine.rulesForEvent(event);
assertEquals(100, actual.size());
}
@Test
public void testMultipleThreadReadDeleteRule() {
Machine machine = new Machine();
List<String> event = new ArrayList<>();
List <Rule> rules = new ArrayList<>();
for (int i = 0; i< 100; i++) {
event.add(String.format("key-%03d",i));
event.add(String.format("val-%03d",i));
}
// first add 100 rules into machine.
for (int j = 0, i = 0; j<200 && i<100; j+=2,i++) {
Rule rule = new Rule("R-" + i);
rule.setKeys(event.get(j));
rule.setExactMatchValues(event.get(j+1));
rules.add(rule);
machine.addPatternRule(rule.name,rule.fields);
}
CountDownLatch latch = new CountDownLatch(1);
class DeleteRuleRunnable implements Runnable {
private final int i;
private DeleteRuleRunnable(int i) {
this.i = i;
}
@Override
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
Rule rule = rules.get(i);
machine.deletePatternRule(rule.name,rule.fields);
}
}
class MatchRuleRunnable implements Runnable {
@Override
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
int i = 0;
int n;
// this thread only return when match out 100 rules 100 times.
while (i < 100) {
List<String> actual = machine.rulesForEvent(event);
// the number of matched rules will keep growing from 0 till to 100
n = actual.size();
if (n == 0) {
i++;
}
}
}
}
ExecutorService execW = Executors.newFixedThreadPool(10);
ExecutorService execR = Executors.newFixedThreadPool(300);
for(int i = 0; i < 100; i++) {
execW.execute(new DeleteRuleRunnable(i));
}
for(int i = 0; i < 300; i++) {
execR.execute(new MatchRuleRunnable());
}
// release threads to let them work
latch.countDown();
execW.shutdown();
execR.shutdown();
try {
execW.awaitTermination(5, TimeUnit.MINUTES);
execR.awaitTermination(5, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
List<String> actual = machine.rulesForEvent(event);
assertEquals(0, actual.size());
}
@Test
public void testFunkyDelete() throws Exception {
String rule = "{ \"foo\": { \"bar\": [ 23 ] }}";
Machine cut = new Machine();
// add the rule, ensure it matches
cut.addRule("r1", rule);
String[] event = { "foo.bar", "23" };
assertEquals(1, cut.rulesForEvent(event).size());
// delete the rule, no match
cut.deleteRule("r1", rule);
assertEquals(0, cut.rulesForEvent(event).size());
assertTrue(cut.isEmpty());
// add it back, it matches
cut.addRule("r1", rule);
assertEquals(1, cut.rulesForEvent(event).size());
// delete it but with the wrong name. Should be a no-op
cut.deleteRule("r2", rule);
assertEquals(1, cut.rulesForEvent(event).size());
assertFalse(cut.isEmpty());
// delete it but with the correct name. Should be no match
cut.deleteRule("r1", rule);
assertEquals(0, cut.rulesForEvent(event).size());
assertTrue(cut.isEmpty());
}
@Test
public void testFunkyDelete1() throws Exception {
String rule = "{ \"foo\": { \"bar\": [ 23, 45 ] }}";
String rule1 = "{ \"foo\": { \"bar\": [ 23 ] }}";
String rule2 = "{ \"foo\": { \"bar\": [ 45 ] }}";
String rule3 = "{ \"foo\": { \"bar\": [ 44, 45, 46 ] }}";
String rule4 = "{ \"foo\": { \"bar\": [ 44, 46, 47 ] }}";
String rule5 = "{ \"foo\": { \"bar\": [ 23, 44, 45, 46, 47 ] }}";
Machine cut = new Machine();
// add the rule, ensure it matches
cut.addRule("r1", rule);
String[] event = { "foo.bar", "23" };
String[] event1 = { "foo.bar", "45" };
assertEquals(1, cut.rulesForEvent(event).size());
assertEquals(1, cut.rulesForEvent(event1).size());
// delete partial rule 23, partial match
cut.deleteRule("r1", rule1);
assertEquals(0, cut.rulesForEvent(event).size());
assertEquals(1, cut.rulesForEvent(event1).size());
// delete partial rule 45, no match
cut.deleteRule("r1", rule2);
assertEquals(0, cut.rulesForEvent(event).size());
assertEquals(0, cut.rulesForEvent(event1).size());
assertTrue(cut.isEmpty());
// add it back, it matches
cut.addRule("r1", rule);
assertEquals(1, cut.rulesForEvent(event).size());
assertEquals(1, cut.rulesForEvent(event1).size());
// delete rule3, partially delete 45, 44 and 46 are not existing will be ignored,
// so should only match 23
cut.deleteRule("r1", rule3);
assertEquals(1, cut.rulesForEvent(event).size());
assertEquals(0, cut.rulesForEvent(event1).size());
// delete rule then should match nothing ...
cut.deleteRule("r1", rule);
assertEquals(0, cut.rulesForEvent(event).size());
assertEquals(0, cut.rulesForEvent(event1).size());
assertTrue(cut.isEmpty());
// add it back, it matches
cut.addRule("r1", rule);
assertEquals(1, cut.rulesForEvent(event).size());
assertEquals(1, cut.rulesForEvent(event1).size());
// delete rule4, as rule4 has nothing related with other rule, machine should do nothing.
cut.deleteRule("r1", rule4);
assertEquals(1, cut.rulesForEvent(event).size());
assertEquals(1, cut.rulesForEvent(event1).size());
// delete all
cut.deleteRule("r1", rule5);
assertEquals(0, cut.rulesForEvent(event).size());
assertEquals(0, cut.rulesForEvent(event1).size());
assertTrue(cut.isEmpty());
}
@Test
public void testRangeDeletion() throws Exception {
String rule = "{\"x\": [{\"numeric\": [\">=\", 0, \"<\", 1000000000]}]}";
Machine cut = new Machine();
// add the rule, ensure it matches
cut.addRule("r1", rule);
String[] event = {"x", "111111111.111111111"};
String[] event1 = {"x", "1000000000"};
assertEquals(1, cut.rulesForEvent(event).size());
assertEquals(0, cut.rulesForEvent(event1).size());
// delete partial rule 23, partial match
cut.deleteRule("r1", rule);
assertEquals(0, cut.rulesForEvent(event).size());
assertEquals(0, cut.rulesForEvent(event1).size());
assertTrue(cut.isEmpty());
// test multiple key/value rule
rule = "{\n" +
"\"m\": [\"abc\"],\n" +
"\"x\": [\n" +
"{\n" +
"\"numeric\": [\">\", 0, \"<\", 30]\n" +
"},\n" +
"{\n" +
"\"numeric\": [\">\", 100, \"<\", 120]\n" +
"}\n" +
"],\n" +
"\"n\": [\"efg\"]\n" +
"}";
cut.addRule("r2", rule);
event = new String[]{"m", "\"abc\"", "n", "\"efg\"", "x", "23"};
event1 = new String[]{"m", "\"abc\"", "n", "\"efg\"", "x", "110"};
assertEquals(1, cut.rulesForEvent(event).size());
assertEquals(1, cut.rulesForEvent(event1).size());
cut.deleteRule("r2", rule);
assertEquals(0, cut.rulesForEvent(event).size());
assertEquals(0, cut.rulesForEvent(event1).size());
assertTrue(cut.isEmpty());
}
@Test
public void deleteRule() throws Exception {
String rule = "{ \"foo\": { \"bar\": [ \"ab\", \"cd\" ] }}";
Machine cut = new Machine();
// add the rule, ensure it matches
cut.addRule("r1", rule);
String[] event = { "foo.bar", "\"ab\"" };
String[] event1 = { "foo.bar", "\"cd\"" };
String[] event2 = { "foo.bar", "\"ab\"", "foo.bar", "\"cd\"" };
assertEquals(1, cut.rulesForEvent(event).size());
assertEquals(1, cut.rulesForEvent(event1).size());
assertEquals(1, cut.rulesForEvent(event2).size());
Map<String, List<String>> namevals = new HashMap<>();
// delete partial rule 23, partial match
namevals.put("foo.bar", Collections.singletonList("\"ab\""));
cut.deleteRule("r1", namevals);
assertEquals(0, cut.rulesForEvent(event).size());
assertEquals(1, cut.rulesForEvent(event1).size());
assertEquals(1, cut.rulesForEvent(event2).size());
namevals.put("foo.bar", Collections.singletonList("\"cd\""));
cut.deleteRule("r1", namevals);
assertEquals(0, cut.rulesForEvent(event).size());
assertEquals(0, cut.rulesForEvent(event1).size());
assertEquals(0, cut.rulesForEvent(event2).size());
}
@Test
public void WHEN_RuleForJsonEventIsPresented_THEN_ItIsMatched() throws Exception {
final Machine rulerMachine = new Machine();
rulerMachine.addRule( "test-rule", "{ \"type\": [\"Notification\"] }" );
String[] sortedEventFields = {
"signature", "\"JYFVGfee...\"",
"signatureVersion", "1",
"signingCertUrl", "\"https://sns.us-east-1.amazonaws.com/SimpleNotificationService-1234.pem\"",
"subscribeUrl", "null",
"topicArn", "\"arn:aws:sns:us-east-1:108960525716:cw-to-sns-to-slack\"",
"type", "\"Notification\""
//, etc
};
List<String> foundRules = rulerMachine.rulesForEvent(sortedEventFields);
assertTrue(foundRules.contains("test-rule"));
}
@Test
public void OneEventWithDuplicatedKeyButDifferentValueMatchRules() throws Exception {
Machine cut = new Machine();
String rule1 = "{ \"foo\": { \"bar\": [ \"ab\" ] }}";
String rule2 = "{ \"foo\": { \"bar\": [ \"cd\" ] }}";
// add the rule, ensure it matches
cut.addRule("r1", rule1);
cut.addRule("r2", rule2);
String[] event = { "foo.bar", "\"ab\"" };
String[] event1 = { "foo.bar", "\"cd\"" };
String[] event2 = { "foo.bar", "\"ab\"", "foo.bar", "\"cd\"" };
assertEquals(1, cut.rulesForEvent(event).size());
assertEquals(1, cut.rulesForEvent(event1).size());
assertEquals(2, cut.rulesForEvent(event2).size());
Map<String, List<String>> namevals = new HashMap<>();
// delete partial rule 23, partial match
namevals.put("foo.bar", Collections.singletonList("\"ab\""));
cut.deleteRule("r1", namevals);
assertEquals(0, cut.rulesForEvent(event).size());
assertEquals(1, cut.rulesForEvent(event1).size());
assertEquals(1, cut.rulesForEvent(event2).size());
namevals.put("foo.bar", Collections.singletonList("\"cd\""));
cut.deleteRule("r2", namevals);
assertEquals(0, cut.rulesForEvent(event).size());
assertEquals(0, cut.rulesForEvent(event1).size());
assertEquals(0, cut.rulesForEvent(event2).size());
}
@Test
public void OneRuleMadeByTwoConditions() throws Exception {
Machine cut = new Machine();
String condition1 = "{\n" +
"\"A\" : [ \"on\" ],\n" +
"\"C\" : [ \"on\" ],\n" +
"\"D\" : [ \"off\" ]\n" +
"}";
String condition2 = "{\n" +
"\"B\" : [\"on\" ],\n" +
"\"C\" : [\"on\" ],\n" +
"\"D\" : [\"off\" ]\n" +
"}";
// add the rule, ensure it matches
cut.addRule("AlarmRule1", condition1);
cut.addRule("AlarmRule1", condition2);
String[] event = { "A", "\"on\"", "C", "\"on\"", "D", "\"off\"" };
String[] event1 = { "B", "\"on\"", "C", "\"on\"", "D", "\"off\"" };
String[] event2 = { "A", "\"on\"", "B", "\"on\"", "C", "\"on\"", "D", "\"on\"" };
String[] event3 = { "A", "\"on\"", "B", "\"on\"", "C", "\"on\"", "D", "\"off\"" };
assertEquals(1, cut.rulesForEvent(event).size());
assertEquals(1, cut.rulesForEvent(event1).size());
assertEquals(0, cut.rulesForEvent(event2).size());
assertEquals(1, cut.rulesForEvent(event3).size());
cut.deleteRule("AlarmRule1", condition1);
assertEquals(0, cut.rulesForEvent(event).size());
assertEquals(1, cut.rulesForEvent(event1).size());
assertEquals(0, cut.rulesForEvent(event2).size());
assertEquals(1, cut.rulesForEvent(event3).size());
cut.deleteRule("AlarmRule1", condition2);
assertEquals(0, cut.rulesForEvent(event).size());
assertEquals(0, cut.rulesForEvent(event1).size());
assertEquals(0, cut.rulesForEvent(event2).size());
assertEquals(0, cut.rulesForEvent(event3).size());
}
@Test
public void testNumericMatch() throws Exception {
String rule = "{\n" +
"\"a\": [ { \"numeric\": [ \"=\", 0 ] } ],\n" +
"\"b\": [ { \"numeric\": [ \"<\", 0 ] } ],\n" +
"\"c\": [ { \"numeric\": [ \"<=\", 0 ] } ],\n" +
"\"x\": [ { \"numeric\": [ \">\", 0 ] } ],\n" +
"\"y\": [ { \"numeric\": [ \">=\", 0 ] } ],\n" +
"\"z\": [ { \"numeric\": [ \">\", 0, \"<\", 1 ] } ]\n" +
"}";
Machine cut = new Machine();
// add the rule, ensure it matches
cut.addRule("r1", rule);
String[] event = {"a", "0", "b", "-0.1", "c", "0", "x", "1", "y", "0", "z", "0.1"};
String eventJSON = "{\n" +
"\t\"a\": [0],\n" +
"\t\"b\": [-0.1],\n" +
"\t\"c\": [0],\n" +
"\t\"x\": [1],\n" +
"\t\"y\": [0],\n" +
"\t\"z\": [0.1]\n" +
"}";
assertEquals(1, cut.rulesForEvent(event).size());
assertTrue(Ruler.matchesRule(eventJSON, rule));
// delete partial rule
cut.deleteRule("r1", rule);
assertEquals(0, cut.rulesForEvent(event).size());
assertTrue(Ruler.matchesRule(eventJSON, rule));
assertTrue(cut.isEmpty());
}
@Test
public void testAnythingButDeletion() throws Exception {
String rule = "{\n" +
"\"a\": [ { \"anything-but\": [ \"dad0\",\"dad1\",\"dad2\" ] } ],\n" +
"\"b\": [ { \"anything-but\": [ 111, 222, 333 ] } ],\n" +
"\"c\": [ { \"anything-but\": \"dad0\" } ],\n" +
"\"d\": [ { \"anything-but\": 111 } ],\n" +
"\"z\": [ { \"numeric\": [ \">\", 0, \"<\", 1 ] } ]\n" +
"}";
Machine cut = new Machine();
// add the rule, ensure it matches
cut.addRule("r1", rule);
String event = "{" +
" \"a\": \"child1\",\n" +
" \"b\": \"444\",\n" +
" \"c\": \"child1\",\n" +
" \"d\": \"444\",\n" +
" \"z\": 0.001 \n" +
"}\n";
String event1 = "{" +
" \"a\": \"dad4\",\n" +
" \"b\": 444,\n" +
" \"c\": \"child1\",\n" +
" \"d\": \"444\",\n" +
" \"z\": 0.001 \n" +
"}\n";
assertEquals(1, cut.rulesForEvent(event).size());
assertEquals(1, cut.rulesForEvent(event1).size());
// delete partial rule 23, partial match
cut.deleteRule("r1", rule);
assertEquals(0, cut.rulesForEvent(event).size());
assertEquals(0, cut.rulesForEvent(event1).size());
assertTrue(cut.isEmpty());
}
@Test
public void testAnythingButEqualsIgnoreCaseDeletion() throws Exception {
String rule = "{\n" +
"\"a\": [ { \"anything-but\": {\"equals-ignore-case\": [ \"dad0\",\"dad1\",\"dad2\" ] } } ],\n" +
"\"c\": [ { \"anything-but\": {\"equals-ignore-case\": \"dad0\" } } ],\n" +
"\"z\": [ { \"numeric\": [ \">\", 0, \"<\", 1 ] } ]\n" +
"}";
Machine cut = new Machine();
// add the rule, ensure it matches
cut.addRule("r1", rule);
String event = "{" +
" \"a\": \"Child1\",\n" +
" \"c\": \"chiLd1\",\n" +
" \"z\": 0.001 \n" +
"}\n";
String event1 = "{" +
" \"a\": \"dAd4\",\n" +
" \"c\": \"Child1\",\n" +
" \"z\": 0.001 \n" +
"}\n";
assertEquals(1, cut.rulesForEvent(event).size());
assertEquals(1, cut.rulesForEvent(event1).size());
// delete partial rule 23, partial match
cut.deleteRule("r1", rule);
assertEquals(0, cut.rulesForEvent(event).size());
assertEquals(0, cut.rulesForEvent(event1).size());
assertTrue(cut.isEmpty());
}
@Test
public void testIpExactMatch() throws Exception {
String[] ipAddressesToBeMatched = {
"0011:2233:4455:6677:8899:aabb:ccdd:eeff",
"2001:db8::ff00:42:8329",
"::0",
"::3",
"::9",
"::a",
"::f",
"2400:6500:FF00::36FB:1F80",
"2400:6500:FF00::36FB:1F85",
"2400:6500:FF00::36FB:1F89",
"2400:6500:FF00::36FB:1F8C",
"2400:6500:FF00::36FB:1F8F",
"54.240.196.255",
"255.255.255.255",
"255.255.255.0",
"255.255.255.5",
"255.255.255.10",
"255.255.255.16",
"255.255.255.26",
"255.255.255.27"
};
String[] ipAddressesNotBeMatched = {
"0011:2233:4455:6677:8899:aabb:ccdd:eefe",
"2001:db8::ff00:42:832a",
"::1",
"::4",
"::8",
"::b",
"::e",
"2400:6500:FF00::36FB:1F81",
"2400:6500:FF00::36FB:1F86",
"2400:6500:FF00::36FB:1F8a",
"2400:6500:FF00::36FB:1F8D",
"2400:6500:FF00::36FB:1F8E",
"54.240.196.254",
"255.255.255.254",
"255.255.255.1",
"255.255.255.6",
"255.255.255.11",
"255.255.255.17",
"255.255.255.28",
"255.255.255.29"
};
String sourceTemplate = "{" +
" \"detail\": {" +
" \"eventName\": [" +
" \"UpdateService\"" +
" ],\n" +
" \"eventSource\": [\n" +
" \"ecs.amazonaws.com\"" +
" ]," +
" \"sourceIPAddress\": [" +
" \"%s\"" +
" ]\n" +
" },\n" +
" \"detail-type\": [" +
" \"AWS API Call via CloudTrail\"" +
" ],\n" +
" \"source\": [" +
" \"aws.ecs\"" +
" ]" +
"}";
Machine machine = new Machine();
for (String ip : ipAddressesToBeMatched) {
machine.addRule(ip, String.format(sourceTemplate, ip));
}
for (String ip : ipAddressesToBeMatched) {
List<String> rules =machine.rulesForJSONEvent(String.format(sourceTemplate, ip));
assertEquals(ip, rules.get(0));
}
for (String ip : ipAddressesNotBeMatched) {
List<String> rules =machine.rulesForJSONEvent(String.format(sourceTemplate, ip));
assertEquals(0, rules.size());
}
for (String ip : ipAddressesToBeMatched) {
machine.deleteRule(ip, String.format(sourceTemplate, ip));
}
assertTrue(machine.isEmpty());
}
@Test
public void testExists() throws Exception {
String rule1 = "{\"abc\": [{\"exists\": false}]}";
String rule2 = "{\"abc\": [{\"exists\": true}]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event1 = "{\"abc\": \"xyz\"}";
String event2 = "{\"xyz\": \"abc\"}";
List<String> matches = machine.rulesForEvent(event1);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule2"));
matches = machine.rulesForEvent(event2);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testAddAndDeleteTwoRulesSamePattern() throws Exception {
final Machine machine = new Machine();
String event = "{\n" +
" \"x\": \"y\"\n" +
"}";
String rule1 = "{\n" +
" \"x\": [ \"y\" ]\n" +
"}";
String rule2 = "{\n" +
" \"x\": [ \"y\" ]\n" +
"}";
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
List<String> found = machine.rulesForEvent(event);
assertEquals(2, found.size());
assertTrue(found.contains("rule1"));
assertTrue(found.contains("rule2"));
machine.deleteRule("rule1", rule1);
found = machine.rulesForEvent(event);
assertEquals(1, found.size());
machine.deleteRule("rule2", rule2);
found = machine.rulesForEvent(event);
assertEquals(0, found.size());
assertTrue(machine.isEmpty());
}
@Test
public void testAddAndDeleteTwoRulesSameCaseInsensitivePatternEqualsIgnoreCase() throws Exception {
final Machine machine = new Machine();
String event = "{\n" +
" \"x\": \"y\"\n" +
"}";
String rule1 = "{\n" +
" \"x\": [ { \"equals-ignore-case\": \"y\" } ]\n" +
"}";
String rule2 = "{\n" +
" \"x\": [ { \"equals-ignore-case\": \"Y\" } ]\n" +
"}";
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
List<String> found = machine.rulesForEvent(event);
assertEquals(2, found.size());
assertTrue(found.contains("rule1"));
assertTrue(found.contains("rule2"));
machine.deleteRule("rule1", rule1);
found = machine.rulesForEvent(event);
assertEquals(1, found.size());
machine.deleteRule("rule2", rule2);
found = machine.rulesForEvent(event);
assertEquals(0, found.size());
assertTrue(machine.isEmpty());
}
@Test
public void testDuplicateKeyLastOneWins() throws Exception {
final Machine machine = new Machine();
String event1 = "{\n" +
" \"x\": \"y\"\n" +
"}";
String event2 = "{\n" +
" \"x\": \"z\"\n" +
"}";
String rule1 = "{\n" +
" \"x\": [ \"y\" ],\n" +
" \"x\": [ \"z\" ]\n" +
"}";
machine.addRule("rule1", rule1);
List<String> found = machine.rulesForEvent(event1);
assertEquals(0, found.size());
found = machine.rulesForEvent(event2);
assertEquals(1, found.size());
assertTrue(found.contains("rule1"));
}
@Test
public void testSharedNameState() throws Exception {
// "bar" will be the first key (alphabetical)
String rule1 = "{\"foo\":[\"a\"], \"bar\":[\"x\", \"y\"]}";
String rule2 = "{\"foo\":[\"a\", \"b\"], \"bar\":[\"x\"]}";
String rule3 = "{\"foo\":[\"a\", \"b\"], \"bar\":[\"y\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
machine.addRule("rule3", rule3);
String event = "{" +
"\"foo\": \"a\"," +
"\"bar\": \"x\"" +
"}";
// Ensure rule3 does not piggyback on rule1's shared NameState accessed by both "x" and "y" for "bar"
List<String> matches = machine.rulesForEvent(event);
assertEquals(2, matches.size());
assertTrue(matches.contains("rule1"));
assertTrue(matches.contains("rule2"));
}
@Test
public void testRuleDeletionFromSharedNameState() throws Exception {
// "bar" will be the first key (alphabetical) and both rules have a match on "x", leading to a shared NameState
String rule1 = "{\"foo\":[\"a\"], \"bar\":[\"x\", \"y\"]}";
String rule2 = "{\"foo\":[\"b\"], \"bar\":[\"x\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event1 = "{" +
"\"foo\": \"a\"," +
"\"bar\": \"x\"" +
"}";
String event2 = "{" +
"\"foo\": \"a\"," +
"\"bar\": \"y\"" +
"}";
List<String> matches = machine.rulesForEvent(event1);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
matches = machine.rulesForEvent(event2);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
// Shared NameState will remain as it is used by rule1
machine.deleteRule("rule2", rule2);
matches = machine.rulesForEvent(event1);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
matches = machine.rulesForEvent(event2);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
// "y" also leads to the shared NameState. The shared NameState will get extended by rule2's "foo" field. By
// checking that only events with a "bar" of "y" and not a "bar" of "x", we verify that no remnants of the
// original rule2 were left in the shared NameState.
String rule2b = "{\"foo\":[\"a\"], \"bar\":[\"y\"]}";
machine.addRule("rule2", rule2b);
matches = machine.rulesForEvent(event1);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
matches = machine.rulesForEvent(event2);
assertEquals(2, matches.size());
assertTrue(matches.contains("rule1"));
assertTrue(matches.contains("rule2"));
}
@Test
public void testPrefixRuleDeletionFromSharedNameState() throws Exception {
// "bar", "foo", "zoo" will be the key order (alphabetical)
String rule1 = "{\"zoo\":[\"1\"], \"foo\":[\"a\"], \"bar\":[\"x\"]}";
String rule2 = "{\"foo\":[\"a\"], \"bar\":[\"x\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"zoo\": \"1\"," +
"\"foo\": \"a\"," +
"\"bar\": \"x\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForEvent(event);
assertEquals(2, matches.size());
assertTrue(matches.contains("rule1"));
assertTrue(matches.contains("rule2"));
// Delete rule2, which is a subpath/prefix of rule1, and ensure full path still exists for rule1 to match
machine.deleteRule("rule2", rule2);
matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testDifferentValuesFromOrRuleBothGoThroughSharedNameState() throws Exception {
// "bar", "foo", "zoo" will be the key order (alphabetical)
String rule1 = "{\"foo\":[\"a\"], \"bar\":[\"x\", \"y\"]}";
String rule2 = "{\"zoo\":[\"1\"], \"bar\":[\"x\"]}";
String rule2b = "{\"foo\":[\"a\"], \"bar\":[\"y\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
machine.addRule("rule2", rule2b);
String event = "{" +
"\"foo\": \"a\"," +
"\"bar\": \"x\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testDifferentValuesFromExplicitOrRuleBothGoThroughSharedNameState() throws Exception {
// "bar", "foo", "zoo" will be the key order (alphabetical)
String rule1 = "{\"foo\":[\"a\"], \"bar\":[\"x\", \"y\"]}";
String rule2 = "{\"$or\":[{\"zoo\":[\"1\"], \"bar\":[\"x\"]}, {\"foo\":[\"a\"], \"bar\":[\"y\"]}]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"foo\": \"a\"," +
"\"bar\": \"x\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testRuleIsSingleItemSubsetOfOtherRule() throws Exception {
// Second rule added pertains to same field as first rule but has a subset of the allowed values.
String rule1 = "{\"foo\": [\"a\", \"b\", \"c\"]}";
String rule2 = "{\"foo\": [\"b\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"foo\": \"a\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testRuleIsMultipleItemSubsetOfOtherRule() throws Exception {
// Second rule added pertains to same field as first rule but has a subset of the allowed values.
String rule1 = "{\"foo\": [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"]}";
String rule2 = "{\"foo\": [\"b\", \"d\", \"f\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"foo\": \"e\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testRuleIsSingleItemSubsetOfOtherRuleWithPrecedingKey() throws Exception {
// Second rule added pertains to same field as first rule but has a subset of the allowed values.
String rule1 = "{\"bar\": [\"1\"], \"foo\": [\"a\", \"b\", \"c\"]}";
String rule2 = "{\"bar\": [\"1\"], \"foo\": [\"b\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"bar\": \"1\"," +
"\"foo\": \"a\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testRuleIsMultipleItemSubsetOfOtherRuleWithPrecedingKey() throws Exception {
// Second rule added pertains to same field as first rule but has a subset of the allowed values.
String rule1 = "{\"bar\": [\"1\"], \"foo\": [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"]}";
String rule2 = "{\"bar\": [\"1\"], \"foo\": [\"b\", \"d\", \"f\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"bar\": \"1\"," +
"\"foo\": \"e\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testRuleIsSingleItemSubsetOfOtherRuleWithFollowingKey() throws Exception {
// Second rule added pertains to same field as first rule but has a subset of the allowed values.
String rule1 = "{\"zoo\": [\"1\"], \"foo\": [\"a\", \"b\", \"c\"]}";
String rule2 = "{\"zoo\": [\"1\"], \"foo\": [\"b\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"zoo\": \"1\"," +
"\"foo\": \"a\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testRuleIsMultipleItemSubsetOfOtherRuleWithFollowingKey() throws Exception {
// Second rule added pertains to same field as first rule but has a subset of the allowed values.
String rule1 = "{\"zoo\": [\"1\"], \"foo\": [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"]}";
String rule2 = "{\"zoo\": [\"1\"], \"foo\": [\"b\", \"d\", \"f\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"zoo\": \"1\"," +
"\"foo\": \"e\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testExistsFalseAsFinalKeyAfterSharedNameState() throws Exception {
// Second rule added uses same NameState for bar, but then has a final key, foo, that must not exist.
String rule1 = "{\"bar\": [\"a\", \"b\"]}";
String rule2 = "{\"bar\": [\"b\"], \"foo\": [{\"exists\": false}]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"bar\": \"a\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testExistsTrueAsFinalKeyAfterSharedNameState() throws Exception {
// Second rule added uses same NameState for bar, but then has a final key, foo, that must exist.
String rule1 = "{\"bar\": [\"a\", \"b\"]}";
String rule2 = "{\"bar\": [\"b\"], \"foo\": [{\"exists\": true}]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"bar\": \"a\"," +
"\"foo\": \"1\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testExistsFalseNameStateSharedWithSpecificValueMatch() throws Exception {
// First rule adds a NameState for exists=false. Second rule will use this same NameState and add a value of "1"
// to it. Third rule will now use this same shared NameState as well due to its value of "1".
String rule1 = "{\"foo\": [\"a\"], \"bar\": [{\"exists\": false}]}";
String rule2 = "{\"foo\": [\"b\"], \"bar\": [{\"exists\": false}, \"1\"]}";
String rule3 = "{\"foo\": [\"a\"], \"bar\": [\"1\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
machine.addRule("rule3", rule3);
String event = "{" +
"\"foo\": \"a\"" +
"}";
// Only rule1 should match
List<String> matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testExistsTrueNameStateSharedWithSpecificValueMatch() throws Exception {
// First rule adds a NameState for exists=true. Second rule will use this same NameState and add a value of "1"
// to it. Third rule will now use this same shared NameState as well due to its value of "1".
String rule1 = "{\"foo\": [\"a\"], \"bar\": [{\"exists\": true}]}";
String rule2 = "{\"foo\": [\"b\"], \"bar\": [{\"exists\": true}, \"1\"]}";
String rule3 = "{\"foo\": [\"a\"], \"bar\": [\"1\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
machine.addRule("rule3", rule3);
String event = "{" +
"\"foo\": \"a\"," +
"\"bar\": \"1\"" +
"}";
// Only rule1 and rule3 should match
List<String> matches = machine.rulesForEvent(event);
assertEquals(2, matches.size());
assertTrue(matches.contains("rule1"));
assertTrue(matches.contains("rule3"));
}
@Test
public void testInitialSharedNameStateWithTwoMustNotExistsIsTerminalForOnlyOne() throws Exception {
// Initial NameState has two different (bar and foo) exists=false patterns. One is terminal, whereas the other
// leads to another NameState with another key (zoo).
String rule1 = "{\"bar\": [{\"exists\": false}]}";
String rule2 = "{\"foo\": [{\"exists\": false}], \"zoo\": [\"a\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{" +
"\"zoo\": \"a\"" +
"}";
List<String> matches = machine.rulesForEvent(event);
assertEquals(2, matches.size());
assertTrue(matches.contains("rule1"));
assertTrue(matches.contains("rule2"));
}
@Test
public void testSharedNameStateForMultipleAnythingButPatterns() throws Exception {
// Every event will match this rule because any bar that is "a" cannot also be "b".
String rule1 = "{\"bar\": [{\"anything-but\": \"a\"}, {\"anything-but\": \"b\"}]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
String event = "{\"bar\": \"b\"}";
List<String> matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testSharedNameStateWithTwoSubRulesDifferingAtFirstNameState() throws Exception {
// Two different sub-rules here with a NameState after bar and after foo: (bar=1, foo=a) and (bar=2, foo=a).
String rule1 = "{\"$or\": [{\"bar\": [\"1\"]}, {\"bar\": [\"2\"]}]," +
"\"foo\": [\"a\"] }";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
String event = "{\"bar\": \"2\"," +
"\"foo\": \"a\"}";
List<String> matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule1"));
}
@Test
public void testInitialSharedNameStateAlreadyExistsWithNonLeadingValue() throws Exception {
// When rule2 is added, a NameState will already exist for bar=b. Adding bar=a will lead to a new initial
// NameState, and then the existing NameState for bar=b will be encountered.
String rule1 = "{\"bar\" :[\"b\"], \"foo\": [\"c\"]}";
String rule2 = "{\"bar\": [\"a\", \"b\"], \"foo\": [\"c\"]}";
Machine machine = new Machine();
machine.addRule("rule1", rule1);
machine.addRule("rule2", rule2);
String event = "{\"bar\": \"a\"," +
"\"foo\": \"c\"}";
List<String> matches = machine.rulesForEvent(event);
assertEquals(1, matches.size());
assertTrue(matches.contains("rule2"));
}
@Test
public void testApproxSizeForSimplestPossibleMachine() throws Exception {
String rule1 = "{ \"a\" : [ 1 ] }";
String rule2 = "{ \"b\" : [ 2 ] }";
String rule3 = "{ \"c\" : [ 3 ] }";
Machine machine = new Machine();
assertEquals(1, machine.approximateObjectCount(10000));
machine.addRule("r1", rule1);
assertEquals(23, machine.approximateObjectCount(10000));
machine.addRule("r2", rule2);
assertEquals(44, machine.approximateObjectCount(10000));
machine.addRule("r3", rule3);
assertEquals(65, machine.approximateObjectCount(10000));
}
@Test
public void testApproxSizeForDuplicatedRules() throws Exception {
String rule1 = "{ \"a\" : [ 1, 2, 3 ], \"b\" : [4, 5, 6] }";
Machine machine = new Machine();
machine.addRule("r1", rule1);
assertEquals(80, machine.approximateObjectCount(10000));
// Adding the same rule multiple times should not increase object count
for (int i = 0; i < 100; i++) {
machine.addRule("r1", rule1);
}
assertEquals(80, machine.approximateObjectCount(10000));
}
@Test
public void testApproxSizeForAddingDuplicateRuleExceptTerminalKeyIsSubset() throws Exception {
String rule1a = "{ \"a\" : [ 1, 2, 3 ], \"b\" : [4, 5, 6] }";
String rule1b = "{ \"a\" : [ 1, 2, 3 ], \"b\" : [4, 5] }";
Machine machine = new Machine();
machine.addRule("r1", rule1a);
assertEquals(80, machine.approximateObjectCount(10000));
// Adding rule with terminal key having subset of values will be treated as same rule and thus increase size
machine.addRule("r1", rule1b);
assertEquals(80, machine.approximateObjectCount(10000));
}
@Test
public void testApproxSizeForAddingDuplicateRuleExceptNonTerminalKeyIsSubset() throws Exception {
String rule1a = "{ \"a\" : [ 1, 2, 3 ], \"b\" : [4, 5, 6] }";
String rule1b = "{ \"a\" : [ 1, 2 ], \"b\" : [4, 5, 6] }";
Machine machine = new Machine();
machine.addRule("r1", rule1a);
assertEquals(80, machine.approximateObjectCount(10000));
// Adding rule with non-terminal key having subset of values will be treated as same rule and not affect count
machine.addRule("r1", rule1b);
assertEquals(80, machine.approximateObjectCount(10000));
}
@Test
public void testApproxSizeForAddingDuplicateRuleExceptTerminalKeyIsSuperset() throws Exception {
String rule1a = "{ \"a\" : [ 1, 2, 3 ], \"b\" : [4, 5, 6] }";
String rule1b = "{ \"a\" : [ 1, 2, 3 ], \"b\" : [4, 5, 6, 7] }";
Machine machine = new Machine();
machine.addRule("r1", rule1a);
assertEquals(80, machine.approximateObjectCount(10000));
// Adding rule with terminal key having superset of values will be treated as new rule and increase count
machine.addRule("r1", rule1b);
assertEquals(90, machine.approximateObjectCount(10000));
}
@Test
public void testApproxSizeForAddingDuplicateRuleExceptNonTerminalKeyIsSuperset() throws Exception {
String rule1a = "{ \"a\" : [ 1, 2, 3 ], \"b\" : [4, 5, 6] }";
String rule1b = "{ \"a\" : [ 1, 2, 3, 7 ], \"b\" : [4, 5, 6] }";
Machine machine = new Machine();
machine.addRule("r1", rule1a);
assertEquals(80, machine.approximateObjectCount(10000));
// Adding rule with non-terminal key having superset of values will be treated as new rule and increase count
machine.addRule("r1", rule1b);
assertEquals(90, machine.approximateObjectCount(10000));
}
@Test
public void testSuffixChineseMatch() throws Exception {
Machine m = new Machine();
String rule = "{\n" +
" \"status\": {\n" +
" \"weatherText\": [{\"suffix\": \"统治者\"}]\n" +
" }\n" +
"}";
String eventStr ="{\n" +
" \"status\": {\n" +
" \"weatherText\": \"事件统治者\",\n" +
" \"pm25\": 23\n" +
" }\n" +
"}";
m.addRule("r1", rule);
List<String> matchRules = m.rulesForEvent(eventStr);
assertEquals(1, matchRules.size());
}
@Test(timeout = 500)
public void testApproximateSizeDoNotTakeForeverForRulesWithNumericMatchers() throws Exception {
Machine machine = new Machine();
machine.addRule("rule",
"{\n" +
" \"a\": [{ \"numeric\": [\"<\", 0] }],\n" +
" \"b\": { \"b1\": [{ \"numeric\": [\"=\", 3] }] },\n" +
" \"c\": [{ \"numeric\": [\">\", 50] }]\n" +
"}");
assertEquals(517, machine.approximateObjectCount(10000));
}
@Test
public void testApproximateSizeForDifferentBasicRules() throws Exception {
Machine machine = new Machine();
assertEquals(1, machine.approximateObjectCount(10000));
machine.addRule("single-rule", "{ \"key\" : [ \"value\" ] }");
assertEquals(8, machine.approximateObjectCount(10000));
// every new rule also is considered as part of the end-state
machine = new Machine();
for(int i = 0 ; i < 1000; i ++) {
machine.addRule("lots-rule-" + i, "{ \"key\" : [ \"value\" ] }");
}
assertEquals(1007, machine.approximateObjectCount(10000));
// new unique rules create new states
machine = new Machine();
for(int i = 0 ; i < 1000; i ++) {
machine.addRule("lots-key-values-" + i, "{ \"many-kv-" + i + "\" : [ \"value" + i + "\" ] }");
}
assertEquals(7001, machine.approximateObjectCount(10000));
// new unique rule keys create same states as unique rules
machine = new Machine();
for(int i = 0 ; i < 1000; i ++) {
machine.addRule("lots-keys-" + i, "{ \"many-key-" + i + "\" : [ \"value\" ] }");
}
assertEquals(6002, machine.approximateObjectCount(10000));
// new unique rule with many values are smaller
machine = new Machine();
for(int i = 0 ; i < 1000; i ++) {
machine.addRule("lots-values-" + i, "{ \"many-values-key\" : [ \"value" + i + " \" ] }");
}
assertEquals(5108, machine.approximateObjectCount(10000));
}
@Test
public void testApproximateSizeWhenCapped() throws Exception {
Machine machine = new Machine();
assertEquals(0, machine.approximateObjectCount(0));
assertEquals(1, machine.approximateObjectCount(1));
assertEquals(1, machine.approximateObjectCount(10));
machine.addRule("single-rule", "{ \"key\" : [ \"value\" ] }");
assertEquals(1, machine.approximateObjectCount(1));
assertEquals(8, machine.approximateObjectCount(10));
for(int i = 0 ; i < 100000; i ++) {
machine.addRule("lots-rule-" + i, "{ \"key\" : [ \"value\" ] }");
}
for(int i = 0 ; i < 100000; i ++) {
machine.addRule("lots-key-values-" + i, "{ \"many-kv-" + i + "\" : [ \"value" + i + "\" ] }");
}
for(int i = 0 ; i < 100000; i ++) {
machine.addRule("lots-keys-" + i, "{ \"many-key-" + i + "\" : [ \"value\" ] }");
}
for(int i = 0 ; i < 100000; i ++) {
machine.addRule("lots-values-" + i, "{ \"many-values-key\" : [ \"value" + i + " \" ] }");
}
assertApproximateCountWithTime(machine, 1000, 1000, 150);
assertApproximateCountWithTime(machine, Integer.MAX_VALUE, 1910015, 5000);
}
private void assertApproximateCountWithTime(Machine machine, int maxThreshold, int expectedValue, int maxExpectedDurationMillis) {
final Instant start = Instant.now();
assertEquals(expectedValue, machine.approximateObjectCount(maxThreshold));
assertTrue(maxExpectedDurationMillis > Duration.between(start, Instant.now()).toMillis());
}
@Test
public void testApproximateSizeForRulesManyEventNameArrayElements() throws Exception {
Machine machine = new Machine();
machine.addRule("rule-with-three-element",
"{\n" +
" \"source\": [\"Source\"],\n" +
" \"detail\": {\n" +
" \"eventName\": [\"Name1\",\"Name2\",\"Name3\"]\n" +
" }\n" +
"}");
assertEquals(25, machine.approximateObjectCount(10000));
machine.addRule("rule-with-six-elements",
"{\n" +
" \"source\": [\"Source\"],\n" +
" \"detail\": {\n" +
" \"eventName\": [\"Name1\",\"Name2\",\"Name3\",\"Name4\",\"Name5\",\"Name6\"]\n" +
" }\n" +
"}");
assertEquals(35, machine.approximateObjectCount(10000));
machine.addRule("rule-with-six-more-elements",
"{\n" +
" \"source\": [\"Source\"],\n" +
" \"detail\": {\n" +
" \"eventName\": [\"Name7\",\"Name8\",\"Name9\",\"Name10\",\"Name11\",\"Name12\"]\n" +
" }\n" +
"}");
assertEquals(60, machine.approximateObjectCount(10000));
}
@Test
public void testApproximateSizeForRulesManySouceAndEventNameArrayElements() throws Exception {
Machine machine = new Machine();
machine.addRule("first-rule",
"{\n" +
" \"source\": [\"Source1\",\"Source2\"],\n" +
" \"detail\": {\n" +
" \"eventName\": [\"Name1\",\"Name2\",\"Name3\"]\n" +
" }\n" +
"}");
assertEquals(35, machine.approximateObjectCount(10000));
machine.addRule("rule-with-two-more-source-and-eventNames",
"{\n" +
" \"source\": [\"Source1\",\"Source2\", \"Source3\",\"Source4\"],\n" +
" \"detail\": {\n" +
" \"eventName\": [\"Name1\",\"Name2\",\"Name3\",\"Name4\",\"Name5\"]\n" +
" }\n" +
"}");
assertEquals(48, machine.approximateObjectCount(10000));
machine.addRule("rule-with-more-unique-source-and-eventNames",
"{\n" +
" \"source\": [\"Source5\",\"Source6\", \"Source7\",\"Source8\"],\n" +
" \"detail\": {\n" +
" \"eventName\": [\"Name6\",\"Name7\",\"Name8\",\"Name9\",\"Name10\"]\n" +
" }\n" +
"}");
assertEquals(87, machine.approximateObjectCount(10000));
}
@Test
public void testLargeArrayRulesVsOR() throws Exception {
Machine machine = new Machine();
machine.addRule("rule1",
"{\n" +
" \"detail-type\" : [ \"jV4 Tij ny6H K9Z 6pALqePKFR\", \"jV4 RbfEU04 dSyRZH K9Z 6pALqePKFR\" ],\n" +
" \"source\" : [ \"e9C1c0.qRk\", \"e9C1c0.3FD\", \"e9C1c0.auf\", \"e9C1c0.L6kj0T\", \"e9C1c0.sTEi\", \"e9C1c0.ATnVwRJH4\", \"e9C1c0.gOTbM9V\", \"e9C1c0.6Foy06YCE03DGH\", \"e9C1c0.UD7QBnjzEQNRODz\", \"e9C1c0.DVTtb8c\", \"e9C1c0.hmXIsf6p\", \"e9C1c0.ANK\" ],\n" +
" \"detail\" : {\n" +
" \"eventSource\" : [ \"qRk.BeMfKctgml0y.s1x\", \"3FD.BeMfKctgml0y.s1x\", \"auf.BeMfKctgml0y.s1x\", \"L6kj0T.BeMfKctgml0y.s1x\", \"sTEi.BeMfKctgml0y.s1x\", \"ATnVwRJH4.BeMfKctgml0y.s1x\", \"gOTbM9V.BeMfKctgml0y.s1x\", \"6Foy06YCE03DGH.BeMfKctgml0y.s1x\", \"UD7QBnjzEQNRODz.BeMfKctgml0y.s1x\", \"DVTtb8c.BeMfKctgml0y.s1x\", \"hmXIsf6p.BeMfKctgml0y.s1x\", \"ANK.BeMfKctgml0y.s1x\" ],\n" +
" \"eventName\" : [ \"QK66sO0I4REUYb\", \"62HIWfGqrGTXpFotMy9xA\", \"7ucBUowmZxyA\", \"uo3piGS6CMHlcHDIzyNSr\", \"KCflDTVvp6krjt\", \"a9QrxONB6ZuU6m\", \"n8ASzCtTR8gjtkUtb\", \"bGZ94i5383n7hOOFF3XEkG3aUUY\", \"Dcw7pR9ikAMdOsAO6\", \"ccIkzb5umk6ffsWxT\", \"CrigfFIQshKoTi27S\", \"Tzi0k780pMtBV5FJV\", \"YS5tzAqzICdIajJcv\", \"ziLYvUKGSf1aqRZxU3ySvIYJ1HAQeF\", \"OgDBotcyXlPBJiGkzgEvx62KgIZ5Fc\", \"4tng21yDnIL8LJhaOptRG4d0yFm6WN\", \"aKnV3yMDVj2lq2Vfb\", \"HUhCGNVADyoDmWD9aCyzZe\", \"QHoYhQ1SDFMUNST7eHp4at\", \"QqCH8sS0zyQyPCVRitbCLHD0FEStOFXEQK\", \"YAzYOUP5qAqRiXLvKi2FGHXwOzLRTqF\", \"cyE74DukyW8Jx89B0mYfuuSwAhMV2XA\", \"5TGldWFzELapQ1gAaWbmzdozlLDy2PI\", \"9iXtpCTGB97r9QA\", \"oSZp5vZ52aD9wBcwIi\", \"OuP0M08FAxvonc5Pj2WTUEi\", \"LoQpJl4NmLXpzYou8FKT32s\", \"NUIhlIsVoqwXmXJKYYIo\", \"ZO0QKPO7T3Ic0WFaZzx5LkX\", \"ryuyOUuRIxS6fhIOtepxTgj\", \"l4x1SJQRJTAl0p3aQOc\", \"5wIJAxf3zR89u5WiKwQ\" ]\n" +
" }\n" +
"}");
machine.addRule("rule2",
"{\n" +
" \"detail-type\" : [ \"jV4 Tij ny6H K9Z 6pALqePKFR\", \"jV4 RbfEU04 dSyRZH K9Z 6pALqePKFR\" ],\n" +
" \"source\" : [ \"0K9kV5.qRk\", \"0K9kV5.3FD\", \"0K9kV5.auf\", \"0K9kV5.L6kj0T\", \"0K9kV5.sTEi\", \"0K9kV5.ATnVwRJH4\", \"0K9kV5.gOTbM9V\", \"0K9kV5.6Foy06YCE03DGH\", \"0K9kV5.UD7QBnjzEQNRODz\", \"0K9kV5.DVTtb8c\", \"0K9kV5.hmXIsf6p\", \"0K9kV5.ANK\" ],\n" +
" \"detail\" : {\n" +
" \"eventSource\" : [ \"qRk.A2Ptm07Ncrg2.s1x\", \"3FD.A2Ptm07Ncrg2.s1x\", \"auf.A2Ptm07Ncrg2.s1x\", \"L6kj0T.A2Ptm07Ncrg2.s1x\", \"sTEi.A2Ptm07Ncrg2.s1x\", \"ATnVwRJH4.A2Ptm07Ncrg2.s1x\", \"gOTbM9V.A2Ptm07Ncrg2.s1x\", \"6Foy06YCE03DGH.A2Ptm07Ncrg2.s1x\", \"UD7QBnjzEQNRODz.A2Ptm07Ncrg2.s1x\", \"DVTtb8c.A2Ptm07Ncrg2.s1x\", \"hmXIsf6p.A2Ptm07Ncrg2.s1x\", \"ANK.A2Ptm07Ncrg2.s1x\" ],\n" +
" \"eventName\" : [ \"eqzMRqwMielUtv\", \"bIdx6KYCn3lpviFOEFWda\", \"oM0D40U9s6En\", \"pRqp3WZkboetrmWci51p6\", \"Sc0UwrhEureEzQ\", \"b0V8ou0Lp6PrEu\", \"VIC8D82ll1FIstePk\", \"qOBBxX2kntyHDwCSGBcOd8yloVo\", \"YXPayoGQlGoFk6nkR\", \"zGMY1DfzOQvwMNmK4\", \"xLUKKGRNglfr7RzbW\", \"wbPkaR8SjIKOWOFKU\", \"U2LAfXHBUgQ9BK6OE\", \"UsXW3IKWtjUun81O5A2RvYipYYiWPf\", \"1WMPVZQFB44o4hS4qsdtv1DrHOg6le\", \"NAZAKdRXGpyYF8aVNTvsQYB4mcevPP\", \"ZKbsTPS4xbrnbP3xG\", \"w52EAqErWZ49EcaFQBN3h7\", \"OI6eIIiVmrxJOVhiq7IENU\", \"QqCH8sS0zyQyPCVRitbCLHD0FEStOFXEQK\", \"EX8qET0anoJJMvoEcGLYMZJvkzSLch4\", \"cyE74DukyW8Jx89B0mYfuuSwAhMV2XA\", \"G2hyHJGzf41Q0hDdKVZ3oeLy4ZJl32S\", \"C6kqFl3fleB3zIF\", \"4fx5kxFt2KucxvrG0s\", \"1MewNMgaPjslx4l5ISCRWhn\", \"VI7aNjEq4a1J6QYF0wQ2pV6\", \"ns4SneqAxCuWNVoepM2Q\", \"1OdzCqyk4cQtQrVOd2Zf60v\", \"0MjQEBo5tW89oNlWktVbRfH\", \"soKlU8SKloI9YCAcssn\", \"3IqglcGMMVfJAin4tBg\" ]\n" +
" }\n" +
"}");
machine.addRule("rule3",
"{\n" +
" \"detail-type\" : [ \"jV4 Tij ny6H K9Z 6pALqePKFR\", \"jV4 RbfEU04 dSyRZH K9Z 6pALqePKFR\" ],\n" +
" \"source\" : [ \"oeoNrI.qRk\", \"oeoNrI.3FD\", \"oeoNrI.auf\", \"oeoNrI.L6kj0T\", \"oeoNrI.sTEi\", \"oeoNrI.ATnVwRJH4\", \"oeoNrI.gOTbM9V\", \"oeoNrI.6Foy06YCE03DGH\", \"oeoNrI.UD7QBnjzEQNRODz\", \"oeoNrI.DVTtb8c\", \"oeoNrI.hmXIsf6p\", \"oeoNrI.ANK\" ],\n" +
" \"detail\" : {\n" +
" \"eventSource\" : [ \"qRk.6SOVnnlY9Y2B.s1x\", \"3FD.6SOVnnlY9Y2B.s1x\", \"auf.6SOVnnlY9Y2B.s1x\", \"L6kj0T.6SOVnnlY9Y2B.s1x\", \"sTEi.6SOVnnlY9Y2B.s1x\", \"ATnVwRJH4.6SOVnnlY9Y2B.s1x\", \"gOTbM9V.6SOVnnlY9Y2B.s1x\", \"6Foy06YCE03DGH.6SOVnnlY9Y2B.s1x\", \"UD7QBnjzEQNRODz.6SOVnnlY9Y2B.s1x\", \"DVTtb8c.6SOVnnlY9Y2B.s1x\", \"hmXIsf6p.6SOVnnlY9Y2B.s1x\", \"ANK.6SOVnnlY9Y2B.s1x\" ],\n" +
" \"eventName\" : [ \"wSjB92xeOBe2jf\", \"8owQcNCzpfsEjvv0zslQc\", \"XHSVWCs93l4m\", \"80jswkMW46QOp9ZasRC9i\", \"XoZakwvaiEbgvF\", \"A4oqVIUG1rS9G7\", \"9mU5hzwkFxHKDpo4A\", \"hI7uk7VTJB6gjcsRUoUIxuBPJaF\", \"UUFHA8cBHOvHk3lfO\", \"3cKTrqLEH5IMlsMDv\", \"TFaY7vCJG9EsxsjVd\", \"ZawowkBcOxdUsfgEs\", \"yOFNW7sxv0TNoMO6m\", \"Hp0AcGKGUlvM8lCgZqpiwOemCb2HSs\", \"SLDqS9ycYaKhJlzAdFC2bS92zrTpOO\", \"nAs966ixa5JQ9u2UlQOWh73PNMWehY\", \"tznZRlX80kDVIC8gH\", \"icLnBAt7pdp9aNDvOnqmMN\", \"NQHtpcQPybOVV0ZU4HInha\", \"QqCH8sS0zyQyPCVRitbCLHD0FEStOFXEQK\", \"6PXEaDOnRk7nmP6EhA9t2OE9g75eMmI\", \"cyE74DukyW8Jx89B0mYfuuSwAhMV2XA\", \"6n4FMCgGV1D09pLFanLGObbRBc1MXSH\", \"gk3lANJe2ZNiCdu\", \"5bL8gLCE5CE8pS0kRR\", \"hHZciQGDRCFKqf5S206HnMM\", \"HT14rl37Pa0ADgY5diV4cUa\", \"VcNAACSECOywtvlq42KR\", \"UhmN71rqtx6x0PagQr9Y4oU\", \"KX6z6AN1ApQq0HsSXbsyXgE\", \"RIo0rQN1PwKHiGnHcHP\", \"lhavqRt32TNqxjnfT2P\" ]\n" +
" }\n" +
"}");
assertEquals(811, machine.approximateObjectCount(150000));
machine = new Machine();
machine.addRule("rule1",
"{\n" +
" \"$or\" : [ {\n" +
" \"source\" : [ \"e9C1c0.qRk\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"QK66sO0I4REUYb\", \"62HIWfGqrGTXpFotMy9xA\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"e9C1c0.3FD\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"7ucBUowmZxyA\", \"uo3piGS6CMHlcHDIzyNSr\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"e9C1c0.auf\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"KCflDTVvp6krjt\", \"ixHBhtn3T99\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"e9C1c0.L6kj0T\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"Yuq5PWrpi8h2Hi\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"e9C1c0.sTEi\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"bGZ94i5383n7hOOFF3XEkG3aUUY\", \"Dcw7pR9ikAMdOsAO6\", \"ccIkzb5umk6ffsWxT\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"e9C1c0.ATnVwRJH4\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"CrigfFIQshKoTi27S\", \"Tzi0k780pMtBV5FJV\", \"YS5tzAqzICdIajJcv\", \"ziLYvUKGSf1aqRZxU3ySvIYJ1HAQeF\", \"OgDBotcyXlPBJiGkzgEvx62KgIZ5Fc\", \"4tng21yDnIL8LJhaOptRG4d0yFm6WN\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"e9C1c0.gOTbM9V\", \"e9C1c0.6Foy06YCE03DGH\", \"e9C1c0.UD7QBnjzEQNRODz\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"aKnV3yMDVj2lq2Vfb\", \"HUhCGNVADyoDmWD9aCyzZe\", \"QHoYhQ1SDFMUNST7eHp4at\", \"QqCH8sS0zyQyPCVRitbCLHD0FEStOFXEQK\", \"YAzYOUP5qAqRiXLvKi2FGHXwOzLRTqF\", \"cyE74DukyW8Jx89B0mYfuuSwAhMV2XA\", \"5TGldWFzELapQ1gAaWbmzdozlLDy2PI\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"DVTtb8c.BeMfKctgml0y.s1x\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"9iXtpCTGB97r9QA\", \"oSZp5vZ52aD9wBcwIi\", \"OuP0M08FAxvonc5Pj2WTUEi\", \"LoQpJl4NmLXpzYou8FKT32s\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"e9C1c0.hmXIsf6p\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"NUIhlIsVoqwXmXJKYYIo\", \"ZO0QKPO7T3Ic0WFaZzx5LkX\", \"ryuyOUuRIxS6fhIOtepxTgj\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"e9C1c0.ANK\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"l4x1SJQRJTAl0p3aQOc\", \"5wIJAxf3zR89u5WiKwQ\" ]\n" +
" }\n" +
" } ]\n" +
"}");
machine.addRule("rule2",
"{\n" +
" \"$or\" : [ {\n" +
" \"source\" : [ \"0K9kV5.qRk\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"eqzMRqwMielUtv\", \"bIdx6KYCn3lpviFOEFWda\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"0K9kV5.3FD\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"oM0D40U9s6En\", \"pRqp3WZkboetrmWci51p6\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"0K9kV5.auf\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"Sc0UwrhEureEzQ\", \"ixHBhtn3T99\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"0K9kV5.L6kj0T\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"Yuq5PWrpi8h2Hi\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"0K9kV5.sTEi\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"qOBBxX2kntyHDwCSGBcOd8yloVo\", \"YXPayoGQlGoFk6nkR\", \"zGMY1DfzOQvwMNmK4\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"0K9kV5.ATnVwRJH4\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"xLUKKGRNglfr7RzbW\", \"wbPkaR8SjIKOWOFKU\", \"U2LAfXHBUgQ9BK6OE\", \"UsXW3IKWtjUun81O5A2RvYipYYiWPf\", \"1WMPVZQFB44o4hS4qsdtv1DrHOg6le\", \"NAZAKdRXGpyYF8aVNTvsQYB4mcevPP\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"0K9kV5.gOTbM9V\", \"0K9kV5.6Foy06YCE03DGH\", \"0K9kV5.UD7QBnjzEQNRODz\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"ZKbsTPS4xbrnbP3xG\", \"w52EAqErWZ49EcaFQBN3h7\", \"OI6eIIiVmrxJOVhiq7IENU\", \"QqCH8sS0zyQyPCVRitbCLHD0FEStOFXEQK\", \"EX8qET0anoJJMvoEcGLYMZJvkzSLch4\", \"cyE74DukyW8Jx89B0mYfuuSwAhMV2XA\", \"G2hyHJGzf41Q0hDdKVZ3oeLy4ZJl32S\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"DVTtb8c.A2Ptm07Ncrg2.s1x\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"C6kqFl3fleB3zIF\", \"4fx5kxFt2KucxvrG0s\", \"1MewNMgaPjslx4l5ISCRWhn\", \"VI7aNjEq4a1J6QYF0wQ2pV6\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"0K9kV5.hmXIsf6p\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"ns4SneqAxCuWNVoepM2Q\", \"1OdzCqyk4cQtQrVOd2Zf60v\", \"0MjQEBo5tW89oNlWktVbRfH\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"0K9kV5.ANK\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"soKlU8SKloI9YCAcssn\", \"3IqglcGMMVfJAin4tBg\" ]\n" +
" }\n" +
" } ]\n" +
"}");
machine.addRule("rule3",
"{\n" +
" \"$or\" : [ {\n" +
" \"source\" : [ \"oeoNrI.qRk\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"wSjB92xeOBe2jf\", \"8owQcNCzpfsEjvv0zslQc\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"oeoNrI.3FD\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"XHSVWCs93l4m\", \"80jswkMW46QOp9ZasRC9i\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"oeoNrI.auf\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"XoZakwvaiEbgvF\", \"ixHBhtn3T99\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"oeoNrI.L6kj0T\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"Yuq5PWrpi8h2Hi\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"oeoNrI.sTEi\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"hI7uk7VTJB6gjcsRUoUIxuBPJaF\", \"UUFHA8cBHOvHk3lfO\", \"3cKTrqLEH5IMlsMDv\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"oeoNrI.ATnVwRJH4\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"TFaY7vCJG9EsxsjVd\", \"ZawowkBcOxdUsfgEs\", \"yOFNW7sxv0TNoMO6m\", \"Hp0AcGKGUlvM8lCgZqpiwOemCb2HSs\", \"SLDqS9ycYaKhJlzAdFC2bS92zrTpOO\", \"nAs966ixa5JQ9u2UlQOWh73PNMWehY\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"oeoNrI.gOTbM9V\", \"oeoNrI.6Foy06YCE03DGH\", \"oeoNrI.UD7QBnjzEQNRODz\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"tznZRlX80kDVIC8gH\", \"icLnBAt7pdp9aNDvOnqmMN\", \"NQHtpcQPybOVV0ZU4HInha\", \"QqCH8sS0zyQyPCVRitbCLHD0FEStOFXEQK\", \"6PXEaDOnRk7nmP6EhA9t2OE9g75eMmI\", \"cyE74DukyW8Jx89B0mYfuuSwAhMV2XA\", \"6n4FMCgGV1D09pLFanLGObbRBc1MXSH\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"DVTtb8c.6SOVnnlY9Y2B.s1x\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"gk3lANJe2ZNiCdu\", \"5bL8gLCE5CE8pS0kRR\", \"hHZciQGDRCFKqf5S206HnMM\", \"HT14rl37Pa0ADgY5diV4cUa\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"oeoNrI.hmXIsf6p\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"VcNAACSECOywtvlq42KR\", \"UhmN71rqtx6x0PagQr9Y4oU\", \"KX6z6AN1ApQq0HsSXbsyXgE\" ]\n" +
" }\n" +
" }, {\n" +
" \"source\" : [ \"oeoNrI.ANK\" ],\n" +
" \"detail\" : {\n" +
" \"eventName\" : [ \"RIo0rQN1PwKHiGnHcHP\", \"lhavqRt32TNqxjnfT2P\" ]\n" +
" }\n" +
" } ]\n" +
"}");
assertEquals(608, machine.approximateObjectCount(10000));
}
}
| 4,868 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/Benchmarks.java | package software.amazon.event.ruler;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.GZIPInputStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* Runs benchmarks to measure various aspects of Ruler performance with the help of JUnit. Normally, most of
* the tests here are marked @Ignore because they are not required as part of normal unit testing. However, after
* any nontrivial change to Ruler code, the tests should be re-run and the results checked against the performance
* numbers given in README.md to ensure there hasn't been a performance regression.
*
* Several of the benchmarks operate on a large file containing 213068 JSON records averaging about 900 bytes in size.
* There are two slightly varying versions, citylots.json.gz and citylots2.json.gz. Between the two of them they
* total ~400Mbytes, which makes Ruler a little slow to check out from git.
*/
public class Benchmarks {
// original citylots
private static final String CITYLOTS_JSON = "src/test/data/citylots.json.gz";
// revised citylots with structured arrays
private static final String CITYLOTS_2 = "src/test/data/citylots2.json.gz";
private final String[] EXACT_RULES = {
"{\n" +
" \"properties\": {\n" +
" \"MAPBLKLOT\": [ \"1430022\" ]\n" +
" }" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"MAPBLKLOT\": [ \"2607117\" ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"MAPBLKLOT\": [ \"2607218\" ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"MAPBLKLOT\": [ \"3745012\" ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"MAPBLKLOT\": [ \"VACSTWIL\" ]\n" +
" }\n" +
"}"
};
private final int[] EXACT_MATCHES = { 1, 101, 35, 655, 1 };
private final String[] WILDCARD_RULES = {
"{\n" +
" \"properties\": {\n" +
" \"MAPBLKLOT\": [ { \"wildcard\": \"143*\" } ]\n" +
" }" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"MAPBLKLOT\": [ { \"wildcard\": \"2*0*1*7\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"MAPBLKLOT\": [ { \"wildcard\": \"*218\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"MAPBLKLOT\": [ { \"wildcard\": \"3*5*2\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"MAPBLKLOT\": [ { \"wildcard\": \"VA*IL\" } ]\n" +
" }\n" +
"}"
};
private final int[] WILDCARD_MATCHES = { 490, 713, 43, 2540, 1 };
private final String[] PREFIX_RULES = {
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"prefix\": \"AC\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"prefix\": \"BL\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"prefix\": \"DR\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"prefix\": \"FU\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"prefix\": \"RH\" } ]\n" +
" }\n" +
"}"
};
private final int[] PREFIX_MATCHES = { 24, 442, 38, 2387, 328 };
private final String[] PREFIX_EQUALS_IGNORE_CASE_RULES = {
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"prefix\": { \"equals-ignore-case\": \"Ac\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"prefix\": { \"equals-ignore-case\": \"bL\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"prefix\": { \"equals-ignore-case\": \"dR\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"prefix\": { \"equals-ignore-case\": \"Fu\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"prefix\": { \"equals-ignore-case\": \"rH\" } } ]\n" +
" }\n" +
"}"
};
private final int[] PREFIX_EQUALS_IGNORE_CASE_MATCHES = { 24, 442, 38, 2387, 328 };
private final String[] SUFFIX_RULES = {
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"suffix\": \"ON\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"suffix\": \"KE\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"suffix\": \"MM\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"suffix\": \"ING\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"suffix\": \"GO\" } ]\n" +
" }\n" +
"}"
};
private final int[] SUFFIX_MATCHES = { 17921, 871, 13, 1963, 682 };
private final String[] SUFFIX_EQUALS_IGNORE_CASE_RULES = {
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"suffix\": { \"equals-ignore-case\": \"oN\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"suffix\": { \"equals-ignore-case\": \"Ke\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"suffix\": { \"equals-ignore-case\": \"mM\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"suffix\": { \"equals-ignore-case\": \"InG\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"suffix\": { \"equals-ignore-case\": \"gO\" } } ]\n" +
" }\n" +
"}"
};
private final int[] SUFFIX_EQUALS_IGNORE_CASE_MATCHES = { 17921, 871, 13, 1963, 682 };
private final String[] EQUALS_IGNORE_CASE_RULES = {
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"equals-ignore-case\": \"jefferson\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"equals-ignore-case\": \"bEaCh\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"equals-ignore-case\": \"HyDe\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"equals-ignore-case\": \"CHESTNUT\" } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"ST_TYPE\": [ { \"equals-ignore-case\": \"st\" } ]\n" +
" }\n" +
"}"
};
private final int[] EQUALS_IGNORE_CASE_MATCHES = { 131, 211, 1758, 825, 116386 };
private final String[] COMPLEX_ARRAYS_RULES = {
"{\n" +
" \"geometry\": {\n" +
" \"type\": [ \"Polygon\" ],\n" +
" \"coordinates\": {\n" +
" \"x\": [ { \"numeric\": [ \"=\", -122.42916360922355 ] } ]\n" +
" }\n" +
" }\n" +
"}",
"{\n" +
" \"geometry\": {\n" +
" \"type\": [ \"MultiPolygon\" ],\n" +
" \"coordinates\": {\n" +
" \"y\": [ { \"numeric\": [ \"=\", 37.729900216217324 ] } ]\n" +
" }\n" +
" }\n" +
"}",
"{\n" +
" \"geometry\": {\n" +
" \"coordinates\": {\n" +
" \"x\": [ { \"numeric\": [ \"<\", -122.41600944012424 ] } ]\n" +
" }\n" +
" }\n" +
"}",
"{\n" +
" \"geometry\": {\n" +
" \"coordinates\": {\n" +
" \"x\": [ { \"numeric\": [ \">\", -122.41600944012424 ] } ]\n" +
" }\n" +
" }\n" +
"}",
"{\n" +
" \"geometry\": {\n" +
" \"coordinates\": {\n" +
" \"x\": [ { \"numeric\": [ \">\", -122.46471267081272, \"<\", -122.4063085128395 ] } ]\n" +
" }\n" +
" }\n" +
"}"
};
private final int[] COMPLEX_ARRAYS_MATCHES = { 227, 2, 149444, 64368, 127485 };
private final String[] NUMERIC_RULES = {
"{\n" +
" \"geometry\": {\n" +
" \"type\": [ \"Polygon\" ],\n" +
" \"firstCoordinates\": {\n" +
" \"x\": [ { \"numeric\": [ \"=\", -122.42916360922355 ] } ]\n" +
" }\n" +
" }\n" +
"}",
"{\n" +
" \"geometry\": {\n" +
" \"type\": [ \"MultiPolygon\" ],\n" +
" \"firstCoordinates\": {\n" +
" \"z\": [ { \"numeric\": [ \"=\", 0 ] } ]\n" +
" }\n" +
" }\n" +
"}",
"{\n" +
" \"geometry\": {\n" +
" \"firstCoordinates\": {\n" +
" \"x\": [ { \"numeric\": [ \"<\", -122.41600944012424 ] } ]\n" +
" }\n" +
" }\n" +
"}",
"{\n" +
" \"geometry\": {\n" +
" \"firstCoordinates\": {\n" +
" \"x\": [ { \"numeric\": [ \">\", -122.41600944012424 ] } ]\n" +
" }\n" +
" }\n" +
"}",
"{\n" +
" \"geometry\": {\n" +
" \"firstCoordinates\": {\n" +
" \"x\": [ { \"numeric\": [ \">\", -122.46471267081272, \"<\", -122.4063085128395 ] } ]\n" +
" }\n" +
" }\n" +
"}"
};
private final int[] NUMERIC_MATCHES = { 8, 120, 148943, 64120, 127053 };
private final String[] ANYTHING_BUT_RULES = {
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"anything-but\": [ \"FULTON\" ] } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"anything-but\": [ \"MASON\" ] } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"ST_TYPE\": [ { \"anything-but\": [ \"ST\" ] } ]\n" +
" }\n" +
"}",
"{\n" +
" \"geometry\": {\n" +
" \"type\": [ {\"anything-but\": [ \"Polygon\" ] } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"FROM_ST\": [ { \"anything-but\": [ \"441\" ] } ]\n" +
" }\n" +
"}"
};
private final int[] ANYTHING_BUT_MATCHES = { 211158, 210411, 96682, 120, 210615 };
private final String[] ANYTHING_BUT_IGNORE_CASE_RULES = {
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"anything-but\": {\"equals-ignore-case\": [ \"Fulton\" ] } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"anything-but\": {\"equals-ignore-case\": [ \"Mason\" ] } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"ST_TYPE\": [ { \"anything-but\": {\"equals-ignore-case\": [ \"st\" ] } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"geometry\": {\n" +
" \"type\": [ {\"anything-but\": {\"equals-ignore-case\": [ \"polygon\" ] } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"FROM_ST\": [ { \"anything-but\": {\"equals-ignore-case\": [ \"441\" ] } } ]\n" +
" }\n" +
"}"
};
private final int[] ANYTHING_BUT_IGNORE_CASE_MATCHES = { 211158, 210411, 96682, 120, 210615 };
private final String[] ANYTHING_BUT_PREFIX_RULES = {
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"anything-but\": {\"prefix\": \"FULTO\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"anything-but\": { \"prefix\": \"MASO\"} } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"ST_TYPE\": [ { \"anything-but\": {\"prefix\": \"S\"} } ]\n" +
" }\n" +
"}",
"{\n" +
" \"geometry\": {\n" +
" \"type\": [ {\"anything-but\": {\"prefix\": \"Poly\"} } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"FROM_ST\": [ { \"anything-but\": {\"prefix\": \"44\"} } ]\n" +
" }\n" +
"}"
};
private final int[] ANYTHING_BUT_PREFIX_MATCHES = { 211158, 210118, 96667, 120, 209091 };
private final String[] ANYTHING_BUT_SUFFIX_RULES = {
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"anything-but\": {\"suffix\": \"ULTON\" } } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"STREET\": [ { \"anything-but\": { \"suffix\": \"ASON\"} } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"ST_TYPE\": [ { \"anything-but\": {\"suffix\": \"T\"} } ]\n" +
" }\n" +
"}",
"{\n" +
" \"geometry\": {\n" +
" \"type\": [ {\"anything-but\": {\"suffix\": \"olygon\"} } ]\n" +
" }\n" +
"}",
"{\n" +
" \"properties\": {\n" +
" \"FROM_ST\": [ { \"anything-but\": {\"suffix\": \"41\"} } ]\n" +
" }\n" +
"}"
};
private final int[] ANYTHING_BUT_SUFFIX_MATCHES = { 211136, 210411, 94908, 0, 209055 };
// This needs to be run with -Xms2g -Xmx2g (Dunno about the 2g but the same Xms and Xmx, and big enough
// to hold several copies of the 200M in citylots2
private final static int NUMBER_OF_RULES = 400000;
private final static int NUMBER_OF_FIELD_NAMES = 10;
@Test
public void ruleMemoryBenchmark() throws Exception {
// 10 random field names
String[] fieldNames = new String[NUMBER_OF_FIELD_NAMES];
for (int i = 0; i < NUMBER_OF_FIELD_NAMES; i++) {
fieldNames[i] = randomAscii(12);
}
// now we're going to add 10K random rules and see how much memory it uses
String ruleTemplate = "{\n" +
" \"Abernathy\": {\n" +
" \"-FIELD1\": [ -NUMBER1 ]\n" +
" },\n" +
" \"Barnard\": {\n" +
" \"Oliver\": [ { \"prefix\": \"-PREFIX\" } ]\n" +
" }\n" +
"}";
List<String> rules = new ArrayList<>();
Machine mm = new Machine();
for (int i = 0; i < NUMBER_OF_RULES; i++) {
String rule = ruleTemplate;
rule = rule.replace("-FIELD1", fieldNames[i % NUMBER_OF_FIELD_NAMES]);
//rule = rule.replace("-NUMBER1", Double.toString(1000000.0 * rand.nextDouble()));
rule = rule.replace("-NUMBER1", Integer.toString(rand.nextInt(100)));
rule = rule.replace("-PREFIX", randomAscii(6));
rules.add(rule);
// handy when fooling with rule templates
// if (i < 12) {
// System.out.println("R: " + rule);
// }
}
System.gc();
long memBefore = Runtime.getRuntime().freeMemory();
int sizeBefore = mm.approximateObjectCount(Integer.MAX_VALUE);
System.out.printf("Before: %.1f (%d)\n", 1.0 * memBefore / 1000000, sizeBefore);
for (int i = 0; i < rules.size(); i++) {
mm.addRule("mm" + i, rules.get(i));
}
System.gc();
long memAfter = Runtime.getRuntime().freeMemory();
int sizeAfter = mm.approximateObjectCount(Integer.MAX_VALUE);
System.out.printf("After: %.1f (%d)\n", 1.0 * memAfter / 1000000, sizeAfter);
int perRuleMem = (int) ((1.0 * (memAfter - memBefore)) / rules.size());
int perRuleSize = (int) ((1.0 * (sizeAfter - sizeBefore)) / rules.size());
System.out.println("Per rule: " + perRuleMem + " (" + perRuleSize + ")");
rules.clear();
}
// This needs to be run with -Xms2g -Xmx2g
// Only use exact match to verify exact match memory optimization change.
@Test
public void exactRuleMemoryBenchmark() throws Exception {
// 10 random field names
String[] fieldNames = new String[NUMBER_OF_FIELD_NAMES];
for (int i = 0; i < NUMBER_OF_FIELD_NAMES; i++) {
fieldNames[i] = randomAscii(12);
}
// now we're going to add 10K random rules and see how much memory it uses
String ruleTemplate = "{\n" +
" \"Abernathy\": {\n" +
" \"-FIELD1\": [ -STR1 ]\n" +
" },\n" +
" \"Barnard\": {\n" +
" \"Oliver\": [ -STR2 ]\n" +
" }\n" +
"}";
List<String> rules = new ArrayList<>();
Machine mm = new Machine();
for (int i = 0; i < NUMBER_OF_RULES; i++) {
String rule = ruleTemplate;
rule = rule.replace("-FIELD1", fieldNames[i % NUMBER_OF_FIELD_NAMES]);
rule = rule.replace("-STR1", "\"" + randomAscii(20) + "\"");
rule = rule.replace("-STR2", "\"" + randomAscii(20) + "\"");
rules.add(rule);
}
System.gc();
long memBefore = Runtime.getRuntime().freeMemory();
int sizeBefore = mm.approximateObjectCount();
System.out.printf("Before: %.1f (%d)\n", 1.0 * memBefore / 1000000, sizeBefore);
for (int i = 0; i < rules.size(); i++) {
mm.addRule("mm" + i, rules.get(i));
}
System.gc();
long memAfter = Runtime.getRuntime().freeMemory();
int sizeAfter = mm.approximateObjectCount();
System.out.printf("After: %.1f (%d)\n", 1.0 * memAfter / 1000000, sizeAfter);
int perRuleMem = (int) ((1.0 * (memAfter - memBefore)) / rules.size());
int perRuleSize = (int) ((1.0 * (sizeAfter - sizeBefore)) / rules.size());
System.out.println("Per rule: " + perRuleMem + " (" + perRuleSize + ")");
rules.clear();
}
@Test
public void AnythingButPerformanceBenchmark() throws Exception {
readCityLots2();
final Machine m = new Machine();
String rule = "{\n" +
" \"properties\": {\n" +
" \"ODD_EVEN\": [ {\"anything-but\":\"E\"} ],\n" +
" \"ST_TYPE\": [ {\"anything-but\":\"ST\"} ]\n" +
" },\n" +
" \"geometry\": {\n" +
" \"coordinates\": {\n" +
" \"z\": [ {\"anything-but\": 1} ] \n" +
" }\n" +
" }\n" +
"}";
m.addRule("r", rule);
int count = 0;
int matched = 0;
long before = System.currentTimeMillis();
for (String lot : citylots2) {
count++;
if ((count % 10000) == 0) {
System.out.println("Lots: " + count);
}
if (m.rulesForJSONEvent(lot).size() != 0) {
matched++;
}
}
assertEquals(52527, matched); // from grep
System.out.println("Matched: " + matched);
long after = System.currentTimeMillis();
System.out.println("Lines: " + citylots2.size() +
", Msec: " + (after - before));
double eps = (1000.0 / (1.0 * (after - before) / citylots2.size()));
System.out.println("Events/sec: " + String.format("%.1f", eps));
}
@Test
public void CL2NoCompileBenchmark() throws Exception {
readCityLots2();
final Machine staticMachine = new Machine();
Map<String, Integer> expected = setRules(staticMachine);
int count = 0;
Map<String, AtomicInteger> received = new HashMap<>();
Set<String> rules = expected.keySet();
System.out.println("Finding Rules...");
long before = System.currentTimeMillis();
for (String lot : citylots2) {
for (String rule : rules) {
if (Ruler.matchesRule(lot, ruleJSON.get(rule))) {
incrRuleCount(rule, received);
}
}
count++;
if ((count % 10000) == 0) {
System.out.println("Lots: " + count);
}
}
long after = System.currentTimeMillis();
System.out.println("Lines: " + citylots2.size() +
", Msec: " + (after - before));
double eps = (1000.0 / (1.0 * (after - before) / citylots2.size()));
System.out.println("Events/sec: " + String.format("%.1f", eps));
System.out.println(" Rules/sec: " + String.format("%.1f", eps * rules.size()));
for (String rule : rules) {
assertEquals(rule, (long) expected.get(rule), received.get(rule).get());
}
}
@Test
public void CL2Benchmark() throws Exception {
readCityLots2();
Benchmarker bm;
// initial run to stabilize memory
bm = new Benchmarker();
bm.addRules(EXACT_RULES, EXACT_MATCHES);
bm.run(citylots2);
bm = new Benchmarker();
bm.addRules(EXACT_RULES, EXACT_MATCHES);
bm.run(citylots2);
System.out.println("EXACT events/sec: " + String.format("%.1f", bm.getEPS()));
bm = new Benchmarker();
bm.addRules(WILDCARD_RULES, WILDCARD_MATCHES);
bm.run(citylots2);
System.out.println("WILDCARD events/sec: " + String.format("%.1f", bm.getEPS()));
bm = new Benchmarker();
bm.addRules(PREFIX_RULES, PREFIX_MATCHES);
bm.run(citylots2);
System.out.println("PREFIX events/sec: " + String.format("%.1f", bm.getEPS()));
bm = new Benchmarker();
bm.addRules(PREFIX_EQUALS_IGNORE_CASE_RULES, PREFIX_EQUALS_IGNORE_CASE_MATCHES);
bm.run(citylots2);
System.out.println("PREFIX_EQUALS_IGNORE_CASE_RULES events/sec: " + String.format("%.1f", bm.getEPS()));
bm = new Benchmarker();
bm.addRules(SUFFIX_RULES, SUFFIX_MATCHES);
bm.run(citylots2);
System.out.println("SUFFIX events/sec: " + String.format("%.1f", bm.getEPS()));
bm = new Benchmarker();
bm.addRules(SUFFIX_EQUALS_IGNORE_CASE_RULES, SUFFIX_EQUALS_IGNORE_CASE_MATCHES);
bm.run(citylots2);
System.out.println("SUFFIX_EQUALS_IGNORE_CASE_RULES events/sec: " + String.format("%.1f", bm.getEPS()));
bm = new Benchmarker();
bm.addRules(EQUALS_IGNORE_CASE_RULES, EQUALS_IGNORE_CASE_MATCHES);
bm.run(citylots2);
System.out.println("EQUALS_IGNORE_CASE events/sec: " + String.format("%.1f", bm.getEPS()));
bm = new Benchmarker();
bm.addRules(NUMERIC_RULES, NUMERIC_MATCHES);
bm.run(citylots2);
System.out.println("NUMERIC events/sec: " + String.format("%.1f", bm.getEPS()));
bm = new Benchmarker();
bm.addRules(ANYTHING_BUT_RULES, ANYTHING_BUT_MATCHES);
bm.run(citylots2);
System.out.println("ANYTHING-BUT events/sec: " + String.format("%.1f", bm.getEPS()));
bm = new Benchmarker();
bm.addRules(ANYTHING_BUT_IGNORE_CASE_RULES, ANYTHING_BUT_IGNORE_CASE_MATCHES);
bm.run(citylots2);
System.out.println("ANYTHING-BUT-IGNORE-CASE events/sec: " + String.format("%.1f", bm.getEPS()));
bm = new Benchmarker();
bm.addRules(ANYTHING_BUT_PREFIX_RULES, ANYTHING_BUT_PREFIX_MATCHES);
bm.run(citylots2);
System.out.println("ANYTHING-BUT-PREFIX events/sec: " + String.format("%.1f", bm.getEPS()));
bm = new Benchmarker();
bm.addRules(ANYTHING_BUT_SUFFIX_RULES, ANYTHING_BUT_SUFFIX_MATCHES);
bm.run(citylots2);
System.out.println("ANYTHING-BUT-SUFFIX events/sec: " + String.format("%.1f", bm.getEPS()));
bm = new Benchmarker();
bm.addRules(COMPLEX_ARRAYS_RULES, COMPLEX_ARRAYS_MATCHES);
bm.run(citylots2);
System.out.println("COMPLEX_ARRAYS events/sec: " + String.format("%.1f", bm.getEPS()));
// skips complex arrays matchers because their slowness can hide improvements
// and regressions for other matchers. Remove this once we find ways to make
// arrays fast enough to others matchers
bm = new Benchmarker();
bm.addRules(NUMERIC_RULES, NUMERIC_MATCHES);
bm.addRules(EXACT_RULES, EXACT_MATCHES);
bm.addRules(PREFIX_RULES, PREFIX_MATCHES);
bm.addRules(ANYTHING_BUT_RULES, ANYTHING_BUT_MATCHES);
bm.addRules(ANYTHING_BUT_IGNORE_CASE_RULES, ANYTHING_BUT_IGNORE_CASE_MATCHES);
bm.addRules(ANYTHING_BUT_PREFIX_RULES, ANYTHING_BUT_PREFIX_MATCHES);
bm.addRules(ANYTHING_BUT_SUFFIX_RULES, ANYTHING_BUT_SUFFIX_MATCHES);
bm.run(citylots2);
System.out.println("PARTIAL_COMBO events/sec: " + String.format("%.1f", bm.getEPS()));
bm = new Benchmarker();
bm.addRules(NUMERIC_RULES, NUMERIC_MATCHES);
bm.addRules(EXACT_RULES, EXACT_MATCHES);
bm.addRules(PREFIX_RULES, PREFIX_MATCHES);
bm.addRules(ANYTHING_BUT_RULES, ANYTHING_BUT_MATCHES);
bm.addRules(ANYTHING_BUT_IGNORE_CASE_RULES, ANYTHING_BUT_IGNORE_CASE_MATCHES);
bm.addRules(ANYTHING_BUT_PREFIX_RULES, ANYTHING_BUT_PREFIX_MATCHES);
bm.addRules(ANYTHING_BUT_SUFFIX_RULES, ANYTHING_BUT_SUFFIX_MATCHES);
bm.addRules(COMPLEX_ARRAYS_RULES, COMPLEX_ARRAYS_MATCHES);
bm.run(citylots2);
System.out.println("COMBO events/sec: " + String.format("%.1f", bm.getEPS()));
}
// make sure we can handle nasty deep events
@Test
public void DeepEventBenchmark() throws Exception {
// how many levels deep we want to go
int maxLevel = 100;
// we create a rule every time the number of events is a multiple of this number
int ruleEveryNEvents = 10;
ObjectMapper m = new ObjectMapper();
Map<String, Object> root = new HashMap<>();
Map<String, Object> ruleRoot = new HashMap<>();
List<String> deepEvents = new ArrayList<>();
List<String> deepRules = new ArrayList<>();
List<Integer> deepExpected = new ArrayList<>();
Map<String, Object> currentLevel = root;
Map<String, Object> currentRule = ruleRoot;
for (int i = 0; i < maxLevel; i++) {
currentLevel.put("numeric" + i, i * i);
currentLevel.put("string" + i, "value" + i);
if (i % ruleEveryNEvents == 0) {
currentRule.put("string" + i, Collections.singletonList("value" + i));
deepRules.add(m.writeValueAsString(ruleRoot));
currentRule.remove("string" + i);
// all the events generated below this point will match this rule.
deepExpected.add(maxLevel - i);
}
deepEvents.add(m.writeValueAsString(root));
HashMap<String, Object> newLevel = new HashMap<>();
currentLevel.put("level" + i, newLevel);
currentLevel = newLevel;
HashMap<String, Object> newRuleLevel = new HashMap<>();
currentRule.put("level" + i, newRuleLevel);
currentRule = newRuleLevel;
}
// warm up
Benchmarker bm = new Benchmarker();
bm.addRules(deepRules.toArray(new String[0]), deepExpected.stream().mapToInt(Integer::intValue).toArray());
bm.run(deepEvents);
// exercise
bm = new Benchmarker();
bm.addRules(deepRules.toArray(new String[0]), deepExpected.stream().mapToInt(Integer::intValue).toArray());
bm.run(deepEvents);
System.out.println("DEEP EXACT events/sec: " + String.format("%.1f", bm.getEPS()));
}
private final List<String> citylots2 = new ArrayList<>();
private static class Benchmarker {
int ruleCount = 0;
Map<String, Integer> wanted = new HashMap<>();
Machine machine = new Machine();
double eps = 0.0;
void addRules(String[] rules, int[] wanted) throws Exception {
for (int i = 0; i < rules.length; i++) {
String rname = String.format("r%d", ruleCount++);
machine.addRule(rname, rules[i]);
this.wanted.put(rname, wanted[i]);
}
}
void run(List<String> events) throws Exception {
final Map<String, Integer> gotMatches = new HashMap<>();
long before = System.currentTimeMillis();
for (String event : events) {
List<String> matches = machine.rulesForJSONEvent(event);
for (String match : matches) {
Integer got = gotMatches.get(match);
if (got == null) {
got = 1;
} else {
got = got + 1;
}
gotMatches.put(match, got);
}
}
long after = System.currentTimeMillis();
eps = (1000.0 / (1.0 * (after - before) / events.size()));
for (String got : gotMatches.keySet()) {
assertEquals(wanted.get(got), gotMatches.get(got));
}
for (String want : wanted.keySet()) {
assertEquals(wanted.get(want), gotMatches.get(want) == null ? (Integer) 0 : gotMatches.get(want));
}
}
double getEPS() {
return eps;
}
}
private final Random rand = new Random(234345);
private String randomAscii(final int len) {
final String abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
sb.append(abc.charAt(rand.nextInt(abc.length())));
}
return sb.toString();
}
private void readCityLots2() {
try {
System.out.println("Reading citylots2");
final FileInputStream fileInputStream = new FileInputStream(CITYLOTS_2);
final GZIPInputStream gzipInputStream = new GZIPInputStream(fileInputStream);
BufferedReader cl2Reader = new BufferedReader(new InputStreamReader(gzipInputStream));
String line = cl2Reader.readLine();
while (line != null) {
citylots2.add(line);
line = cl2Reader.readLine();
}
cl2Reader.close();
System.out.println("Read " + citylots2.size() + " events");
} catch (Exception e) {
System.out.println("Can't find, current directory " + System.getProperty("user.dir"));
throw new RuntimeException(e);
}
}
/////////////////////////// Old benchmarks start here ////////////////////////
private BufferedReader cityLotsReader;
private final Machine machine = new Machine();
private final Map<String, String> ruleJSON = new HashMap<>();
@Test
public void RulebaseBenchmark() throws Exception {
File dir = new File("data");
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
String name = file.getName();
if (name.startsWith("rules")) {
BufferedReader reader = new BufferedReader(new FileReader(file));
List<String[]> lines = linesFrom(reader);
reader.close();
doRules(lines);
}
}
}
}
private void doRules(List<String[]> lines) {
Machine machine = new Machine();
String[] rnames = new String[lines.size()];
for (int i = 0; i < rnames.length; i++) {
rnames[i] = "R" + String.format("%03d", i);
}
List<Map<String, List<String>>> rules = new ArrayList<>();
int size = 0;
for (String[] line : lines) {
Map<String, List<String>> rule = new HashMap<>();
for (int i = 0; i < line.length; i += 2) {
List<String> l = new ArrayList<>();
l.add(line[i + 1]);
rule.put(line[i], l);
size += l.size();
}
rules.add(rule);
}
long before = System.currentTimeMillis();
for (int i = 0; i < rules.size(); i++) {
machine.addRule(rnames[i], rules.get(i));
}
long after = System.currentTimeMillis();
long delta = after - before;
int avg = (int) ((1.0 * size / rules.size()) + 0.5);
System.out.printf("%d rules, average size %d, %dms\n", rules.size(), avg, delta);
}
private List<String[]> linesFrom(BufferedReader reader) throws Exception {
List<String[]> lines = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split("\\*");
lines.add(parts);
}
return lines;
}
@Test
public void CitylotsBenchmark() throws Exception {
openInput();
System.out.println("Turning JSON into field-lists...");
List<String[]> parsedLines = readAndParseLines();
Map<String, Integer> expected = setRules(machine);
List<String> allRules = new ArrayList<>();
System.out.println("Finding Rules...");
long before = System.currentTimeMillis();
for (String[] line : parsedLines) {
allRules.addAll(machine.rulesForEvent(line));
}
long after = System.currentTimeMillis();
System.out.println("Lines: " + parsedLines.size() +
", Msec: " + (after - before));
double eps = (1000.0 / (1.0 * (after - before) / parsedLines.size()));
System.out.println("Events/sec: " + String.format("%.1f", eps));
Map<String, Integer> rc = new HashMap<>();
for (String rule : allRules) {
incr(rule, rc);
}
for (String r : expected.keySet()) {
assertEquals(expected.get(r), rc.get(r));
}
}
@Test
public void RealisticCityLots() throws Exception {
openInput();
System.out.println("Reading lines...");
List<String> lines = readLines();
Map<String, Integer> expected = setRules(machine);
List<String> allRules = new ArrayList<>();
System.out.println("Finding Rules...");
long before = System.currentTimeMillis();
int count = 0;
for (String line : lines) {
allRules.addAll(machine.rulesForJSONEvent(line));
count++;
if ((count % 10000) == 0) {
System.out.println("Lots: " + count);
}
}
long after = System.currentTimeMillis();
System.out.println("Lines: " + lines.size() +
", Msec: " + (after - before));
double eps = (1000.0 / (1.0 * (after - before) / lines.size()));
System.out.println("Events/sec: " + String.format("%.1f", eps));
System.out.println(" Rules/sec: " + String.format("%.1f", eps * allRules.size()));
Map<String, Integer> rc = new HashMap<>();
for (String rule : allRules) {
incr(rule, rc);
}
for (String r : expected.keySet()) {
assertEquals(expected.get(r), rc.get(r));
}
}
@Test
public void NoCompileBenchmark() throws Exception {
openInput();
System.out.println("Reading lines...");
List<String> lines = readLines();
int count = 0;
final Machine staticMachine = new Machine();
Map<String, Integer> expected = setRules(staticMachine);
Map<String, AtomicInteger> received = new HashMap<>();
Set<String> rules = expected.keySet();
System.out.println("Finding Rules...");
long before = System.currentTimeMillis();
for (String lot : lines) {
for (String rule : rules) {
if (Ruler.matchesRule(lot, ruleJSON.get(rule))) {
incrRuleCount(rule, received);
}
}
count++;
if ((count % 10000) == 0) {
System.out.println("Lots: " + count);
}
}
long after = System.currentTimeMillis();
System.out.println("Lines: " + lines.size() +
", Msec: " + (after - before));
double eps = (1000.0 / (1.0 * (after - before) / lines.size()));
System.out.println("Events/sec: " + String.format("%.1f", eps));
System.out.println(" Rules/sec: " + String.format("%.1f", eps * rules.size()));
for (String rule : rules) {
assertEquals(rule, (long) expected.get(rule), received.get(rule).get());
}
}
private void incrRuleCount(String rule, Map<String, AtomicInteger> counts) {
AtomicInteger count = counts.get(rule);
if (count == null) {
count = new AtomicInteger(0);
counts.put(rule, count);
}
count.incrementAndGet();
}
private void incr(String r, Map<String, Integer> rc) {
rc.merge(r, 1, Integer::sum);
}
private void openInput() {
try {
final FileInputStream fileInputStream = new FileInputStream(CITYLOTS_JSON);
final GZIPInputStream gzipInputStream = new GZIPInputStream(fileInputStream);
cityLotsReader = new BufferedReader(new InputStreamReader(gzipInputStream));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private List<String> readLines() throws Exception {
String line;
List<String> lines = new ArrayList<>();
while ((line = cityLotsReader.readLine()) != null) {
lines.add(line);
}
return lines;
}
private List<String[]> readAndParseLines() throws Exception {
String line;
List<String[]> lines = new ArrayList<>();
while ((line = cityLotsReader.readLine()) != null) {
List<String> fieldList = Event.flatten(line);
String[] fields = new String[fieldList.size()];
fieldList.toArray(fields);
lines.add(fields);
}
return lines;
}
private Map<String, Integer> setRules(Machine machine) {
List<Rule> rules = new ArrayList<>();
HashMap<String, Integer> expected = new HashMap<>();
Rule rule;
rule = new Rule("R1");
rule.setKeys("properties.STREET", "properties.FROM_ST");
rule.setJson("{ \"properties\": { \"STREET\": [ \"FOERSTER\" ], \"FROM_ST\": [ \"755\" ] } }");
rule.setValues("\"FOERSTER\"", "\"755\"");
rule.setShouldMatch(1);
rules.add(rule);
ruleJSON.put("R1", rule.json);
rule = new Rule("R2");
rule.setJson("{ \"properties\": { \"BLOCK_NUM\": [ \"3027A\" ] } }");
rule.setKeys("properties.BLOCK_NUM");
rule.setValues("\"3027A\"");
rule.setShouldMatch(59);
rules.add(rule);
ruleJSON.put("R2", rule.json);
rule = new Rule("R3");
rule.setKeys("properties.BLOCK_NUM", "properties.ODD_EVEN");
rule.setValues("\"2183\"", "\"E\"");
rule.setJson("{ \"properties\": { \"BLOCK_NUM\": [ \"2183\" ], \"ODD_EVEN\": [ \"E\" ] } }");
rule.setShouldMatch(27);
rules.add(rule);
ruleJSON.put("R3", rule.json);
rule = new Rule("R4");
rule.setKeys("properties.STREET");
rule.setValues("\"17TH\"");
rule.setJson("{ \"properties\": { \"STREET\": [ \"17TH\" ] } }");
rule.setShouldMatch(1619);
rules.add(rule);
ruleJSON.put("R4", rule.json);
rule = new Rule("R5");
rule.setKeys("properties.FROM_ST", "geometry.type");
rule.setValues("\"2521\"", "\"Polygon\"");
rule.setJson("{ \"properties\": { \"FROM_ST\": [ \"2521\" ] }, \"geometry\": { \"type\": [ \"Polygon\" ] } }");
rule.setShouldMatch(19);
rules.add(rule);
ruleJSON.put("R5", rule.json);
rule = new Rule("R6");
rule.setKeys("properties.STREET");
rule.setValues("\"FOLSOM\"");
rule.setJson("{ \"properties\": { \"STREET\": [ \"FOLSOM\" ] } }");
rule.setShouldMatch(1390);
rules.add(rule);
ruleJSON.put("R6", rule.json);
rule = new Rule("R7");
rule.setKeys("properties.BLOCK_NUM", "properties.ST_TYPE");
rule.setValues("\"3789\"", "\"ST\"");
rule.setJson("{ \"properties\": { \"BLOCK_NUM\": [ \"3789\" ], \"ST_TYPE\": [ \"ST\" ] } }");
rule.setShouldMatch(527);
rules.add(rule);
ruleJSON.put("R7", rule.json);
for (Rule r : rules) {
expected.put(r.name, r.shouldMatch);
machine.addRule(r.name, r.fields);
}
return expected;
}
private static class Rule {
String name;
String json;
int shouldMatch = 0;
final Map<String, List<String>> fields = new HashMap<>();
private String[] keys;
Rule(String name) {
this.name = name;
}
void setJson(String json) {
assertNull(RuleCompiler.check(json));
this.json = json;
}
void setKeys(String... keys) {
this.keys = keys;
}
void setValues(String... values) {
for (int i = 0; i < values.length; i++) {
final List<String> valList = new ArrayList<>();
valList.add(values[i]);
fields.put(keys[i], valList);
}
}
void setShouldMatch(int shouldMatch) {
this.shouldMatch = shouldMatch;
}
}
}
| 4,869 |
0 | Create_ds/event-ruler/src/test/software/amazon/event | Create_ds/event-ruler/src/test/software/amazon/event/ruler/GenericMachineTest.java | package software.amazon.event.ruler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Unit testing a state GenericMachine is hard. Tried hand-computing a few GenericMachines
* but kept getting them wrong, the software was right. So this is really
* more of a smoke/integration test. But the coverage is quite good.
*/
public class GenericMachineTest {
@Test
public void anythingButPrefixTest() throws Exception {
String event = " {\n" +
" \"a\": \"lorem\", " +
" \"b\": \"ipsum\"" +
" }";
String ruleTemplate = "{\n" +
" \"a\": [ { \"anything-but\": { \"prefix\": \"FOO\" } } ]" +
"}";
String[] prefixes = { "l", "lo", "lor", "lorem" };
List<String> ruleNames = new ArrayList<>();
Machine m = new Machine();
for (int i = 0; i < prefixes.length; i++) {
String ruleName = "r" + i;
ruleNames.add(ruleName);
String rule = ruleTemplate.replace("FOO", prefixes[i]);
m.addRule(ruleName, rule);
}
List<String> matches = m.rulesForJSONEvent(event);
assertEquals(0, matches.size());
String[] shouldMatch = { "now", "is", "the", "time", "for", "all", "good", "aliens" };
for (String s : shouldMatch) {
String e = event.replace("lorem", s);
matches = m.rulesForJSONEvent(e);
assertEquals(ruleNames.size(), matches.size());
for (String rn : ruleNames) {
assertTrue(matches.contains(rn));
}
}
for (int i = 0; i < prefixes.length; i++) {
String ruleName = "r" + i;
String rule = ruleTemplate.replace("FOO", prefixes[i]);
m.deleteRule(ruleName, rule);
}
for (String s : shouldMatch) {
String e = event.replace("lorem", s);
matches = m.rulesForJSONEvent(e);
assertEquals(0, matches.size());
}
}
@Test
public void anythingButSuffixTest() throws Exception {
String event = " {\n" +
" \"a\": \"lorem\", " +
" \"b\": \"ipsum\"" +
" }";
String ruleTemplate = "{\n" +
" \"a\": [ { \"anything-but\": { \"suffix\": \"FOO\" } } ]" +
"}";
String[] suffixes = { "m", "em", "rem", "orem", "lorem" };
List<String> ruleNames = new ArrayList<>();
Machine m = new Machine();
for (int i = 0; i < suffixes.length; i++) {
String ruleName = "r" + i;
ruleNames.add(ruleName);
String rule = ruleTemplate.replace("FOO", suffixes[i]);
m.addRule(ruleName, rule);
}
List<String> matches = m.rulesForJSONEvent(event);
assertEquals(0, matches.size());
String[] shouldMatch = { "run", "walk", "skip", "hop" };
for (String s : shouldMatch) {
String e = event.replace("lorem", s);
matches = m.rulesForJSONEvent(e);
assertEquals(ruleNames.size(), matches.size());
for (String rn : ruleNames) {
assertTrue(matches.contains(rn));
}
}
for (int i = 0; i < suffixes.length; i++) {
String ruleName = "r" + i;
String rule = ruleTemplate.replace("FOO", suffixes[i]);
m.deleteRule(ruleName, rule);
}
for (String s : shouldMatch) {
String e = event.replace("lorem", s);
matches = m.rulesForJSONEvent(e);
assertEquals(0, matches.size());
}
}
public static String readData(String jsonName) throws Exception {
String wd = System.getProperty("user.dir");
Path path = FileSystems.getDefault().getPath(wd, "src", "test", "data", jsonName);
return new String(Files.readAllBytes(path));
}
public static JsonNode readAsTree(String jsonName) throws Exception, IOException {
return new ObjectMapper().readTree(readData(jsonName));
}
@Test
public void arraysBugTest() throws Exception {
String event = "{\n" +
" \"requestContext\": { \"obfuscatedCustomerId\": \"AIDACKCEVSQ6C2EXAMPLE\" },\n" +
" \"hypotheses\": [\n" +
" { \"isBluePrint\": true, \"creator\": \"A123\" },\n" +
" { \"isBluePrint\": false, \"creator\": \"A234\" }\n" +
" ]\n" +
"}";
String r1 = "{\n" +
" \"hypotheses\": {\n" +
" \"isBluePrint\": [ false ],\n" +
" \"creator\": [ \"A123\" ]\n" +
" }\n" +
"}";
String r2 = "{\n" +
" \"hypotheses\": {\n" +
" \"isBluePrint\": [ true ],\n" +
" \"creator\": [ \"A234\" ]\n" +
" }\n" +
"}";
Machine m = new Machine();
m.addRule("r1", r1);
m.addRule("r2", r2);
JsonNode json = new ObjectMapper().readTree(event);
List<String> matches = m.rulesForJSONEvent(json);
assertEquals(0, matches.size());
}
@Test
public void nestedArraysTest() throws Exception {
String event1 = readData("arrayEvent1.json");
String event2 = readData("arrayEvent2.json");
String event3 = readData("arrayEvent3.json");
String event4 = readData("arrayEvent4.json");
String rule1 = readData("arrayRule1.json");
String rule2 = readData("arrayRule2.json");
String rule3 = readData("arrayRule3.json");
Machine m = new Machine();
m.addRule("rule1", rule1);
m.addRule("rule2", rule2);
m.addRule("rule3", rule3);
List<String> r1 = m.rulesForEvent(event1);
List<String> r1AC = m.rulesForJSONEvent(event1);
assertEquals(2, r1.size());
assertTrue(r1.contains("rule1"));
assertTrue(r1.contains("rule2"));
assertEquals(r1, r1AC);
// event2 shouldn't match any rules
List<String> r2 = m.rulesForEvent(event2);
List<String> r2AC = m.rulesForJSONEvent(event2);
assertEquals(0, r2.size());
assertEquals(r2, r2AC);
// event3 shouldn't match any rules with AC on
List<String> r3 = m.rulesForEvent(event3);
List<String> r3AC = m.rulesForJSONEvent(event3);
assertEquals(1, r3.size());
assertTrue(r3.contains("rule3"));
assertEquals(0, r3AC.size());
// event4 should match rule3
List<String> r4 = m.rulesForEvent(event4);
List<String> r4AC = m.rulesForJSONEvent(event4);
assertEquals(1, r4.size());
assertTrue(r4.contains("rule3"));
assertEquals(r4, r4AC);
}
// create a customized class as T
// TODO: Figure out what these unused fields are for and either finish what was started here, or discard it
public static final class SimpleFilter {
private String filterId;
private String filterExpression;
private List<String> downChannels;
private long lastUpdatedMs;
SimpleFilter(String clientId, String filterId, String filterExpression,
List<String> downChannels, long lastUpdatedMs) {
this.filterId = filterId;
this.filterExpression = filterExpression;
this.downChannels = downChannels;
this.lastUpdatedMs = lastUpdatedMs;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof SimpleFilter)) {
return false;
}
SimpleFilter other = (SimpleFilter) obj;
return filterId.equals(other.filterId);
}
@Override
public int hashCode() {
return filterId.hashCode();
}
}
private final static SimpleFilter r1 =
new SimpleFilter("clientId1111","filterId1111","{ \"a\" : [ 1 ] }",
Arrays.asList("dc11111", "dc21111", "dc31111"),1525821702L);
private final static SimpleFilter r2 =
new SimpleFilter("clientId2222","filterId2222","{ \"a\" : [ 2 ] }",
Arrays.asList("dc12222", "dc22222", "dc32222"),1525821702L);
private final static SimpleFilter r3 =
new SimpleFilter("clientId1111","filterId3333","{ \"a\" : [ 3 ] }",
Arrays.asList("dc13333", "dc23333", "dc33333"),1525821702L);
@Test
public void testSimplestPossibleGenericMachine() throws Exception {
String rule1 = "{ \"a\" : [ 1 ] }";
String rule2 = "{ \"b\" : [ 2 ] }";
String rule3 = "{ \"c\" : [ 3 ] }";
GenericMachine<SimpleFilter> genericMachine = new GenericMachine<>();
genericMachine.addRule(r1, rule1);
genericMachine.addRule(r2, rule2);
genericMachine.addRule(r3, rule3);
String[] event1 = { "a", "1" };
String jsonEvent1 = "{ \"a\" : 1 }" ;
String[] event2 = { "b", "2" };
String jsonEvent2 = "{ \"b\" : 2 }" ;
String[] event4 = { "x", "true" };
String jsonEvent4 = "{ \"x\" : true }" ;
String[] event5 = { "a", "1", "b", "2","c", "3"};
String jsonEvent5 = "{ \"a\" : 1, \"b\": 2, \"c\" : 3 }";
List<SimpleFilter> val;
val = genericMachine.rulesForEvent(event1);
assertEquals(1, val.size());
assertEquals(r1, val.get(0));
assertNotNull(val.get(0));
val = genericMachine.rulesForJSONEvent(jsonEvent1);
assertEquals(1, val.size());
assertEquals(r1, val.get(0));
assertNotNull(val.get(0));
val = genericMachine.rulesForEvent(event2);
assertEquals(1, val.size());
assertEquals(r2, val.get(0));
assertNotNull(val.get(0));
val = genericMachine.rulesForJSONEvent(jsonEvent2);
assertEquals(1, val.size());
assertEquals(r2, val.get(0));
assertNotNull(val.get(0));
val = genericMachine.rulesForEvent(event4);
assertEquals(0, val.size());
val = genericMachine.rulesForJSONEvent(jsonEvent4);
assertEquals(0, val.size());
val = genericMachine.rulesForEvent(event5);
assertEquals(3, val.size());
val.forEach(r -> assertTrue(Stream.of(r1, r2, r3).anyMatch(i -> (i == r))));
val = genericMachine.rulesForJSONEvent(jsonEvent5);
assertEquals(3, val.size());
val.forEach(r -> assertTrue(Stream.of(r1, r2, r3).anyMatch(i -> (i == r))));
}
@Test
public void testEvaluateComplexity() throws Exception {
String rule1 = "{ \"a\" : [ { \"wildcard\": \"a*bc\" } ] }";
String rule2 = "{ \"b\" : [ { \"wildcard\": \"a*aa\" } ] }";
String rule3 = "{ \"c\" : [ { \"wildcard\": \"xyz*\" } ] }";
GenericMachine<SimpleFilter> genericMachine = new GenericMachine<>();
genericMachine.addRule(r1, rule1);
genericMachine.addRule(r2, rule2);
genericMachine.addRule(r3, rule3);
MachineComplexityEvaluator evaluator = new MachineComplexityEvaluator(100);
assertEquals(3, genericMachine.evaluateComplexity(evaluator));
}
@Test
public void testEvaluateComplexityHitMax() throws Exception {
String rule1 = "{ \"a\" : [ { \"wildcard\": \"a*bc\" } ] }";
String rule2 = "{ \"b\" : [ { \"wildcard\": \"a*aa\" } ] }";
String rule3 = "{ \"c\" : [ { \"wildcard\": \"xyz*\" } ] }";
GenericMachine<SimpleFilter> genericMachine = new GenericMachine<>();
genericMachine.addRule(r1, rule1);
genericMachine.addRule(r2, rule2);
genericMachine.addRule(r3, rule3);
MachineComplexityEvaluator evaluator = new MachineComplexityEvaluator(2);
assertEquals(2, genericMachine.evaluateComplexity(evaluator));
}
@Test
public void testEmptyInput() throws Exception {
String rule1 = "{\n" + "\"detail\": {\n" + " \"c-count\": [ { \"exists\": false } ]\n" + "},\n"
+ "\"d-count\": [ { \"exists\": false } ],\n" + "\"e-count\": [ { \"exists\": false } ]\n" + "}";
String event = "{}";
GenericMachine<String> genericMachine = new GenericMachine<>();
genericMachine.addRule("rule1", rule1);
List<String> rules = genericMachine.rulesForJSONEvent(event);
assertTrue(rules.contains("rule1"));
rules = genericMachine.rulesForEvent(new ArrayList<>());
assertTrue(rules.contains("rule1"));
}
}
| 4,870 |
0 | Create_ds/event-ruler/src/test/software/amazon/event/ruler | Create_ds/event-ruler/src/test/software/amazon/event/ruler/input/InputByteTest.java | package software.amazon.event.ruler.input;
import org.junit.Test;
import static software.amazon.event.ruler.input.InputCharacterType.BYTE;
import static software.amazon.event.ruler.input.DefaultParser.ASTERISK_BYTE;
import static software.amazon.event.ruler.input.DefaultParser.BACKSLASH_BYTE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class InputByteTest {
@Test
public void testGetType() {
assertEquals(BYTE, new InputByte(ASTERISK_BYTE).getType());
}
@Test
public void testGetByte() {
assertEquals(ASTERISK_BYTE, new InputByte(ASTERISK_BYTE).getByte());
}
@Test
public void testEquals() {
assertTrue(new InputByte(ASTERISK_BYTE).equals(new InputByte(ASTERISK_BYTE)));
assertFalse(new InputByte(ASTERISK_BYTE).equals(new InputByte(BACKSLASH_BYTE)));
assertFalse(new InputByte(ASTERISK_BYTE).equals(new InputWildcard()));
}
@Test
public void testHashCode() {
assertEquals(Byte.valueOf((byte) 'a').hashCode(), new InputByte((byte) 'a').hashCode());
assertNotEquals(Byte.valueOf((byte) 'a').hashCode(), new InputByte((byte) 'b').hashCode());
}
}
| 4,871 |
0 | Create_ds/event-ruler/src/test/software/amazon/event/ruler | Create_ds/event-ruler/src/test/software/amazon/event/ruler/input/ParserTest.java | package software.amazon.event.ruler.input;
import software.amazon.event.ruler.MatchType;
import org.junit.Test;
import static software.amazon.event.ruler.input.DefaultParser.getParser;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class ParserTest {
@Test
public void testParseByte() {
assertEquals(new InputByte((byte) 'a'), getParser().parse((byte) 'a'));
}
@Test
public void testParseString() {
assertArrayEquals(new InputCharacter[] { new InputByte((byte) 'a'),
new InputByte((byte) '*'),
new InputByte((byte) 'c') },
getParser().parse(MatchType.EXACT, "a*c"));
}
@Test
public void testOtherMatchTypes() {
final int[] parserInvokedCount = { 0, 0, 0, 0 };
DefaultParser parser = new DefaultParser(
new WildcardParser() {
@Override
public InputCharacter[] parse(String value) {
parserInvokedCount[0] +=1;
return null;
}
},
new EqualsIgnoreCaseParser() {
@Override
public InputCharacter[] parse(String value) {
parserInvokedCount[1] += 1;
return null;
}
},
new SuffixParser() {
@Override
public InputCharacter[] parse(String value) {
parserInvokedCount[2] += 1;
return null;
}
},
new SuffixEqualsIgnoreCaseParser() {
@Override
public InputCharacter[] parse(String value) {
parserInvokedCount[3] += 1;
return null;
}
}
);
assertNull(parser.parse(MatchType.WILDCARD, "abc"));
assertEquals(parserInvokedCount[0], 1);
assertEquals(parserInvokedCount[1], 0);
assertEquals(parserInvokedCount[2], 0);
assertEquals(parserInvokedCount[3], 0);
assertNull(parser.parse(MatchType.EQUALS_IGNORE_CASE, "abc"));
assertEquals(parserInvokedCount[0], 1);
assertEquals(parserInvokedCount[1], 1);
assertEquals(parserInvokedCount[2], 0);
assertEquals(parserInvokedCount[3], 0);
assertNull(parser.parse(MatchType.SUFFIX, "abc"));
assertEquals(parserInvokedCount[0], 1);
assertEquals(parserInvokedCount[1], 1);
assertEquals(parserInvokedCount[2], 1);
assertEquals(parserInvokedCount[3], 0);
assertNull(parser.parse(MatchType.SUFFIX_EQUALS_IGNORE_CASE, "abc"));
assertEquals(parserInvokedCount[0], 1);
assertEquals(parserInvokedCount[1], 1);
assertEquals(parserInvokedCount[2], 1);
assertEquals(parserInvokedCount[3], 1);
}
}
| 4,872 |
0 | Create_ds/event-ruler/src/test/software/amazon/event/ruler | Create_ds/event-ruler/src/test/software/amazon/event/ruler/input/InputMultiByteSetTest.java | package software.amazon.event.ruler.input;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static software.amazon.event.ruler.input.InputCharacterType.MULTI_BYTE_SET;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class InputMultiByteSetTest {
@Test
public void testGetType() {
assertEquals(MULTI_BYTE_SET,
new InputMultiByteSet(new HashSet<>(Arrays.asList(new MultiByte((byte) 'a')))).getType());
}
@Test
public void testCast() {
InputCharacter character = new InputMultiByteSet(new HashSet<>(Arrays.asList(new MultiByte((byte) 'a'))));
assertSame(character, InputMultiByteSet.cast(character));
}
@Test
public void testGetMultiBytes() {
Set<MultiByte> multiBytes = new HashSet<>(Arrays.asList(new MultiByte((byte) 'a')));
assertEquals(multiBytes, new InputMultiByteSet(multiBytes).getMultiBytes());
}
@Test
public void testEquals() {
InputMultiByteSet setA1 = new InputMultiByteSet(new HashSet<>(Arrays.asList(new MultiByte((byte) 'a'))));
InputMultiByteSet setA2 = new InputMultiByteSet(new HashSet<>(Arrays.asList(new MultiByte((byte) 'a'))));
InputMultiByteSet setB = new InputMultiByteSet(new HashSet<>(Arrays.asList(new MultiByte((byte) 'b'))));
assertTrue(setA1.equals(setA2));
assertFalse(setA1.equals(setB));
assertFalse(setA1.equals(new InputWildcard()));
}
@Test
public void testHashCode() {
InputMultiByteSet setA1 = new InputMultiByteSet(new HashSet<>(Arrays.asList(new MultiByte((byte) 'a'))));
InputMultiByteSet setA2 = new InputMultiByteSet(new HashSet<>(Arrays.asList(new MultiByte((byte) 'a'))));
InputMultiByteSet setB = new InputMultiByteSet(new HashSet<>(Arrays.asList(new MultiByte((byte) 'b'))));
assertEquals(setA1.hashCode(), setA2.hashCode());
assertNotEquals(setA1.hashCode(), setB.hashCode());
}
}
| 4,873 |
0 | Create_ds/event-ruler/src/test/software/amazon/event/ruler | Create_ds/event-ruler/src/test/software/amazon/event/ruler/input/SuffixEqualsIgnoreCaseParserTest.java | package software.amazon.event.ruler.input;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashSet;
import static org.junit.Assert.assertArrayEquals;
public class SuffixEqualsIgnoreCaseParserTest {
private SuffixEqualsIgnoreCaseParser parser;
@Before
public void setup() {
parser = new SuffixEqualsIgnoreCaseParser();
}
@Test
public void testParseSimpleString() {
assertArrayEquals(new InputCharacter[] {
set(new MultiByte((byte) 97), new MultiByte((byte) 65)),
set(new MultiByte((byte) 98), new MultiByte((byte) 66)),
set(new MultiByte((byte) 99), new MultiByte((byte) 67)),
}, parser.parse("aBc"));
}
@Test
public void testParseSimpleStringWithNonLetters() {
assertArrayEquals(new InputCharacter[] {
set(new MultiByte((byte) 97), new MultiByte((byte) 65)),
new InputByte((byte) 49),
set(new MultiByte((byte) 98), new MultiByte((byte) 66)),
new InputByte((byte) 50),
set(new MultiByte((byte) 99), new MultiByte((byte) 67)),
new InputByte((byte) 33),
}, parser.parse("a1B2c!"));
}
@Test
public void testParseStringWithSingleBytesMultiBytesCharactersNonCharactersAndDifferingLengthMultiBytes() {
assertArrayEquals(new InputCharacter[] {
new InputByte((byte) 49),
set(new MultiByte((byte) 97), new MultiByte((byte) 65)),
set(new MultiByte((byte) 97), new MultiByte((byte) 65)),
new InputByte((byte) 42),
new InputByte((byte) -96), new InputByte((byte) -128), new InputByte((byte) -30),
set(new MultiByte((byte) -119, (byte) -61), new MultiByte((byte) -87, (byte) -61)),
set(new MultiByte((byte) -70, (byte) -56), new MultiByte((byte) -91, (byte) -79, (byte) -30)),
}, parser.parse("1aA*†Éⱥ"));
}
private static InputMultiByteSet set(MultiByte ... multiBytes) {
return new InputMultiByteSet(new HashSet<>(Arrays.asList(multiBytes)));
}
} | 4,874 |
0 | Create_ds/event-ruler/src/test/software/amazon/event/ruler | Create_ds/event-ruler/src/test/software/amazon/event/ruler/input/WildcardParserTest.java | package software.amazon.event.ruler.input;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class WildcardParserTest {
private WildcardParser parser;
@Before
public void setup() {
parser = new WildcardParser();
}
@Test
public void testParseNoSpecialCharacters() {
assertArrayEquals(toArray(toByte('a'), toByte('b'), toByte('c')), parser.parse("abc"));
}
@Test
public void testParseWithWildcard() {
assertArrayEquals(toArray(toByte('a'), wildcard(), toByte('c')), parser.parse("a*c"));
}
@Test
public void testParseWithEscapedAsterisk() {
assertArrayEquals(toArray(toByte('a'), toByte('*'), toByte('c')), parser.parse("a\\*c"));
}
@Test
public void testParseWithEscapedBackslash() {
assertArrayEquals(toArray(toByte('a'), toByte('\\'), toByte('c')), parser.parse("a\\\\c"));
}
@Test
public void testParseWithEscapedBackslashThenWildcard() {
assertArrayEquals(toArray(toByte('a'), toByte('\\'), wildcard()), parser.parse("a\\\\*"));
}
@Test
public void testParseWithEscapedBackslashThenEscapedAsterisk() {
assertArrayEquals(toArray(toByte('a'), toByte('\\'), toByte('*')), parser.parse("a\\\\\\*"));
}
@Test
public void testParseWithEscapedAsteriskThenWildcard() {
assertArrayEquals(toArray(toByte('a'), toByte('*'), wildcard()), parser.parse("a\\**"));
}
@Test
public void testParseWithInvalidEscapeCharacter() {
try {
parser.parse("a\\bc");
fail("Expected ParseException");
} catch (ParseException e) {
assertEquals("Invalid escape character at pos 1", e.getMessage());
}
}
@Test
public void testParseWithConsecutiveWildcardCharacters() {
try {
parser.parse("a**");
fail("Expected ParseException");
} catch (ParseException e) {
assertEquals("Consecutive wildcard characters at pos 1", e.getMessage());
}
}
private static InputCharacter[] toArray(InputCharacter ... chars) {
return chars;
}
private static InputByte toByte(char c) {
return new InputByte((byte) c);
}
private static InputWildcard wildcard() {
return new InputWildcard();
}
}
| 4,875 |
0 | Create_ds/event-ruler/src/test/software/amazon/event/ruler | Create_ds/event-ruler/src/test/software/amazon/event/ruler/input/ParseExceptionTest.java | package software.amazon.event.ruler.input;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ParseExceptionTest {
@Test
public void testGetMessage() {
String msg = "kaboom";
ParseException e = new ParseException(msg);
assertEquals(msg, e.getMessage());
}
}
| 4,876 |
0 | Create_ds/event-ruler/src/test/software/amazon/event/ruler | Create_ds/event-ruler/src/test/software/amazon/event/ruler/input/EqualsIgnoreCaseParserTest.java | package software.amazon.event.ruler.input;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashSet;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class EqualsIgnoreCaseParserTest {
private EqualsIgnoreCaseParser parser;
@Before
public void setup() {
parser = new EqualsIgnoreCaseParser();
}
@Test
public void testParseEmptyString() {
assertEquals(0, parser.parse("").length);
}
@Test
public void testParseSimpleString() {
assertArrayEquals(new InputCharacter[] {
set(new MultiByte((byte) 97), new MultiByte((byte) 65)),
set(new MultiByte((byte) 98), new MultiByte((byte) 66)),
set(new MultiByte((byte) 99), new MultiByte((byte) 67)),
}, parser.parse("aBc"));
}
@Test
public void testParseSimpleStringWithNonLetters() {
assertArrayEquals(new InputCharacter[] {
set(new MultiByte((byte) 97), new MultiByte((byte) 65)),
new InputByte((byte) 49),
set(new MultiByte((byte) 98), new MultiByte((byte) 66)),
new InputByte((byte) 50),
set(new MultiByte((byte) 99), new MultiByte((byte) 67)),
new InputByte((byte) 33),
}, parser.parse("a1B2c!"));
}
@Test
public void testParseStringWithSingleBytesMultiBytesCharactersNonCharactersAndDifferingLengthMultiBytes() {
assertArrayEquals(new InputCharacter[] {
new InputByte((byte) 49),
set(new MultiByte((byte) 97), new MultiByte((byte) 65)),
set(new MultiByte((byte) 97), new MultiByte((byte) 65)),
new InputByte((byte) 42),
new InputByte((byte) -30), new InputByte((byte) -128), new InputByte((byte) -96),
set(new MultiByte((byte) -61, (byte) -87), new MultiByte((byte) -61, (byte) -119)),
set(new MultiByte((byte) -30, (byte) -79, (byte) -91), new MultiByte((byte) -56, (byte) -70))
}, parser.parse("1aA*†Éⱥ"));
}
private static InputMultiByteSet set(MultiByte ... multiBytes) {
return new InputMultiByteSet(new HashSet<>(Arrays.asList(multiBytes)));
}
}
| 4,877 |
0 | Create_ds/event-ruler/src/test/software/amazon/event/ruler | Create_ds/event-ruler/src/test/software/amazon/event/ruler/input/MultiByteTest.java | package software.amazon.event.ruler.input;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import static software.amazon.event.ruler.input.DefaultParser.NINE_BYTE;
import static software.amazon.event.ruler.input.DefaultParser.ZERO_BYTE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class MultiByteTest {
@Test
public void testNoBytes() {
try {
new MultiByte();
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) { }
}
@Test
public void testGetBytes() {
byte[] bytes = new byte[] { (byte) 'a', (byte) 'b' };
assertArrayEquals(bytes, new MultiByte(bytes).getBytes());
}
@Test
public void testSingularIsSingular() {
assertEquals((byte) 'a', new MultiByte((byte) 'a').singular());
}
@Test
public void testSingularIsNotSingular() {
try {
new MultiByte((byte) 'a', (byte) 'b').singular();
fail("Expected IllegalStateException");
} catch (IllegalStateException e) { }
}
@Test
public void testIs() {
assertTrue(new MultiByte((byte) 'a', (byte) 'b').is((byte) 'a', (byte) 'b'));
assertFalse(new MultiByte((byte) 'a', (byte) 'b').is((byte) 'a'));
assertFalse(new MultiByte((byte) 'a', (byte) 'b').is((byte) 'a', (byte) 'c'));
assertFalse(new MultiByte((byte) 'a', (byte) 'b').is((byte) 'b', (byte) 'a'));
}
@Test
public void testIsNumeric() {
for (int i = 0; i < 10; i++) {
assertTrue(new MultiByte(String.valueOf(i).getBytes(StandardCharsets.UTF_8)).isNumeric());
}
assertFalse(new MultiByte(ZERO_BYTE, NINE_BYTE).isNumeric());
assertFalse(new MultiByte((byte) 'a').isNumeric());
assertFalse(new MultiByte((byte) '*').isNumeric());
assertFalse(new MultiByte((byte) '†').isNumeric());
assertFalse(new MultiByte((byte) 'É').isNumeric());
assertFalse(new MultiByte((byte) 'ⱥ').isNumeric());
}
@Test
public void testIsLessThan() {
assertFalse(new MultiByte((byte) 0x01, (byte) 0xA1).isLessThan(new MultiByte((byte) 0x01, (byte) 0xA1)));
assertTrue(new MultiByte((byte) 0x01, (byte) 0xA1).isLessThan(new MultiByte((byte) 0x01, (byte) 0xA2)));
assertFalse(new MultiByte((byte) 0x01, (byte) 0xA1).isLessThan(new MultiByte((byte) 0x01, (byte) 0xA0)));
assertTrue(new MultiByte((byte) 0x01, (byte) 0xA1).isLessThan(new MultiByte((byte) 0x02, (byte) 0xA1)));
assertFalse(new MultiByte((byte) 0x01, (byte) 0xA1).isLessThan(new MultiByte((byte) 0x00, (byte) 0xA1)));
assertFalse(new MultiByte((byte) 0x01, (byte) 0xA1).isLessThan(new MultiByte((byte) 0x01)));
assertTrue(new MultiByte((byte) 0x01).isLessThan(new MultiByte((byte) 0x01, (byte) 0xA1)));
}
@Test
public void testIsLessThanOrEqualTo() {
assertTrue(new MultiByte((byte) 0x01, (byte) 0xA1).isLessThanOrEqualTo(new MultiByte((byte) 0x01, (byte) 0xA1)));
assertTrue(new MultiByte((byte) 0x01, (byte) 0xA1).isLessThanOrEqualTo(new MultiByte((byte) 0x01, (byte) 0xA2)));
assertFalse(new MultiByte((byte) 0x01, (byte) 0xA1).isLessThanOrEqualTo(new MultiByte((byte) 0x01, (byte) 0xA0)));
assertTrue(new MultiByte((byte) 0x01, (byte) 0xA1).isLessThanOrEqualTo(new MultiByte((byte) 0x02, (byte) 0xA1)));
assertFalse(new MultiByte((byte) 0x01, (byte) 0xA1).isLessThanOrEqualTo(new MultiByte((byte) 0x00, (byte) 0xA1)));
assertFalse(new MultiByte((byte) 0x01, (byte) 0xA1).isLessThanOrEqualTo(new MultiByte((byte) 0x01)));
assertTrue(new MultiByte((byte) 0x01).isLessThanOrEqualTo(new MultiByte((byte) 0x01, (byte) 0xA1)));
}
@Test
public void testIsGreaterThan() {
assertFalse(new MultiByte((byte) 0x01, (byte) 0xA1).isGreaterThan(new MultiByte((byte) 0x01, (byte) 0xA1)));
assertFalse(new MultiByte((byte) 0x01, (byte) 0xA1).isGreaterThan(new MultiByte((byte) 0x01, (byte) 0xA2)));
assertTrue(new MultiByte((byte) 0x01, (byte) 0xA1).isGreaterThan(new MultiByte((byte) 0x01, (byte) 0xA0)));
assertFalse(new MultiByte((byte) 0x01, (byte) 0xA1).isGreaterThan(new MultiByte((byte) 0x02, (byte) 0xA1)));
assertTrue(new MultiByte((byte) 0x01, (byte) 0xA1).isGreaterThan(new MultiByte((byte) 0x00, (byte) 0xA1)));
assertTrue(new MultiByte((byte) 0x01, (byte) 0xA1).isGreaterThan(new MultiByte((byte) 0x01)));
assertFalse(new MultiByte((byte) 0x01).isGreaterThan(new MultiByte((byte) 0x01, (byte) 0xA1)));
}
@Test
public void testIsGreaterThanOrEqualTo() {
assertTrue(new MultiByte((byte) 0x01, (byte) 0xA1).isGreaterThanOrEqualTo(new MultiByte((byte) 0x01, (byte) 0xA1)));
assertFalse(new MultiByte((byte) 0x01, (byte) 0xA1).isGreaterThanOrEqualTo(new MultiByte((byte) 0x01, (byte) 0xA2)));
assertTrue(new MultiByte((byte) 0x01, (byte) 0xA1).isGreaterThanOrEqualTo(new MultiByte((byte) 0x01, (byte) 0xA0)));
assertFalse(new MultiByte((byte) 0x01, (byte) 0xA1).isGreaterThanOrEqualTo(new MultiByte((byte) 0x02, (byte) 0xA1)));
assertTrue(new MultiByte((byte) 0x01, (byte) 0xA1).isGreaterThanOrEqualTo(new MultiByte((byte) 0x00, (byte) 0xA1)));
assertTrue(new MultiByte((byte) 0x01, (byte) 0xA1).isGreaterThanOrEqualTo(new MultiByte((byte) 0x01)));
assertFalse(new MultiByte((byte) 0x01).isGreaterThanOrEqualTo(new MultiByte((byte) 0x01, (byte) 0xA1)));
}
@Test
public void testEquals() {
assertTrue(new MultiByte((byte) 'a', (byte) 'b').equals(new MultiByte((byte) 'a', (byte) 'b')));
assertFalse(new MultiByte((byte) 'a', (byte) 'b').equals(new MultiByte((byte) 'b', (byte) 'a')));
assertFalse(new MultiByte((byte) 'a', (byte) 'b').equals(new MultiByte((byte) 'a', (byte) 'c')));
assertFalse(new MultiByte((byte) 'a', (byte) 'b').equals(new MultiByte((byte) 'a')));
assertFalse(new MultiByte((byte) 'a', (byte) 'b').equals(new MultiByte((byte) 'a', (byte) 'b', (byte) 'c')));
assertFalse(new MultiByte((byte) 'a', (byte) 'b').equals(new Object()));
}
@Test
public void testHashCode() {
assertEquals(new MultiByte((byte) 'a').hashCode(), new MultiByte((byte) 'a').hashCode());
assertNotEquals(new MultiByte((byte) 'a').hashCode(), new MultiByte((byte) 'b').hashCode());
}
}
| 4,878 |
0 | Create_ds/event-ruler/src/test/software/amazon/event/ruler | Create_ds/event-ruler/src/test/software/amazon/event/ruler/input/InputWildcardTest.java | package software.amazon.event.ruler.input;
import org.junit.Test;
import static software.amazon.event.ruler.input.InputCharacterType.WILDCARD;
import static software.amazon.event.ruler.input.DefaultParser.ASTERISK_BYTE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class InputWildcardTest {
@Test
public void testGetType() {
assertEquals(WILDCARD, new InputWildcard().getType());
}
@Test
public void testEquals() {
assertTrue(new InputWildcard().equals(new InputWildcard()));
assertFalse(new InputWildcard().equals(new InputByte(ASTERISK_BYTE)));
}
@Test
public void testHashCode() {
assertEquals(new InputWildcard().hashCode(), new InputWildcard().hashCode());
}
}
| 4,879 |
0 | Create_ds/event-ruler/src/test/software/amazon/event/ruler | Create_ds/event-ruler/src/test/software/amazon/event/ruler/input/SuffixParserTest.java | package software.amazon.event.ruler.input;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class SuffixParserTest {
private SuffixParser parser;
@Before
public void setup() {
parser = new SuffixParser();
}
@Test
public void testParseSimpleString() {
assertArrayEquals(new InputCharacter[] {
new InputByte((byte) 34), new InputByte((byte) 97) ,
new InputByte((byte) 98), new InputByte((byte) 99)
}, parser.parse("\"abc"));
}
@Test
public void testParseReverseString() {
assertArrayEquals(new InputCharacter[] {
new InputByte((byte) 34), new InputByte((byte) 100) , new InputByte((byte) 99) ,
new InputByte((byte) 98), new InputByte((byte) 97)
}, parser.parse("\"dcba"));
}
@Test
public void testParseChineseString() {
assertArrayEquals(new InputCharacter[] {
new InputByte((byte) 34), new InputByte((byte) -88) ,
new InputByte((byte) -101), new InputByte((byte) -23)
}, parser.parse("\"雨"));
}
} | 4,880 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/NameStateWithPattern.java | package software.amazon.event.ruler;
import javax.annotation.Nullable;
import java.util.Objects;
import static java.util.Objects.requireNonNull;
/**
* Class that holds a NameState and the Pattern from the match that led to the NameState.
*/
public class NameStateWithPattern {
private final NameState nameState;
private final Patterns pattern;
/**
* Create a NameStateWithPattern.
*
* @param nameState The NameState - cannot be null.
* @param pattern The pattern - can be null if the NameState is the starting state of a Machine.
*/
public NameStateWithPattern(NameState nameState, @Nullable Patterns pattern) {
this.nameState = requireNonNull(nameState);
this.pattern = pattern;
}
public NameState getNameState() {
return nameState;
}
public Patterns getPattern() {
return pattern;
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof NameStateWithPattern)) {
return false;
}
NameStateWithPattern otherNameStateWithPattern = (NameStateWithPattern) o;
return nameState.equals(otherNameStateWithPattern.nameState) &&
pattern.equals(otherNameStateWithPattern.pattern);
}
@Override
public int hashCode() {
return Objects.hash(nameState, pattern);
}
} | 4,881 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/ACStep.java | package software.amazon.event.ruler;
import java.util.Set;
/**
* Represents a suggestion of a state/token combo from which there might be a transition, in an array-consistent fashion.
*/
class ACStep {
final int fieldIndex;
final NameState nameState;
final Set<Double> candidateSubRuleIds;
final ArrayMembership membershipSoFar;
ACStep(final int fieldIndex, final NameState nameState, final Set<Double> candidateSubRuleIds,
final ArrayMembership arrayMembership) {
this.fieldIndex = fieldIndex;
this.nameState = nameState;
this.candidateSubRuleIds = candidateSubRuleIds;
this.membershipSoFar = arrayMembership;
}
}
| 4,882 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/SubRuleContext.java | package software.amazon.event.ruler;
/**
* This class stores context regarding a sub-rule.
*
* A sub-rule refers to name/value pairs, usually represented by Map of String to List of Patterns, that compose a rule.
* In the case of $or, one rule will have multiple name/value pairs, and this is why we use the "sub-rule" terminology.
*/
public class SubRuleContext {
private final double id;
private SubRuleContext(double id) {
this.id = id;
}
public double getId() {
return id;
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof SubRuleContext)) {
return false;
}
SubRuleContext otherContext = (SubRuleContext) o;
return id == otherContext.id;
}
@Override
public int hashCode() {
return Double.hashCode(id);
}
/**
* Generator for SubRuleContexts.
*/
static final class Generator {
private double nextId = -Double.MAX_VALUE;
public SubRuleContext generate() {
assert nextId < Double.MAX_VALUE : "SubRuleContext.Generator's nextId reached Double.MAX_VALUE - " +
"this required the equivalent of calling generate() at 6 billion TPS for 100 years";
SubRuleContext subRuleContext = new SubRuleContext(nextId);
nextId = Math.nextUp(nextId);
return subRuleContext;
}
}
}
| 4,883 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/ComparableNumber.java | package software.amazon.event.ruler;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
/**
* Represents a number, turned into a comparable string
* Numbers are allowed in the range -50**9 .. +50**9, inclusive
* Comparisons are precise to 6 digits to the right of the decimal point
* They are all treated as floating point
* They are turned into strings by:
* 1. Add 10**9 (so no negatives), then multiply by 10**6 to remove the decimal point
* 2. Format to a 14 char string left padded with 0 because hex string converted from 5e9*1e6=10e15 has 14 characters.
* Note: We use Hex because of a) it can save 3 bytes memory per number than decimal b) it aligned IP address radix.
* If needed, we can consider to use 32 or 64 radix description to save more memory,e.g. the string length will be 10
* for 32 radix, and 9 for 64 radix.
*
* Note:
* The number is parsed to be java double to support number with decimal fraction, the max range supported is from
* -5e9 to 5e9 with precision of 6 digits to the right of decimal point.
* There is well known issue that double number will lose the precision while calculation among double and other data
* types, the higher the number, the lower the accuracy that can be maintained.
* For example: 0.30d - 0.10d = 0.19999999999999998 instead of 0.2d, and if extend to 1e10, the test result shows only
* 5 digits of precision from right of decimal point can be guaranteed with existing implementation.
* The current max number 5e9 is selected with a balance between keeping the committed 6 digits of precision from right
* of decimal point and the memory cost (each number is parsed into a 14 characters HEX string).
*
* CAVEAT:
* When there is need to further enlarging the max number, PLEASE BE VERY CAREFUL TO RESERVE THE NUMBER PRECISION AND
* TAKEN THE MEMORY COST INTO CONSIDERATION, BigDecimal shall be used to ensure the precision of double calculation ...
*/
class ComparableNumber {
private static final double TEN_E_SIX = 1E6;
static final int MAX_LENGTH_IN_BYTES = 16;
private static final String HEXES = new String(Constants.HEX_DIGITS, StandardCharsets.US_ASCII);
public static final int NIBBLE_SIZE = 4;
// 1111 0000
private static final int UPPER_NIBBLE_MASK = 0xF0;
// 0000 1111
private static final int LOWER_NIBBLE_MASK = 0x0F;
private ComparableNumber() {
}
static String generate(final double f) {
if (f < -Constants.FIVE_BILLION || f > Constants.FIVE_BILLION) {
throw new IllegalArgumentException("Value must be between " + -Constants.FIVE_BILLION +
" and " + Constants.FIVE_BILLION + ", inclusive");
}
return toHexStringSkippingFirstByte((long) (TEN_E_SIX * (Constants.FIVE_BILLION + f)));
}
/**
* converts a single byte to its two hexadecimal character representation
* @param value the byte we want to convert to hex string
* @return a 2 digit char array with the equivalent hex representation
*/
static char[] byteToHexChars(byte value) {
char[] result = new char[2];
int upperNibbleIndex = (value & UPPER_NIBBLE_MASK) >> NIBBLE_SIZE;
int lowerNibbleIndex = value & LOWER_NIBBLE_MASK;
result[0] = HEXES.charAt(upperNibbleIndex);
result[1] = HEXES.charAt(lowerNibbleIndex);
return result;
}
private static byte[] longToByteBuffer(long value) {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.putLong(value);
return buffer.array();
}
static String toHexStringSkippingFirstByte(long value) {
byte[] raw = longToByteBuffer(value);
char[] outputChars = new char[14];
for (int i = 1; i < raw.length; i++) {
int pos = (i - 1) * 2;
char[] currentByteChars = byteToHexChars(raw[i]);
outputChars[pos] = currentByteChars[0];
outputChars[pos + 1] = currentByteChars[1];
}
return new String(outputChars);
}
}
| 4,884 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/ArrayMembership.java | package software.amazon.event.ruler;
/**
* Represents which JSON arrays within an Event structure a particular field appears within, and at which position.
* The arrays are identified using integers.
*/
class ArrayMembership {
private static final IntIntMap EMPTY = new IntIntMap();
private IntIntMap membership;
ArrayMembership() {
membership = new IntIntMap();
}
ArrayMembership(final ArrayMembership membership) {
if (membership.size() == 0) {
this.membership = EMPTY;
} else {
this.membership = (IntIntMap) membership.membership.clone();
}
}
void putMembership(int array, int index) {
if (index == IntIntMap.NO_VALUE) {
membership.remove(array);
} else {
membership.put(array, index);
}
}
void deleteMembership(int array) {
membership.remove(array);
}
int getMembership(int array) {
return membership.get(array);
}
boolean isEmpty() {
return membership.isEmpty();
}
private int size() {
return membership.size();
}
// for debugging
public String toString() {
StringBuilder sb = new StringBuilder();
for (IntIntMap.Entry entry : membership.entries()) {
sb.append(entry.getKey()).append('[').append(entry.getValue()).append("] ");
}
return sb.toString();
}
/**
* We are stepping through the NameState machine field by field, and have built up data on the array memberships
* observed so far in this map. We need to compare this to the array-membership data of the field we're looking at
* and see if they are consistent. Either or both memberships might be empty, which simplifies things.
* Method returns null if the new field's membership is inconsistent with so-far membership. If it is compatible,
* returns the possibly-revised array membership of the matching task.
*
* @param fieldMembership Array membership of the field under consideration
* @param membershipSoFar Array membership observed so far in a rule-matching task
* @return null or the new matching-task membership so far
*/
static ArrayMembership checkArrayConsistency(final ArrayMembership membershipSoFar, final ArrayMembership fieldMembership) {
// no existing memberships, so we'll take the ones from the field, if any
if (membershipSoFar.isEmpty()) {
return fieldMembership.isEmpty() ? membershipSoFar : new ArrayMembership(fieldMembership);
}
// any change will come from memberships in the new field we're investigating. For each of its memberships
ArrayMembership newMembership = null;
for (IntIntMap.Entry arrayEntry : fieldMembership.membership.entries()) {
final int array = arrayEntry.getKey();
final int indexInThisArrayOfThisField = arrayEntry.getValue();
final int indexInThisArrayPreviouslyAppearingInMatch = membershipSoFar.getMembership(array);
if (indexInThisArrayPreviouslyAppearingInMatch == IntIntMap.NO_VALUE) {
// if there's no membership so far, this is an acceptable delta. Update the new memberships, first
// creating it if necessary
if (newMembership == null) {
newMembership = new ArrayMembership(membershipSoFar);
}
newMembership.putMembership(array, indexInThisArrayOfThisField);
} else {
// This field does appear within an index that has already appeared in the matching task so far.
// If it's in the same element, fine, no updates. If it's a different entry, return null to
// signal array-inconsistency.
if (indexInThisArrayOfThisField != indexInThisArrayPreviouslyAppearingInMatch) {
return null;
}
}
}
// we may have scanned all the fields and not added anything, in which case return the input
return (newMembership == null) ? membershipSoFar : newMembership;
}
}
| 4,885 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/Patterns.java | package software.amazon.event.ruler;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* The Patterns deal pre-processing of rules for the eventual matching against events.
* It has subclasses for different match types (like ValuePatterns, Ranges, AnythingBut, etc).
* This class also acts as the factory for to build patterns which is useful if you have
* key value pairs and would like to build your rules for them directly instead of using the fancy
* JSON query language (and its compiler). Once you build rules, you can add them via `Machine.addRule()`.
*
* NOTE: The subclasses have additional builders that are only needed by JSON rule compilier and are
* left out of here intentionally for now.
*/
public class Patterns implements Cloneable {
public static final String EXISTS_BYTE_STRING = "N";
private final MatchType type;
// This interface is deprecated and we keep it here for backward compatibility only.
// Note: right now (5/28/2019), only ValuePatterns overrides it.
@Deprecated
public String pattern() { return null; }
Patterns(final MatchType type) {
this.type = type;
}
public MatchType type() {
return type;
}
public static ValuePatterns exactMatch(final String value) {
return new ValuePatterns(MatchType.EXACT, value);
}
// prefixes have to be given as strings, which with our semantics means they will be enclosed in "
// characters, like so: "\"foo\"". We need the starting " preserved, because that's how we pass
// string field values around. But we have to amputate the last one because it'll break the prefix
// semantics.
public static ValuePatterns prefixMatch(final String prefix) {
return new ValuePatterns(MatchType.PREFIX, prefix);
}
public static ValuePatterns prefixEqualsIgnoreCaseMatch(final String prefix) {
return new ValuePatterns(MatchType.PREFIX_EQUALS_IGNORE_CASE, prefix);
}
public static ValuePatterns suffixMatch(final String suffix) {
return new ValuePatterns(MatchType.SUFFIX, new StringBuilder(suffix).reverse().toString());
}
public static ValuePatterns suffixEqualsIgnoreCaseMatch(final String suffix) {
return new ValuePatterns(MatchType.SUFFIX_EQUALS_IGNORE_CASE, new StringBuilder(suffix).reverse().toString());
}
public static AnythingBut anythingButMatch(final String anythingBut) {
return new AnythingBut(Collections.singleton(anythingBut), false);
}
public static AnythingBut anythingButMatch(final double anythingBut) {
return new AnythingBut(Collections.singleton(ComparableNumber.generate(anythingBut)), true);
}
public static AnythingBut anythingButMatch(final Set<String> anythingButs) {
return new AnythingBut(anythingButs, false);
}
public static AnythingButEqualsIgnoreCase anythingButIgnoreCaseMatch(final String anythingBut) {
return new AnythingButEqualsIgnoreCase(Collections.singleton(anythingBut));
}
public static AnythingButEqualsIgnoreCase anythingButIgnoreCaseMatch(final Set<String> anythingButs) {
return new AnythingButEqualsIgnoreCase(anythingButs);
}
public static AnythingBut anythingButNumberMatch(final Set<Double> anythingButs) {
Set<String> normalizedNumbers = new HashSet<>(anythingButs.size());
for (Double d : anythingButs) {
normalizedNumbers.add(ComparableNumber.generate(d));
}
return new AnythingBut(normalizedNumbers, true);
}
public static ValuePatterns anythingButPrefix(final String prefix) {
return new ValuePatterns(MatchType.ANYTHING_BUT_PREFIX, prefix);
}
public static ValuePatterns anythingButSuffix(final String suffix) {
return new ValuePatterns(MatchType.ANYTHING_BUT_SUFFIX, new StringBuilder(suffix).reverse().toString());
}
public static ValuePatterns numericEquals(final double val) {
return new ValuePatterns(MatchType.NUMERIC_EQ, ComparableNumber.generate(val));
}
public static Patterns existencePatterns() {
return new Patterns(MatchType.EXISTS);
}
public static Patterns absencePatterns() {
return new Patterns(MatchType.ABSENT);
}
// Implement equals-ignore-case by doing lower-case comparisons
public static ValuePatterns equalsIgnoreCaseMatch(final String value) {
return new ValuePatterns(MatchType.EQUALS_IGNORE_CASE, value);
}
public static ValuePatterns wildcardMatch(final String value) {
return new ValuePatterns(MatchType.WILDCARD, value);
}
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return new Patterns(this.type);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || !o.getClass().equals(getClass())) {
return false;
}
Patterns patterns = (Patterns) o;
return type == patterns.type;
}
@Override
public int hashCode() {
return type != null ? type.hashCode() : 0;
}
@Override
public String toString() {
return "T:" + type;
}
}
| 4,886 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/AnythingBut.java | package software.amazon.event.ruler;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
/**
* Represents denylist like rule: any value matches if it's *not* in the anything-but list.
* It supports lists whose members must be all strings or all numbers.
* Numbers are treated as strings created with ComparableNumber.generate.
*/
public class AnythingBut extends Patterns {
private final Set<String> values;
// isNumeric: true means all the value in the Set are numbers; false means all the value are string.
private final boolean isNumeric;
AnythingBut(final Set<String> values, final boolean isNumeric) {
super(MatchType.ANYTHING_BUT);
this.values = Collections.unmodifiableSet(values);
this.isNumeric = isNumeric;
}
static AnythingBut anythingButMatch(final Set<String> values, final boolean isNumber) {
return new AnythingBut(values, isNumber);
}
public Set<String> getValues() {
return values;
}
boolean isNumeric() {
return isNumeric;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
AnythingBut that = (AnythingBut) o;
return isNumeric == that.isNumeric && (Objects.equals(values, that.values));
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (values != null ? values.hashCode() : 0);
result = 31 * result + (isNumeric ? 1 : 0);
return result;
}
@Override
public String toString() {
return "AB:"+ values + ", isNum=" + isNumeric + " (" + super.toString() + ")";
}
}
| 4,887 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/AnythingButEqualsIgnoreCase.java | package software.amazon.event.ruler;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
/**
* Represents denylist like rule: any value matches if it's *not* in the anything-but/ignore-case list.
* It supports lists whose members must be all strings.
* Matching is case-insensitive
*/
public class AnythingButEqualsIgnoreCase extends Patterns {
private final Set<String> values;
AnythingButEqualsIgnoreCase(final Set<String> values) {
super(MatchType.ANYTHING_BUT_IGNORE_CASE);
this.values = Collections.unmodifiableSet(values);
}
public Set<String> getValues() {
return values;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
AnythingButEqualsIgnoreCase that = (AnythingButEqualsIgnoreCase) o;
return (Objects.equals(values, that.values));
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (values != null ? values.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ABIC:"+ values + ", (" + super.toString() + ")";
}
}
| 4,888 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/MachineComplexityEvaluator.java | package software.amazon.event.ruler;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import static software.amazon.event.ruler.MatchType.WILDCARD;
/**
* Evaluates the complexity of machines.
*/
public class MachineComplexityEvaluator {
/**
* Cap evaluation of complexity at this threshold.
*/
private final int maxComplexity;
public MachineComplexityEvaluator(int maxComplexity) {
this.maxComplexity = maxComplexity;
}
int getMaxComplexity() {
return maxComplexity;
}
/**
* Returns the maximum possible number of wildcard rule prefixes that could match a theoretical input value for a
* machine beginning with ByteState state. This value is equivalent to the maximum number of states a traversal
* could be present in simultaneously, counting only states that can lead to a wildcard match pattern. This function
* will recursively evaluate all other machines accessible via next NameStates, and will return the maximum observed
* from any machine. Caps out evaluation at maxComplexity to keep runtime under control. Otherwise, runtime for this
* machine would be O(MN^2), where N is the number of states accessible from ByteState state, and M is the total
* number of ByteMachines accessible via next NameStates.
*
* @param state Evaluates a machine beginning at this state.
* @return The lesser of maxComplexity and the maximum possible number of wildcard rule prefixes from any machines.
*/
int evaluate(ByteState state) {
// Upfront cost: generate the map of all matches accessible from every state in the machine.
Map<SingleByteTransition, Set<ByteMatch>> matchesAccessibleFromEachTransition =
getMatchesAccessibleFromEachTransition(state);
Set<ByteTransition> visited = new HashSet<>();
visited.add(state);
int maxSize = 0;
// We'll do a breadth-first-search but it shouldn't matter.
Queue<ByteTransition> transitions = new LinkedList<>();
state.getTransitions().forEach(trans -> transitions.add(trans));
while (!transitions.isEmpty()) {
ByteTransition transition = transitions.remove();
if (visited.contains(transition)) {
continue;
}
visited.add(transition);
// The sum of all the wildcard patterns accessible from each SingleByteTransition we are present in on our
// current traversal is the number of wildcard rule prefixes matching a theoretical worst-case input value.
int size = 0;
for (SingleByteTransition single : transition.expand()) {
size += getWildcardPatterns(matchesAccessibleFromEachTransition.get(single)).size();
// Look for "transitions for all bytes" (i.e. wildcard transitions). Since an input value that matches
// foo will also match foo*, we also need to include in our size wildcard patterns accessible from foo*.
ByteState nextState = single.getNextByteState();
if (nextState != null) {
for (SingleByteTransition transitionForAllBytes : nextState.getTransitionForAllBytes().expand()) {
if (!(transitionForAllBytes instanceof ByteMachine.EmptyByteTransition) &&
!contains(transition.expand(), transitionForAllBytes)) {
size += getWildcardPatterns(matchesAccessibleFromEachTransition.get(transitionForAllBytes))
.size();
}
}
}
}
if (size >= maxComplexity) {
return maxComplexity;
}
if (size > maxSize) {
maxSize = size;
}
// Load up our queue with the next round of transitions, where each transition represents a set of states
// that could be accessed with a particular byte value.
ByteTransition nextTransition = transition.getTransitionForNextByteStates();
if (nextTransition != null) {
nextTransition.getTransitions().forEach(trans -> transitions.add(trans));
}
}
// Now that we have a maxSize for this ByteMachine, let's recursively get the maxSize for each next NameState
// accessible via any of this ByteMachine's matches. We will return the maximum maxSize.
int maxSizeFromNextNameStates = 0;
Set<ByteMatch> uniqueMatches = new HashSet<>();
for (Set<ByteMatch> matches : matchesAccessibleFromEachTransition.values()) {
uniqueMatches.addAll(matches);
}
for (ByteMatch match : uniqueMatches) {
NameState nextNameState = match.getNextNameState();
if (nextNameState != null) {
maxSizeFromNextNameStates = Math.max(maxSizeFromNextNameStates, nextNameState.evaluateComplexity(this));
}
}
return Math.max(maxSize, maxSizeFromNextNameStates);
}
/**
* Generates a map of SingleByteTransition to all the matches accessible from the SingleByteTransition. The map
* includes all SingleByteTransitions accessible from ByteState state. This function is O(N), where N is the number
* of states accessible from ByteState state.
*
* @param state Starting state.
* @return A map of SingleByteTransition to all the matches accessible from the SingleByteTransition
*/
private Map<SingleByteTransition, Set<ByteMatch>> getMatchesAccessibleFromEachTransition(ByteState state) {
Map<SingleByteTransition, Set<ByteMatch>> result = new HashMap<>();
Set<SingleByteTransition> visited = new HashSet<>();
Stack<SingleByteTransition> stack = new Stack<>();
stack.push(state);
// We'll do a depth-first-search as a state's matches can only be computed once the computation is complete for
// all deeper states. Let's avoid recursion, which is prone to stack overflow.
while (!stack.isEmpty()) {
// Peek instead of pop. Need this transition to remain on stack so we can compute its matches once all
// deeper states are complete.
SingleByteTransition transition = stack.peek();
if (!result.containsKey(transition)) {
result.put(transition, new HashSet<>());
}
Set<ByteMatch> matches = result.get(transition);
// Visited means we have already processed this transition once (via peeking) and have since computed the
// matches for all deeper states. Time to compute this transition's matches then pop it from the stack.
if (visited.contains(transition)) {
ByteState nextState = transition.getNextByteState();
if (nextState != null) {
for (ByteTransition eachTransition : nextState.getTransitions()) {
for (SingleByteTransition single : eachTransition.expand()) {
matches.addAll(result.get(single));
}
}
}
stack.pop();
continue;
}
visited.add(transition);
// Add all matches directly accessible from this transition.
transition.getMatches().forEach(match -> matches.add(match));
// Push the next round of deeper states into the stack. By the time we return back to the current transition
// on the stack, all matches for deeper states will have been computed.
ByteState nextState = transition.getNextByteState();
if (nextState != null) {
for (ByteTransition eachTransition : nextState.getTransitions()) {
for (SingleByteTransition single : eachTransition.expand()) {
if (!visited.contains(single)) {
stack.push(single);
}
}
}
}
}
return result;
}
private static boolean contains(Iterable<SingleByteTransition> iterable, SingleByteTransition single) {
if (iterable instanceof Set) {
return ((Set) iterable).contains(single);
}
for (SingleByteTransition eachSingle : iterable) {
if (single.equals(eachSingle)) {
return true;
}
}
return false;
}
private static Set<Patterns> getWildcardPatterns(Set<ByteMatch> matches) {
Set<Patterns> patterns = new HashSet<>();
for (ByteMatch match : matches) {
if (match.getPattern().type() == WILDCARD) {
patterns.add(match.getPattern());
}
}
return patterns;
}
} | 4,889 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/Machine.java | package software.amazon.event.ruler;
/**
* Represents a state machine used to match name/value patterns to rules.
* The machine is thread safe. The concurrency strategy is:
* Multi-thread access assumed, single-thread update enforced by synchronized on
* addRule/deleteRule.
* ConcurrentHashMap and ConcurrentSkipListSet are used so that writer and readers can be in tables
* simultaneously. So all changes the writer made could be synced to and viable by all readers (in other threads).
* Though it may generate a half-built rule to rulesForEvent() e.g. when a long rule is adding and
* in the middle of adding, some event is coming to query machine, it won't generate side impact with rulesForEvent
* because each step of routing will check next State and transition map before moving forward.
*/
public class Machine extends GenericMachine<String> {
public Machine() {
}
} | 4,890 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/SetOperations.java | package software.amazon.event.ruler;
import java.util.Set;
import java.util.function.Function;
class SetOperations {
private SetOperations() { }
/**
* Add each element of the intersection of two sets to a third set. This is optimized for performance as it iterates
* through the smaller set.
*
* @param set1 First set involved in intersection.
* @param set2 Second set involved in intersection.
* @param addTo Add intersection to this set.
* @param <T> Type of all three sets.
*/
public static <T> void intersection(final Set<T> set1, final Set<T> set2, final Set<T> addTo) {
intersection(set1, set2, addTo, t -> t);
}
/**
* Add the transformation of each element of the intersection of two sets to a third set. This is optimized for
* performance as it iterates through the smaller set.
*
* @param set1 First set involved in intersection.
* @param set2 Second set involved in intersection.
* @param addTo Add intersection to this set.
* @param transform Transform each element of intersection into an element of the third set.
* @param <T> Type of first two sets.
* @param <R> Type of addTo set.
*/
public static <T, R> void intersection(final Set<T> set1, final Set<T> set2, final Set<R> addTo,
final Function<T, R> transform) {
Set<T> smaller = set1.size() <= set2.size() ? set1 : set2;
Set<T> larger = set1.size() <= set2.size() ? set2 : set1;
for (T element : smaller) {
if (larger.contains(element)) {
addTo.add(transform.apply(element));
}
}
}
}
| 4,891 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/MatchType.java | package software.amazon.event.ruler;
/**
* The types of value matches that Ruler supports
*/
public enum MatchType {
EXACT, // exact string
ABSENT, // absent key pattern
EXISTS, // existence pattern
PREFIX, // string prefix
PREFIX_EQUALS_IGNORE_CASE, // case-insensitive string prefix
SUFFIX, // string suffix
SUFFIX_EQUALS_IGNORE_CASE, // case-insensitive string suffix
NUMERIC_EQ, // exact numeric match
NUMERIC_RANGE, // numeric range with high & low bound & </<=/>/>= options
ANYTHING_BUT, // deny list effect
ANYTHING_BUT_IGNORE_CASE, // deny list effect (case insensitive)
ANYTHING_BUT_PREFIX, // anything that doesn't start with this
ANYTHING_BUT_SUFFIX, // anything that doesn't end with this
EQUALS_IGNORE_CASE, // case-insensitive string match
WILDCARD, // string match using one or more non-consecutive '*' wildcard characters
}
| 4,892 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/GenericMachine.java | package software.amazon.event.ruler;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
/**
* Represents a state machine used to match name/value patterns to rules.
* The machine is thread safe. The concurrency strategy is:
* Multi-thread access assumed, single-thread update enforced by synchronized on
* addRule/deleteRule.
* ConcurrentHashMap and ConcurrentSkipListSet are used so that writer and readers can be in tables
* simultaneously. So all changes the writer made could be synced to and viable by all readers (in other threads).
* Though it may generate a half-built rule to rulesForEvent() e.g. when a long rule is adding and
* in the middle of adding, some event is coming to query machine, it won't generate side impact with rulesForEvent
* because each step of routing will check next State and transition map before moving forward.
*
* T is a type representing a Rule name, it should be an immutable class.
*/
public class GenericMachine<T> {
/**
* This could be increased but is an initial control
*/
private static final int MAXIMUM_RULE_SIZE = 256;
/**
* The start state of matching and adding rules.
*/
private final NameState startState = new NameState();
/**
* A Map of all reference counts for each step in field name separated by "." used by current rules.
* when reference count is 0, we could safely remove the key from map.
* Use ConcurrentHashMap to support concurrent access.
* For example, if we get rule { "a" : { "b" : [ 123 ] } }, the flatten field name is "a.b", the step name
* will be "a" and "b", which will be tracked in this map.
*/
private final Map<String, Integer> fieldStepsUsedRefCount = new ConcurrentHashMap<>();
/**
* Generate context for a sub-rule that can be passed through relevant methods.
*/
private final SubRuleContext.Generator subRuleContextGenerator = new SubRuleContext.Generator();
public GenericMachine() {}
/**
* Return any rules that match the fields in the event in a way that is Array-Consistent (thus trailing "AC" on
* names of implementing classes). Array-Consistent means that we reject matches where fields which are members
* of different elements of the same JSON array in the event are matched.
* @param jsonEvent The JSON representation of the event
* @return list of rule names that match. The list may be empty but never null.
*/
@SuppressWarnings("unchecked")
public List<T> rulesForJSONEvent(final String jsonEvent) throws Exception {
final Event event = new Event(jsonEvent, this);
return (List<T>) ACFinder.matchRules(event, this);
}
@SuppressWarnings("unchecked")
public List<T> rulesForJSONEvent(final JsonNode eventRoot) {
final Event event = new Event(eventRoot, this);
return (List<T>) ACFinder.matchRules(event, this);
}
/**
* Return any rules that match the fields in the event.
*
* @param jsonEvent The JSON representation of the event
* @return list of rule names that match. The list may be empty but never null.
* @deprecated The rulesForJSONEvent version provides array-consistent matching, which is probably what your users want.
*/
@Deprecated
@SuppressWarnings("unchecked")
public List<T> rulesForEvent(final String jsonEvent) {
return (List<T>) Finder.rulesForEvent(Event.flatten(jsonEvent), this);
}
/**
* Return any rules that match the fields in the event.
*
* @param event the fields are those from the JSON expression of the event, sorted by key.
* @return list of rule names that match. The list may be empty but never null.
*/
@SuppressWarnings("unchecked")
public List<T> rulesForEvent(final List<String> event) {
return (List<T>) Finder.rulesForEvent(event, this);
}
/**
* Return any rules that match the fields in the parsed Json event.
*
* @param eventRoot the root node of the parsed JSON.
* @return list of rule names that match. The list may be empty but never null.
* @deprecated The rulesForJSONEvent version provides array-consistent matching, which is probably what your users want.
*/
@Deprecated
@SuppressWarnings("unchecked")
public List<T> rulesForEvent(final JsonNode eventRoot) {
return (List<T>) Finder.rulesForEvent(Event.flatten(eventRoot), this);
}
/**
* Return any rules that match the fields in the event.
*
* @param event the fields are those from the JSON expression of the event, sorted by key.
* @return list of rule names that match. The list may be empty but never null.
*/
@SuppressWarnings("unchecked")
public List<T> rulesForEvent(final String[] event) {
return (List<T>) Finder.rulesForEvent(event, this);
}
/**
* The root state for the machine
*
* @return the root state, null if the machine has no rules in it
*/
final NameState getStartState() {
return startState;
}
/**
* Check to see whether a field step name is actually used in any rule.
*
* @param stepName the field step name to check
* @return true if the field is used in any rule, false otherwise
*/
boolean isFieldStepUsed(final String stepName) {
if (fieldStepsUsedRefCount.get(stepName) != null) {
return true;
}
// We need split step name further with "." to check each sub step individually to cover the case if customer
// use the "." internally in field of event, e.g. rule: {"a.b" : [123]} and {"a" : { "b" : [123] }} will both
// result "a" and "b" being added into fieldStepsUsedRefCount map in addPatternRule API, at that time, we
// cannot distinguish the "." is from original event or added by us when we flatten the event, but they are
// both possible to match some rules, so we do this check.
// The main reason we decided to put "recordStep" work in addPatternRule API is this API have been used by many
// customer directly already and we want them to get the same performance boost.
if (stepName.contains(".")) {
String[] steps = stepName.split("\\.");
return Arrays.stream(steps).allMatch(step -> (fieldStepsUsedRefCount.get(step) != null));
}
return false;
}
/**
* Add a rule to the machine. A rule is a set of names, each of which is associated with one or more values.
*
* "synchronized" here is to ensure that only one thread is updating the machine at any point in time.
* This method relies on the caller not changing the arguments while it is exiting - but once it has completed,
* this library has no dependence on those structures.
* Multiple rules with the same name may be incrementally added, producing an "or" relationship with
* relationship with previous namevals added for that name. E.g.
* addRule r1 with namevalue {a,[1]}, then call again with r1 {a,[2]}, it will have same effect call addRule with
* r1 {a, [1,2]}
*
* @param name ARN of the rule
* @param namevals names and values which make up the rule
*/
public void addRule(final T name, final Map<String, List<String>> namevals) {
final Map<String, List<Patterns>> patternMap = new HashMap<>();
for (final Map.Entry<String, List<String>> nameVal : namevals.entrySet()) {
patternMap.put(nameVal.getKey(), nameVal.getValue().stream().map(Patterns::exactMatch).
collect(Collectors.toList()));
}
addPatternRule(name, patternMap);
}
/**
* Add a rule to the machine. A rule is a set of names, each of which
* is associated with one or more value-patterns. These can be simple values (like "1", "a", "true")
* or more sophisticated (like {anything-but : "1", range: { ... } })
*
* @param name ARN of the rule4
* @param namevals names and values which make up the rule
*/
public void addPatternRule(final T name, final Map<String, List<Patterns>> namevals) {
if (namevals.size() > MAXIMUM_RULE_SIZE) {
throw new RuntimeException("Size of rule '" + name + "' exceeds max value of " + MAXIMUM_RULE_SIZE);
}
// clone namevals for ruler use.
Map<String, List<Patterns>> namePatterns = new HashMap<>();
for (final Map.Entry<String, List<Patterns>> nameVal : namevals.entrySet()) {
namePatterns.put(nameVal.getKey(), nameVal.getValue().stream().map(p -> (Patterns)(p.clone())).
collect(Collectors.toList()));
}
final ArrayList<String> keys = new ArrayList<>(namePatterns.keySet());
Collections.sort(keys);
synchronized(this) {
addStep(keys, namePatterns, name);
}
}
/**
* Delete rule from the machine. The rule is a set of name/values.
* "synchronized" here is to ensure that only one thread is updating the machine at any point in time.
* This method relies on the caller not changing the arguments while it is exiting - but once it has completed,
* this library has no dependence on those structures.
* As with addRule, multiple name/val patterns attached to a rule name may be removed all at once or
* one by one.
* Machine will only remove a rule which both matches the name/vals and the provided rule name:
* - if name/vals provided have not reached any rules, return;
* - if name/vals provided have reached any rules, only rule which matched the input rule name will be removed.
*
* Note: this API will only probe rule which is able to be approached by input namevalues,
* it doesn't remove all rules associated with rule name unless the input rule expression have covered all rules
* associated with rule name. For example:
* r1 {a, [1,2]} was added into machine, you could call deleteRule with r1 {a, [1]}, machine in this case will
* delete r1 {a, [1]} only, so event like a=1 will not match r1 any more.
* if caller calls deleteRule again with input r1 {a, [2]}, machine will remove another rule of r1.
* The eventual result will be same as one time deleteRule call with r1 {a, [1,2]}.
* So, caller is expected to save its rule expression if want to entirely remove the rule unless deliberately
* want to remove partial rule from rule name.
*
* @param name ARN of the rule
* @param namevals names and values which make up the rule
*/
public void deletePatternRule(final T name, final Map<String, List<Patterns>> namevals) {
if (namevals.size() > MAXIMUM_RULE_SIZE) {
throw new RuntimeException("Size of rule '" + name + "' exceeds max value of " + MAXIMUM_RULE_SIZE);
}
final List<String> keys = new ArrayList<>(namevals.keySet());
Collections.sort(keys);
synchronized(this) {
final List<String> deletedKeys = new ArrayList<>();
final Set<Double> candidateSubRuleIds = new HashSet<>();
deleteStep(getStartState(), keys, 0, namevals, name, deletedKeys, candidateSubRuleIds);
// check and delete the key from filedUsed ...
checkAndDeleteUsedFields(deletedKeys);
}
}
public void deleteRule(final T name, final Map<String, List<String>> namevals) {
final Map<String, List<Patterns>> patternMap = new HashMap<>();
for (final Map.Entry<String, List<String>> nameVal : namevals.entrySet()) {
patternMap.put(nameVal.getKey(), nameVal.getValue().stream().map(Patterns::exactMatch)
.collect(Collectors.toList()));
}
deletePatternRule(name, patternMap);
}
private Set<Double> deleteStep(final NameState state,
final List<String> keys,
final int keyIndex,
final Map<String, List<Patterns>> patterns,
final T ruleName,
final List<String> deletedKeys,
final Set<Double> candidateSubRuleIds) {
final Set<Double> deletedSubRuleIds = new HashSet<>();
final String key = keys.get(keyIndex);
ByteMachine byteMachine = state.getTransitionOn(key);
NameMatcher<NameState> nameMatcher = state.getKeyTransitionOn(key);
// matchers are null, we have nothing to delete.
if (byteMachine == null && nameMatcher == null) {
return deletedSubRuleIds;
}
for (Patterns pattern : patterns.get(key)) {
NameState nextNameState = null;
if (isNamePattern(pattern)) {
if (nameMatcher != null) {
nextNameState = nameMatcher.findPattern(pattern);
}
} else {
if (byteMachine != null) {
nextNameState = byteMachine.findPattern(pattern);
}
}
if (nextNameState != null) {
// If this was the last step, then reaching the last state means the rule matched, and we should delete
// the rule from the next NameState.
final int nextKeyIndex = keyIndex + 1;
boolean isTerminal = nextKeyIndex == keys.size();
// Trim the candidate sub-rule ID set to contain only the sub-rule IDs present in the next NameState.
Set<Double> nextNameStateSubRuleIds = isTerminal ?
nextNameState.getTerminalSubRuleIdsForPattern(pattern) :
nextNameState.getNonTerminalSubRuleIdsForPattern(pattern);
// If no sub-rule IDs are found for next NameState, then we have no candidates, and will return below
// without further recursion through the keys.
if (nextNameStateSubRuleIds == null) {
candidateSubRuleIds.clear();
// If candidate set is empty, we are at first NameState, so initialize to next NameState's sub-rule IDs.
// When initializing, ensure that sub-rule IDs match the provided rule name for deletion.
} else if (candidateSubRuleIds.isEmpty()) {
for (Double nextNameStateSubRuleId : nextNameStateSubRuleIds) {
if (Objects.equals(ruleName, nextNameState.getRule(nextNameStateSubRuleId))) {
candidateSubRuleIds.add(nextNameStateSubRuleId);
}
}
// Have already initialized candidate set. Just retain the candidates present in the next NameState.
} else {
candidateSubRuleIds.retainAll(nextNameStateSubRuleIds);
}
if (isTerminal) {
for (Double candidateSubRuleId : candidateSubRuleIds) {
if (nextNameState.deleteSubRule(candidateSubRuleId, pattern, true)) {
deletedSubRuleIds.add(candidateSubRuleId);
// Only delete the pattern if the pattern does not transition to the next NameState.
if (!doesNameStateContainPattern(nextNameState, pattern) &&
deletePattern(state, key, pattern)) {
deletedKeys.add(key);
}
}
}
} else {
if (candidateSubRuleIds.isEmpty()) {
return deletedSubRuleIds;
}
deletedSubRuleIds.addAll(deleteStep(nextNameState, keys, nextKeyIndex, patterns, ruleName,
deletedKeys, new HashSet<>(candidateSubRuleIds)));
for (double deletedSubRuleId : deletedSubRuleIds) {
nextNameState.deleteSubRule(deletedSubRuleId, pattern, false);
}
// Unwinding the key recursion, so we aren't on a rule match. Only delete the pattern if the pattern
// does not transition to the next NameState.
if (!doesNameStateContainPattern(nextNameState, pattern) && deletePattern(state, key, pattern)) {
deletedKeys.add(key);
}
}
}
}
return deletedSubRuleIds;
}
private boolean doesNameStateContainPattern(final NameState nameState, final Patterns pattern) {
return nameState.getTerminalPatterns().contains(pattern) ||
nameState.getNonTerminalPatterns().contains(pattern);
}
/**
* Delete given pattern from either NameMatcher or ByteMachine. Remove the parent NameState's transition to
* NameMatcher or ByteMachine if empty after pattern deletion.
*
* @param parentNameState The NameState transitioning to the NameMatcher or ByteMachine.
* @param key The key we transition on.
* @param pattern The pattern to delete.
* @return True if and only if transition from parent NameState was removed.
*/
private boolean deletePattern(final NameState parentNameState, final String key, Patterns pattern) {
if (isNamePattern(pattern)) {
NameMatcher<NameState> nameMatcher = parentNameState.getKeyTransitionOn(key);
nameMatcher.deletePattern(pattern);
if (nameMatcher.isEmpty()) {
parentNameState.removeKeyTransition(key);
return true;
}
} else {
ByteMachine byteMachine = parentNameState.getTransitionOn(key);
byteMachine.deletePattern(pattern);
if (byteMachine.isEmpty()) {
parentNameState.removeTransition(key);
return true;
}
}
return false;
}
/**
* Add a rule to the machine. A rule is a set of names, each of which
* is associated with one or more values.
*
* @param name ARN of the rule
* @param json the JSON form of the rule
*/
public void addRule(final T name, final String json) throws IOException {
try {
JsonRuleCompiler.compile(json).forEach(rule -> addPatternRule(name, rule));
} catch (JsonParseException e) {
addPatternRule(name, RuleCompiler.compile(json));
}
}
/**
* Add a rule to the machine. A rule is a set of names, each of which
* is associated with one or more values.
*
* @param name ARN of the rule
* @param json the JSON form of the rule
*/
public void addRule(final T name, final Reader json) throws IOException {
try {
JsonRuleCompiler.compile(json).forEach(rule -> addPatternRule(name, rule));
} catch (JsonParseException e) {
addPatternRule(name, RuleCompiler.compile(json));
}
}
/**
* Add a rule from the machine. A rule is a set of names, each of which
* is associated with one or more values.
*
* @param name ARN of the rule
* @param json the JSON form of the rule
*/
public void addRule(final T name, final InputStream json) throws IOException {
try {
JsonRuleCompiler.compile(json).forEach(rule -> addPatternRule(name, rule));
} catch (JsonParseException e) {
addPatternRule(name, RuleCompiler.compile(json));
}
}
/**
* Add a rule to the machine. A rule is a set of names, each of which
* is associated with one or more values.
*
* @param name ARN of the rule
* @param json the JSON form of the rule
*/
public void addRule(final T name, final byte[] json) throws IOException {
try {
JsonRuleCompiler.compile(json).forEach(rule -> addPatternRule(name, rule));
} catch (JsonParseException e) {
addPatternRule(name, RuleCompiler.compile(json));
}
}
/**
* Delete a rule from the machine. A rule is a set of names, each of which
* is associated with one or more values.
*
* @param name ARN of the rule
* @param json the JSON form of the rule
*/
public void deleteRule(final T name, final String json) throws IOException {
try {
JsonRuleCompiler.compile(json).forEach(rule -> deletePatternRule(name, rule));
} catch (JsonParseException e) {
deletePatternRule(name, RuleCompiler.compile(json));
}
}
/**
* Delete a rule from the machine. A rule is a set of names, each of which
* is associated with one or more values.
*
* @param name ARN of the rule
* @param json the JSON form of the rule
*/
public void deleteRule(final T name, final Reader json) throws IOException {
try {
JsonRuleCompiler.compile(json).forEach(rule -> deletePatternRule(name, rule));
} catch (JsonParseException e) {
deletePatternRule(name, RuleCompiler.compile(json));
}
}
/**
* Delete a rule to the machine. A rule is a set of names, each of which
* is associated with one or more values.
*
* @param name ARN of the rule
* @param json the JSON form of the rule
*/
public void deleteRule(final T name, final InputStream json) throws IOException {
try {
JsonRuleCompiler.compile(json).forEach(rule -> deletePatternRule(name, rule));
} catch (JsonParseException e) {
deletePatternRule(name, RuleCompiler.compile(json));
}
}
private void addStep(final List<String> keys,
final Map<String, List<Patterns>> patterns,
final T ruleName) {
List<String> addedKeys = new ArrayList<>();
Set<NameState> nameStates[] = new Set[keys.size()];
if (addStep(getStartState(), keys, 0, patterns, ruleName, addedKeys, nameStates)) {
SubRuleContext context = subRuleContextGenerator.generate();
for (int i = 0; i < keys.size(); i++) {
boolean isTerminal = i + 1 == keys.size();
for (Patterns pattern : patterns.get(keys.get(i))) {
for (NameState nameState : nameStates[i]) {
nameState.addSubRule(ruleName, context.getId(), pattern, isTerminal);
}
}
}
}
addIntoUsedFields(addedKeys);
}
/**
* Add a step, meaning keys and patterns, to the provided NameState.
*
* @param state NameState to add the step to.
* @param keys All keys of the rule.
* @param keyIndex The current index for keys.
* @param patterns Map of key to patterns.
* @param ruleName Name of the rule.
* @param addedKeys Pass in an empty list - this tracks keys that have been added.
* @param nameStatesForEachKey Pass in array of length keys.size() - this tracks NameStates accessible by each key.
* @return True if and only if the keys and patterns being added represent a new sub-rule. Specifically, there
* exists at least one key or at least one pattern for a key not present in another sub-rule of the rule.
*/
private boolean addStep(final NameState state,
final List<String> keys,
final int keyIndex,
final Map<String, List<Patterns>> patterns,
final T ruleName,
List<String> addedKeys,
final Set<NameState>[] nameStatesForEachKey) {
final String key = keys.get(keyIndex);
ByteMachine byteMachine = state.getTransitionOn(key);
NameMatcher<NameState> nameMatcher = state.getKeyTransitionOn(key);
if (byteMachine == null && hasValuePatterns(patterns.get(key))) {
byteMachine = new ByteMachine();
state.addTransition(key, byteMachine);
addedKeys.add(key);
}
if (nameMatcher == null && hasKeyPatterns(patterns.get(key))) {
nameMatcher = createNameMatcher();
state.addKeyTransition(key, nameMatcher);
addedKeys.add(key);
}
// for each pattern, we'll provisionally add it to the BMC, which may already have it. Pass the states
// list in in case the BMC doesn't already have a next-step for this pattern and needs to make a new one
NameState lastNextState = null;
Set<NameState> nameStates = new HashSet<>();
if (nameStatesForEachKey[keyIndex] == null) {
nameStatesForEachKey[keyIndex] = new HashSet<>();
}
for (Patterns pattern : patterns.get(key)) {
if (isNamePattern(pattern)) {
lastNextState = nameMatcher.addPattern(pattern, lastNextState == null ? new NameState() : lastNextState);
} else {
assert byteMachine != null;
lastNextState = byteMachine.addPattern(pattern, lastNextState);
}
nameStates.add(lastNextState);
nameStatesForEachKey[keyIndex].add(lastNextState);
}
// Determine if we are adding a new rule or not. If we are not yet at the terminal key, go deeper recursively.
// If we are at the terminal key, unwind recursion stack, checking each NameState to see if any pattern for
// rule name is new. As soon as one rule+pattern for any NameState is new, we know we are processing a new
// sub-rule and can continue returning true without further NameState checks.
boolean isRuleNew = false;
final int nextKeyIndex = keyIndex + 1;
boolean isTerminal = nextKeyIndex == keys.size();
for (NameState nameState : nameStates) {
if (!isTerminal) {
isRuleNew = addStep(nameState, keys, nextKeyIndex, patterns, ruleName, addedKeys, nameStatesForEachKey)
|| isRuleNew;
}
if (!isRuleNew) {
for (Patterns pattern : patterns.get(key)) {
if (!nameState.containsRule(ruleName, pattern)) {
isRuleNew = true;
break;
}
}
}
}
return isRuleNew;
}
private boolean hasValuePatterns(List<Patterns> patterns) {
return patterns.stream().anyMatch(p -> !isNamePattern(p));
}
private boolean hasKeyPatterns(List<Patterns> patterns) {
return patterns.stream().anyMatch(this::isNamePattern);
}
private boolean isNamePattern(Patterns pattern) {
return pattern.type() == MatchType.ABSENT;
}
private void addIntoUsedFields(List<String> keys) {
for (String key : keys) {
recordFieldStep(key);
}
}
private void checkAndDeleteUsedFields(final List<String> keys) {
for (String key : keys) {
eraseFieldStep(key);
}
}
public boolean isEmpty() {
return startState.isEmpty() && fieldStepsUsedRefCount.isEmpty();
}
@Nonnull
@SuppressWarnings("unchecked")
private <R> NameMatcher<R> createNameMatcher() {
return (NameMatcher<R>) new SingleStateNameMatcher();
}
private void recordFieldStep(String fieldName) {
final String [] steps = fieldName.split("\\.");
for (String step : steps) {
fieldStepsUsedRefCount.compute(step, (k, v) -> (v == null) ? 1 : v + 1);
}
}
private void eraseFieldStep(String fieldName) {
final String [] steps = fieldName.split("\\.");
for (String step : steps) {
fieldStepsUsedRefCount.compute(step, (k, v) -> (v == 1) ? null : v - 1);
}
}
public int evaluateComplexity(MachineComplexityEvaluator evaluator) {
return startState.evaluateComplexity(evaluator);
}
/**
* Gives roughly the number of objects within the machine. This is useful to identify large rule-machines
* that potentially require loads of memory. The method performs all of its calculation at runtime to avoid
* taking up memory and making the impact of large rule-machines worse. When calculating this value; we
* consider any transitions, states, byte-machines, and rules. There's are also a checks to ensure we're
* not stuck in endless loops (that's possible for wildcard matches) or taking a long time for numeric range
* matchers.
*
* NOTEs:
* 1. As this method is dependent on number of internal objects, as ruler evolves this will also
* give different results.
* 2. It will also give you different results based on the order in which you add or remove rules as in
* some-cases Ruler takes short-cuts for exact matches (see ShortcutTransition for more details).
* 3. This method isn't thread safe, and so is prefixed with approximate.
*
* @param maxObjectCount Caps evaluation of object at this threshold.
*/
public int approximateObjectCount(int maxObjectCount) {
final HashSet<Object> objectSet = new HashSet<>();
startState.gatherObjects(objectSet, maxObjectCount);
return Math.min(objectSet.size(), maxObjectCount);
}
@Deprecated
/**
* Use `approximateObjectCount(int maxObjectCount)` instead.
*
* Due to unbounded nature of this method, counting can be painfully long.
*/
public int approximateObjectCount() {
return approximateObjectCount(Integer.MAX_VALUE);
}
@Override
public String toString() {
return "GenericMachine{" +
"startState=" + startState +
", fieldStepsUsedRefCount=" + fieldStepsUsedRefCount +
'}';
}
}
| 4,893 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/CIDR.java | package software.amazon.event.ruler;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import static software.amazon.event.ruler.Constants.HEX_DIGITS;
import static software.amazon.event.ruler.Constants.MAX_DIGIT;
/**
* Supports matching on IPv4 and IPv6 CIDR patterns, as compressed into a string range match.
*/
public class CIDR {
/**
* Binary representation of these bytes is 1's followed by all 0's. The number of 0's is equal to the array index.
* So the binary values are: 11111111, 11111110, 11111100, 11111000, 11110000, 11100000, 11000000, 10000000, 00000000
*/
private final static byte[] LEADING_MIN_BITS = { (byte) 0xff, (byte) 0xfe, (byte) 0xfc, (byte) 0xf8, (byte) 0xf0, (byte) 0xe0, (byte) 0xc0, (byte) 0x80, 0x00 };
/**
* Binary representation of these bytes is 0's followed by all 1's. The number of 1's is equal to the array index.
* So the binary values are: 00000000, 00000001, 00000011, 00000111, 00001111, 00011111, 00111111, 01111111, 11111111
*/
private final static byte[] TRAILING_MAX_BITS = { 0x0, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, (byte) 0xff };
private CIDR() { }
private static boolean isIPv4OrIPv6(String ip) {
return Constants.IPv4_REGEX.matcher(ip).matches() || Constants.IPv6_REGEX.matcher(ip).matches();
}
private static byte[] ipToBytes(final String ip) {
// have to do the regex check because if we past what looks like a hostname, InetAddress.getByName will
// launch a DNS search
byte[] addr = {};
try {
if (isIPv4OrIPv6(ip)) {
addr = InetAddress.getByName(ip).getAddress();
}
} catch (Exception e) {
barf("Invalid IP address: " + ip);
}
if (addr.length != 4 && addr.length != 16) {
barf("Nonstandard IP address: " + ip);
}
return addr;
}
/**
* Converts an IP address literal (v4 or v6) into a hexadecimal string.
* Throws an IllegalArgumentException if the alleged ip is not a valid IP address literal.
* @param ip String alleged to be an IPv4 or IPv6 address literal.
* @return Hexadecimal form of the address, 4 or 16 bytes.
*/
static String ipToString(final String ip) {
return new String(toHexDigits(ipToBytes(ip)), StandardCharsets.UTF_8);
}
/**
* Converts a string to an IP address literal if this is possible. If not
* possible, returns the original string.
* @param ip String that might be an IP address literal
* @return Hexadecimal form of the input if it was an IP address literal.
*/
static String ipToStringIfPossible(final String ip) {
if (!isIPv4OrIPv6(ip)) {
return ip;
}
try {
return ipToString(ip);
} catch (Exception e){
return ip;
}
}
/**
* Converts a string to an IP address literal to isCIDR format Range if this is possible.
* If not possible, returns null.
* @param ip String that might be an IP address literal
* @return Range with isCIDR as true
*/
static Range ipToRangeIfPossible(final String ip) {
if (!isIPv4OrIPv6(ip)) {
return null;
}
try {
final byte[] digits = toHexDigits(ipToBytes(ip));
final byte[] bottom = digits.clone();
final byte[] top = digits.clone();
boolean openBottom;
boolean openTop;
byte lastByte = top[top.length - 1];
if (lastByte == MAX_DIGIT) {
bottom[top.length - 1] = (byte) (lastByte - 1);
openBottom = true;
openTop = false;
} else {
if (lastByte != HEX_DIGITS[9]) {
top[top.length - 1] = (byte) (lastByte + 1);
} else {
top[top.length - 1] = HEX_DIGITS[10];
}
openBottom = false;
openTop = true;
}
return new Range(bottom, openBottom, top, openTop, true);
} catch (Exception e) {
return null;
}
}
private static byte[] toHexDigits(final byte[] address) {
final byte[] digits = new byte[address.length * 2];
int digitInd = 0;
for (int ipByte : address) {
digits[digitInd++] = HEX_DIGITS[(ipByte >> 4) & 0x0F];
digits[digitInd++] = HEX_DIGITS[ipByte & 0x0F];
}
return digits;
}
public static Range cidr(String cidr) throws IllegalArgumentException {
String[] slashed = cidr.split("/");
if (slashed.length != 2) {
barf("Malformed CIDR, one '/' required");
}
int maskBits = -1;
try {
maskBits = Integer.parseInt(slashed[1]);
} catch (NumberFormatException e) {
barf("Malformed CIDR, mask bits must be an integer");
}
if (maskBits < 0) {
barf("Malformed CIDR, mask bits must not be negative");
}
byte[] providedIp = ipToBytes(slashed[0]);
if (providedIp.length == 4) {
if (maskBits > 31) {
barf("IPv4 mask bits must be < 32");
}
} else {
if (maskBits > 127) {
barf("IPv6 mask bits must be < 128");
}
}
byte[] minBytes = computeBottomBytes(providedIp, maskBits);
byte[] maxBytes = computeTopBytes(providedIp, maskBits);
return new Range(toHexDigits(minBytes), false, toHexDigits(maxBytes), false, true);
}
/**
* Calculate the byte representation of the lowest IP address covered by the provided CIDR.
*
* @param baseBytes The byte representation of the IP address (left-of-slash) component of the provided CIDR.
* @param maskBits The integer (right-of-slash) of the provided CIDR.
* @return The byte representation of the lowest IP address covered by the provided CIDR.
*/
private static byte[] computeBottomBytes(final byte[] baseBytes, final int maskBits) {
int variableBits = computeVariableBits(baseBytes, maskBits);
// Calculate the byte representation of the lowest IP address covered by the provided CIDR.
// Iterate from the least significant byte (right hand side) back to the most significant byte (left hand side).
byte[] minBytes = new byte[baseBytes.length];
for (int i = baseBytes.length - 1; i >= 0; i--) {
// This is the case where some or all of the byte is variable. So the min byte value possible is equal to
// the original IP address's bits for the leading non-variable bits and equal to all 0's for the trailing
// variable bits.
if (variableBits > 0) {
minBytes[i] = (byte) (baseBytes[i] & LEADING_MIN_BITS[Math.min(8, variableBits)]);
// There is no variable component to this byte. Thus, it must equal the byte from the original IP address in
// the provided CIDR.
} else {
minBytes[i] = baseBytes[i];
}
// Subtract 8 variable bits. We're effectively chopping off the least significant byte for next iteration.
variableBits -= 8;
}
return minBytes;
}
/**
* Calculate the byte representation of the highest IP address covered by the provided CIDR.
*
* @param baseBytes The byte representation of the IP address (left-of-slash) component of the provided CIDR.
* @param maskBits The integer (right-of-slash) of the provided CIDR.
* @return The byte representation of the highest IP address covered by the provided CIDR.
*/
private static byte[] computeTopBytes(final byte[] baseBytes, final int maskBits) {
int variableBits = computeVariableBits(baseBytes, maskBits);
// Calculate the byte representation of the highest IP address covered by the provided CIDR.
// Iterate from the least significant byte (right hand side) back to the most significant byte (left hand side).
byte[] maxBytes = new byte[baseBytes.length];
for (int i = baseBytes.length - 1; i >= 0; i--) {
// This is the case where some or all of the byte is variable. So the max byte value possible is equal to
// the original IP address's bits for the leading non-variable bits and equal to all 1's for the trailing
// variable bits.
if (variableBits > 0) {
maxBytes[i] = (byte) (baseBytes[i] | TRAILING_MAX_BITS[Math.min(8, variableBits)]);
// There is no variable component to this byte. Thus, it must equal the byte from the original IP address in
// the provided CIDR.
} else {
maxBytes[i] = baseBytes[i];
}
// Subtract 8 variable bits. We're effectively chopping off the least significant byte for next iteration.
variableBits -= 8;
}
return maxBytes;
}
/**
* The maskBits in a provided CIDR refer to the number of leading bits in the binary representation of the IP
* address component that are fixed. Thus, variableBits refers to the number of remaining (trailing) bits.
*
* @param baseBytes The byte representation of the IP address (left-of-slash) component of the provided CIDR.
* @param maskBits The integer (right-of-slash) of the provided CIDR.
* @return The number of variable (trailing) bits after the fixed maskBits bits.
*/
private static int computeVariableBits(final byte[] baseBytes, final int maskBits) {
return (baseBytes.length == 4 ? 32 : 128) - maskBits;
}
private static void barf(final String msg) throws IllegalArgumentException {
throw new IllegalArgumentException(msg);
}
}
| 4,894 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/ShortcutTransition.java | package software.amazon.event.ruler;
import java.util.Collections;
import java.util.Set;
// Shortcut transition is designed mainly for exactly match by its memory consuming because the exactly match is always
// in the last byte of value, while it will take a lots of memory if we build a traverse path byte by byte.
// however, if we add another value like "ab"->match1. so we have two transitions separately, but, in term of memory
// cost, the byte "a" and "b" are duplicated in those two transitions and we want to reuse the same path as much as possible.
// The idea here to share the byte which is common among the transitions, when create the exactly match, if we know, by
// along the byte state path, the remaining path doesn't exist, instead of creating a entirely byte path and put the match in last byte,
// we just use the first next byte which is not existing path, and use it to create the shortcut transition to link to the match directly.
// For example, if we have value "abcdfg", current way is "a"->"b"->"c"->"d"->"e"->"f"->"g"->match0
// while, with the shortcut transition, it is just "a"-> match0("abcdef").
// the shortcut transition to proxy to a match directly and will do the adjustment whenever adding new transitions.
// The definition of shortcut transition is a transition which transits to a exact match only by extending a next byte
// which doesn't exist in current byte state path. e.g. if we add value "abcdefg", "a" is the first byte in current path
// which isn't existing yet, so, we put the shortcut transition on state of "a" and it points to match "abcdefg" directly.
// +---+
// | a +-->match0-("abcdefg")
// +-+-+
// then we add "ab" and doing the adjustment, it ends up with the effects like below:
// +---+ +---+ +---+
// | a +-->+ b +-->+ c +-->null
// +---+ +-+-+ +-+-+
// | |
// v v
// match1-"ab" match0-"abcdefg"
// we take "ab" go through current state path which triggers the byteMachine extends to "b" as "a"->"b" and put the real transition
// with match("ab") on state of "b", then do re-evaluate the match0("abcdefg"), at this time, we see, the first byte which
// is not existing is "c", so we create a new shortcut transition of match0("abcdefg") and put it to "c", at the last step,
// we remove the shortcut transition from "a", we leave it as the last step is to avoid any impact to concurrent read request.
// as you see, during the whole change, we didn't change any existing data from "a" to "c", every change is newly built stuff,
// we update existing path only once new proposal is ready.
// Note:
// 1) the adjustment will ensure the shortcut transition will be always at the tail position in the traverse path.
// 2) the byte which has the shortcut transition must be always the next byte in the match which doesn't exist in existing
// byte path.
// 3) shortcut Transition will only work for exactly match and should only have one match in one shortcut transition.
public class ShortcutTransition extends SingleByteTransition {
private ByteMatch match;
@Override
ByteState getNextByteState() {
return null;
}
@Override
SingleByteTransition setNextByteState(ByteState nextState) {
return nextState;
}
@Override
public ByteTransition getTransition(byte utf8byte) {
return null;
}
@Override
public ByteTransition getTransitionForAllBytes() {
return null;
}
@Override
public Set<ByteTransition> getTransitions() {
return Collections.EMPTY_SET;
}
@Override
ByteMatch getMatch() {
return match;
}
@Override
SingleByteTransition setMatch(ByteMatch match) {
this.match = match;
return this;
}
@Override
public Iterable<ShortcutTransition> getShortcuts() {
return this;
}
@Override
boolean isShortcutTrans() {
return true ;
}
}
| 4,895 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/ByteMachine.java | package software.amazon.event.ruler;
import com.fasterxml.jackson.core.io.doubleparser.JavaDoubleParser;
import software.amazon.event.ruler.input.InputByte;
import software.amazon.event.ruler.input.InputCharacter;
import software.amazon.event.ruler.input.InputCharacterType;
import software.amazon.event.ruler.input.InputMultiByteSet;
import software.amazon.event.ruler.input.MultiByte;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.concurrent.ThreadSafe;
import static software.amazon.event.ruler.CompoundByteTransition.coalesce;
import static software.amazon.event.ruler.MatchType.EQUALS_IGNORE_CASE;
import static software.amazon.event.ruler.MatchType.EXACT;
import static software.amazon.event.ruler.MatchType.EXISTS;
import static software.amazon.event.ruler.MatchType.SUFFIX;
import static software.amazon.event.ruler.MatchType.ANYTHING_BUT_SUFFIX;
import static software.amazon.event.ruler.MatchType.SUFFIX_EQUALS_IGNORE_CASE;
import static software.amazon.event.ruler.input.MultiByte.MAX_CONTINUATION_BYTE;
import static software.amazon.event.ruler.input.MultiByte.MAX_FIRST_BYTE_FOR_ONE_BYTE_CHAR;
import static software.amazon.event.ruler.input.MultiByte.MAX_FIRST_BYTE_FOR_TWO_BYTE_CHAR;
import static software.amazon.event.ruler.input.MultiByte.MAX_NON_FIRST_BYTE;
import static software.amazon.event.ruler.input.MultiByte.MIN_CONTINUATION_BYTE;
import static software.amazon.event.ruler.input.MultiByte.MIN_FIRST_BYTE_FOR_ONE_BYTE_CHAR;
import static software.amazon.event.ruler.input.MultiByte.MIN_FIRST_BYTE_FOR_TWO_BYTE_CHAR;
import static software.amazon.event.ruler.input.DefaultParser.getParser;
/**
* Represents a UTF8-byte-level state machine that matches a Ruler state machine's field values.
* Each state is a map keyed by utf8 byte. getTransition(byte) yields a Target, which can contain either or
* both of the next ByteState, and the first of a chain of Matches, which indicate a match to some pattern.
*/
@ThreadSafe
class ByteMachine {
// Only these match types support shortcuts during traversal.
private static final Set<MatchType> SHORTCUT_MATCH_TYPES = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(EXACT)));
private final ByteState startState = new ByteState();
// For wildcard rule "*", the start state is a match.
private ByteMatch startStateMatch;
// non-zero if the machine has a numerical-comparison pattern included. In which case, values
// should be converted to ComparableNumber before testing for matches, if possible.
//
private final AtomicInteger hasNumeric = new AtomicInteger(0);
// as with the previous, but signals the presence of an attempt to match an IP address
//
private final AtomicInteger hasIP = new AtomicInteger(0);
// signal the presence of suffix match in current byteMachine instance
private final AtomicInteger hasSuffix = new AtomicInteger(0);
// For anything-but patterns, we assume they've matched unless we can prove they didn't. When we
// add an anything-but to the machine, we put it in just like an exact match and remember it in
// this structure. Then when we traverse the machine, if we get an exact match to the anything-but,
// that represents a failure, which we record in the failedAnythingButs hash, and then finally
// do a bit of set arithmetic to add the anythingButs, minus the failedAnythingButs, to the
// result set.
//
// We could do this more straightforwardly by filling in the whole byte state. For
// example, if you had "anything-but: foo", in the first state, "f" would transition to state 2, all 255
// other byte values to a "success" match. In state 2 and state 3, "o" would transition to the next state
// and all 255 others to success; then you'd have all 256 values in state 4 be success. This would be simple
// and fast, but VERY memory-expensive, because you'd have 4 fully-filled states, and a thousand or so
// different NameState objects. Now, there are optimizations to be had with default-values in ByteStates,
// and lazily allocating Matches only when you have unique values, but all of these things would add
// considerable complexity, and this is also easy to understand, and probably not much slower.
//
private final Map<NameState, List<Patterns>> anythingButs = new ConcurrentHashMap<>();
// Multiple different next-namestate steps can result from processing a single field value, for example
// "foot" matches "foot" exactly, "foo" as a prefix, and "hand" as an anything-but. So, this
// method returns a list.
Set<NameStateWithPattern> transitionOn(String valString) {
// not thread-safe, but this is only used in the scope of this method on one thread
final Set<NameStateWithPattern> transitionTo = new HashSet<>();
boolean fieldValueIsNumeric = false;
if (hasNumeric.get() > 0) {
try {
final double numerically = JavaDoubleParser.parseDouble(valString);
valString = ComparableNumber.generate(numerically);
fieldValueIsNumeric = true;
} catch (Exception e) {
// no-op, couldn't treat this as a sensible number
}
} else if (hasIP.get() > 0) {
try {
// we'll try both the quoted and unquoted version to help people whose events aren't
// in JSON
if (valString.startsWith("\"") && valString.endsWith("\"")) {
valString = CIDR.ipToString(valString.substring(1, valString.length() -1));
} else {
valString = CIDR.ipToString(valString);
}
} catch (IllegalArgumentException e) {
// no-op, couldn't treat this as an IP address
}
}
doTransitionOn(valString, transitionTo, fieldValueIsNumeric);
return transitionTo;
}
boolean isEmpty() {
if (startState.hasNoTransitions() && startStateMatch == null) {
assert anythingButs.isEmpty();
assert hasNumeric.get() == 0;
assert hasIP.get() == 0;
return true;
}
return false;
}
// this is to support deleteRule(). It deletes the ByteStates that exist to support matching the provided pattern.
void deletePattern(final Patterns pattern) {
switch (pattern.type()) {
case NUMERIC_RANGE:
assert pattern instanceof Range;
deleteRangePattern((Range) pattern);
break;
case ANYTHING_BUT:
assert pattern instanceof AnythingBut;
deleteAnythingButPattern((AnythingBut) pattern);
break;
case ANYTHING_BUT_IGNORE_CASE:
assert pattern instanceof AnythingButEqualsIgnoreCase;
deleteAnythingButEqualsIgnoreCasePattern((AnythingButEqualsIgnoreCase) pattern);
break;
case EXACT:
case NUMERIC_EQ:
case PREFIX:
case PREFIX_EQUALS_IGNORE_CASE:
case SUFFIX:
case SUFFIX_EQUALS_IGNORE_CASE:
case ANYTHING_BUT_PREFIX:
case ANYTHING_BUT_SUFFIX:
case EQUALS_IGNORE_CASE:
case WILDCARD:
assert pattern instanceof ValuePatterns;
deleteMatchPattern((ValuePatterns) pattern);
break;
case EXISTS:
deleteExistencePattern(pattern);
break;
default:
throw new AssertionError(pattern + " is not implemented yet");
}
}
private void deleteExistencePattern(Patterns pattern) {
final InputCharacter[] characters = getParser().parse(pattern.type(), Patterns.EXISTS_BYTE_STRING);
deleteMatchStep(startState, 0, pattern, characters);
}
private void deleteAnythingButPattern(AnythingBut pattern) {
pattern.getValues().forEach(value ->
deleteMatchStep(startState, 0, pattern, getParser().parse(pattern.type(), value)));
}
private void deleteAnythingButEqualsIgnoreCasePattern(AnythingButEqualsIgnoreCase pattern) {
pattern.getValues().forEach(value ->
deleteMatchStep(startState, 0, pattern, getParser().parse(pattern.type(), value)));
}
private void deleteMatchPattern(ValuePatterns pattern) {
final InputCharacter[] characters = getParser().parse(pattern.type(), pattern.pattern());
if (characters.length == 1 && isWildcard(characters[0])) {
// Only character is wildcard. Remove the start state match.
startStateMatch = null;
return;
}
deleteMatchStep(startState, 0, pattern, characters);
}
private void deleteMatchStep(ByteState byteState, int charIndex, Patterns pattern,
final InputCharacter[] characters) {
final InputCharacter currentChar = characters[charIndex];
final ByteTransition trans = getTransition(byteState, currentChar);
for (SingleByteTransition eachTrans : trans.expand()) {
if (charIndex < characters.length - 1) {
// if it is shortcut trans, we delete it directly.
if (eachTrans.isShortcutTrans()) {
deleteMatch(currentChar, byteState, pattern, eachTrans);
} else {
ByteState nextByteState = eachTrans.getNextByteState();
if (nextByteState != null && nextByteState != byteState) {
deleteMatchStep(nextByteState, charIndex + 1, pattern, characters);
}
// Perform handling for certain wildcard cases.
eachTrans = deleteMatchStepForWildcard(byteState, charIndex, pattern, characters, eachTrans,
nextByteState);
if (nextByteState != null &&
(nextByteState.hasNoTransitions() || nextByteState.hasOnlySelfReferentialTransition())) {
// The transition's next state has no meaningful transitions, so compact the transition.
putTransitionNextState(byteState, currentChar, eachTrans, null);
}
}
} else {
deleteMatch(currentChar, byteState, pattern, eachTrans);
}
}
}
/**
* Performs delete match step handling for certain wildcard cases.
*
* @param byteState The current ByteState.
* @param charIndex The index of the current character in characters.
* @param pattern The pattern we are deleting.
* @param characters The array of InputCharacters corresponding to the pattern's value.
* @param transition One of the transitions from byteState using the current byte.
* @param nextByteState The next ByteState led to by transition.
* @return Transition, or a replacement for transition if the original instance no longer exists in the machine.
*/
private SingleByteTransition deleteMatchStepForWildcard(ByteState byteState, int charIndex, Patterns pattern,
InputCharacter[] characters,
SingleByteTransition transition, ByteState nextByteState) {
final InputCharacter currentChar = characters[charIndex];
// There will be a match using second last character on second last state when last character is
// a wildcard. This allows empty substring to satisfy wildcard.
if (charIndex == characters.length - 2 && isWildcard(characters[characters.length - 1])) {
// Delete the match.
SingleByteTransition updatedTransition = deleteMatch(currentChar, byteState, pattern, transition);
if (updatedTransition != null) {
return updatedTransition;
}
// Undo the machine changes for a wildcard as described in the Javadoc of addTransitionNextStateForWildcard.
} else if (nextByteState != null && isWildcard(currentChar)) {
// Remove transition for all possible byte values if it leads to an only self-referencing state
if (nextByteState.hasOnlySelfReferentialTransition()) {
byteState.removeTransitionForAllBytes(transition);
}
// Remove match on last char that exists for second-last char wildcard on second last state to be satisfied
// by empty substring.
if (charIndex == characters.length - 2 && isWildcard(characters[characters.length - 2])) {
deleteMatches(characters[charIndex + 1], byteState, pattern);
// Remove match on second last char that exists for third last and last char wildcard combination on third
// last state to be both satisfied by empty substrings. I.e. "ax" can match "a*x*".
} else if (charIndex == characters.length - 3 && isWildcard(characters[characters.length - 1]) &&
isWildcard(characters[characters.length - 3])) {
deleteMatches(characters[charIndex + 1], byteState, pattern);
}
// Remove transition that exists for wildcard to be satisfied by empty substring.
ByteTransition skipWildcardTransition = getTransition(byteState, characters[charIndex + 1]);
for (SingleByteTransition eachTrans : skipWildcardTransition.expand()) {
ByteState skipWildcardState = eachTrans.getNextByteState();
if (!eachTrans.getMatches().iterator().hasNext() && skipWildcardState != null &&
(skipWildcardState.hasNoTransitions() ||
skipWildcardState.hasOnlySelfReferentialTransition())) {
removeTransition(byteState, characters[charIndex + 1], eachTrans);
}
}
}
return transition;
}
// this method is only called after findRangePattern proves that matched pattern exist.
private void deleteRangePattern(Range range) {
// if range to be deleted does not exist, just return
if (findRangePattern(range) == null) {
return;
}
// Inside Range pattern, there are bottom value and top value, this function will traverse each byte of bottom
// and top value separately to hunt down all matches eligible to be deleted.
// The ArrayDequeue is used to save all byteStates in transition path since state associated with first byte of
// value to state associated with last byte of value. Then, checkAndDeleteStateAlongTraversedPath function will
// check each state saved in ArrayDequeue along reverse direction of traversing path and recursively check and
// delete match and state if it is eligible.
// Note: byteState is deletable only when it has no match and no transition to next byteState.
// Refer to definition of class ComparableNumber, the max length in bytes for Number type is 16,
// so here we take 16 as ArrayDeque capacity which is defined as ComparableNumber.MAX_BYTE_LENGTH.
final ArrayDeque<AbstractMap.SimpleImmutableEntry<Byte, ByteTransition>> byteStatesTraversePathAlongRangeBottomValue =
new ArrayDeque<>(ComparableNumber.MAX_LENGTH_IN_BYTES);
final ArrayDeque<AbstractMap.SimpleImmutableEntry<Byte, ByteTransition>> byteStatesTraversePathAlongRangeTopValue =
new ArrayDeque<>(ComparableNumber.MAX_LENGTH_IN_BYTES);
ByteTransition forkState = startState;
int forkOffset = 0;
byteStatesTraversePathAlongRangeBottomValue.addFirst(new AbstractMap.SimpleImmutableEntry<>(range.bottom[0], forkState));
byteStatesTraversePathAlongRangeTopValue.addFirst(new AbstractMap.SimpleImmutableEntry<>(range.top[0], forkState));
// bypass common prefix of range's bottom and top patterns
// we need move forward the state and save all states traversed for checking later.
while (range.bottom[forkOffset] == range.top[forkOffset]) {
forkState = findNextByteStateForRangePattern(forkState, range.bottom[forkOffset]);
assert forkState != null : "forkState != null";
byteStatesTraversePathAlongRangeBottomValue.addFirst(new AbstractMap.SimpleImmutableEntry<>(range.bottom[forkOffset], forkState));
byteStatesTraversePathAlongRangeTopValue.addFirst(new AbstractMap.SimpleImmutableEntry<>(range.top[forkOffset], forkState));
forkOffset++;
}
// when bottom byte on forkOffset position < top byte in same position, there must be matches existing
// in this state, go ahead to delete matches in the fork state.
for (byte bb : Range.digitSequence(range.bottom[forkOffset], range.top[forkOffset], false, false)) {
deleteMatches(getParser().parse(bb), forkState, range);
}
// process all the transitions on the bottom range bytes
ByteTransition state = forkState;
int lastMatchOffset = forkOffset;
// see explanation in addRangePattern(), we need delete state and match accordingly.
for (int offsetB = forkOffset + 1; offsetB < (range.bottom.length - 1); offsetB++) {
byte b = range.bottom[offsetB];
if (b < Constants.MAX_DIGIT) {
while (lastMatchOffset < offsetB) {
state = findNextByteStateForRangePattern(state, range.bottom[lastMatchOffset]);
assert state != null : "state must be existing for this pattern";
byteStatesTraversePathAlongRangeBottomValue.addFirst(
new AbstractMap.SimpleImmutableEntry<>(range.bottom[lastMatchOffset], state));
lastMatchOffset++;
}
assert lastMatchOffset == offsetB : "lastMatchOffset == offsetB";
for (byte bb : Range.digitSequence(b, Constants.MAX_DIGIT, false, true)) {
deleteMatches(getParser().parse(bb), state, range);
}
}
}
// now for last "bottom" digit
// see explanation in addRangePattern(), we need to delete states and matches accordingly.
final byte lastBottom = range.bottom[range.bottom.length - 1];
final byte lastTop = range.top[range.top.length - 1];
if ((lastBottom < Constants.MAX_DIGIT) || !range.openBottom) {
while (lastMatchOffset < range.bottom.length - 1) {
state = findNextByteStateForRangePattern(state, range.bottom[lastMatchOffset]);
assert state != null : "state != null";
byteStatesTraversePathAlongRangeBottomValue.addFirst(new AbstractMap.SimpleImmutableEntry<>(range.bottom[lastMatchOffset], state));
lastMatchOffset++;
}
assert lastMatchOffset == range.bottom.length - 1 : "lastMatchOffset == range.bottom.length - 1";
if (!range.openBottom) {
deleteMatches(getParser().parse(lastBottom), state, range);
}
// unless the last digit is also at the fork position, fill in the extra matches due to
// the strictly-less-than condition (see discussion above)
if (forkOffset < (range.bottom.length - 1)) {
for (byte bb : Range.digitSequence(lastBottom, Constants.MAX_DIGIT, false, true)) {
deleteMatches(getParser().parse(bb), state, range);
}
}
}
// now process transitions along the top range bytes
// see explanation in addRangePattern(), we need to delete states and matches accordingly.
state = forkState;
lastMatchOffset = forkOffset;
for (int offsetT = forkOffset + 1; offsetT < (range.top.length - 1); offsetT++) {
byte b = range.top[offsetT];
if (b > '0') {
while (lastMatchOffset < offsetT) {
state = findNextByteStateForRangePattern(state, range.top[lastMatchOffset]);
assert state != null : "state must be existing for this pattern";
byteStatesTraversePathAlongRangeTopValue.addFirst(new AbstractMap.SimpleImmutableEntry<>(range.top[lastMatchOffset], state));
lastMatchOffset++;
}
assert lastMatchOffset == offsetT : "lastMatchOffset == offsetT";
for (byte bb : Range.digitSequence((byte) '0', range.top[offsetT], true, false)) {
deleteMatches(getParser().parse(bb), state, range);
}
}
}
// now for last "top" digit.
// see explanation in addRangePattern(), we need to delete states and matches accordingly.
if ((lastTop > '0') || !range.openTop) {
while (lastMatchOffset < range.top.length - 1) {
state = findNextByteStateForRangePattern(state, range.top[lastMatchOffset]);
assert state != null : "state != null";
byteStatesTraversePathAlongRangeTopValue.addFirst(new AbstractMap.SimpleImmutableEntry<>(range.top[lastMatchOffset], state));
lastMatchOffset++;
}
assert lastMatchOffset == range.top.length - 1 : "lastMatchOffset == range.top.length - 1";
if (!range.openTop) {
deleteMatches(getParser().parse(lastTop), state, range);
}
// unless the last digit is also at the fork position, fill in the extra matches due to
// the strictly-less-than condition (see discussion above)
if (forkOffset < (range.top.length - 1)) {
for (byte bb : Range.digitSequence((byte) '0', lastTop, true, false)) {
deleteMatches(getParser().parse(bb), state, range);
}
}
}
// by now we should have deleted all matches in all associated byteStates,
// now we start cleaning up ineffective byteSates along states traversed path we saved before.
checkAndDeleteStateAlongTraversedPath(byteStatesTraversePathAlongRangeBottomValue);
checkAndDeleteStateAlongTraversedPath(byteStatesTraversePathAlongRangeTopValue);
// well done now, we have deleted all matches pattern matched and cleaned all empty state as if that pattern
// wasn't added into machine before.
}
private void checkAndDeleteStateAlongTraversedPath(
ArrayDeque<AbstractMap.SimpleImmutableEntry<Byte, ByteTransition>> byteStateQueue) {
if (byteStateQueue.isEmpty()) {
return;
}
Byte childByteKey = byteStateQueue.pollFirst().getKey();
while (!byteStateQueue.isEmpty()) {
final AbstractMap.SimpleImmutableEntry<Byte, ByteTransition> parentStatePair = byteStateQueue.pollFirst();
final Byte parentByteKey = parentStatePair.getKey();
final ByteTransition parentByteTransition = parentStatePair.getValue();
for (SingleByteTransition singleParent : parentByteTransition.expand()) {
// Check all transitions from singleParent using childByteKey. Delete each transition that is a dead-end
// (i.e. transition that has no transitions itself).
ByteTransition transition = getTransition(singleParent, childByteKey);
for (SingleByteTransition eachTrans : transition.expand()) {
ByteState nextState = eachTrans.getNextByteState();
if (nextState != null && nextState.hasNoTransitions()) {
putTransitionNextState(singleParent.getNextByteState(), getParser().parse(childByteKey),
eachTrans, null);
}
}
}
childByteKey = parentByteKey;
}
}
private void doTransitionOn(final String valString, final Set<NameStateWithPattern> transitionTo,
boolean fieldValueIsNumeric) {
final Map<NameState, List<Patterns>> failedAnythingButs = new HashMap<>();
final byte[] val = valString.getBytes(StandardCharsets.UTF_8);
// we need to add the name state for key existence
addExistenceMatch(transitionTo);
// attempt to harvest the possible suffix match
addSuffixMatch(val, transitionTo, failedAnythingButs);
if (startStateMatch != null) {
transitionTo.add(new NameStateWithPattern(startStateMatch.getNextNameState(), startStateMatch.getPattern()));
}
// we have to do old-school indexing rather than "for (byte b : val)" because there is some special-casing
// on transitions on the last byte in the value array
ByteTransition trans = startState;
for (int valIndex = 0; valIndex < val.length; valIndex++) {
final ByteTransition nextTrans = getTransition(trans, val[valIndex]);
attemptAddShortcutTransitionMatch(nextTrans, valString, EXACT, transitionTo);
if (!nextTrans.isShortcutTrans()) {
// process any matches hanging off this transition
for (ByteMatch match : nextTrans.getMatches()) {
switch (match.getPattern().type()) {
case EXACT:
case EQUALS_IGNORE_CASE:
case WILDCARD:
if (valIndex == (val.length - 1)) {
transitionTo.add(new NameStateWithPattern(match.getNextNameState(), match.getPattern()));
}
break;
case NUMERIC_EQ:
// only matches at last character
if (fieldValueIsNumeric && valIndex == (val.length - 1)) {
transitionTo.add(new NameStateWithPattern(match.getNextNameState(), match.getPattern()));
}
break;
case PREFIX:
case PREFIX_EQUALS_IGNORE_CASE:
transitionTo.add(new NameStateWithPattern(match.getNextNameState(), match.getPattern()));
break;
case ANYTHING_BUT_SUFFIX:
case SUFFIX:
case SUFFIX_EQUALS_IGNORE_CASE:
case EXISTS:
// we already harvested these matches via separate functions due to special matching
// requirements, so just ignore them here.
break;
case NUMERIC_RANGE:
// as soon as you see the match, you've matched
Range range = (Range) match.getPattern();
if ((fieldValueIsNumeric && !range.isCIDR) || (!fieldValueIsNumeric && range.isCIDR)) {
transitionTo.add(new NameStateWithPattern(match.getNextNameState(), match.getPattern()));
}
break;
case ANYTHING_BUT:
AnythingBut anythingBut = (AnythingBut) match.getPattern();
// only applies if at last character
if (valIndex == (val.length - 1) && anythingBut.isNumeric() == fieldValueIsNumeric) {
addToAnythingButsMap(failedAnythingButs, match.getNextNameState(), match.getPattern());
}
break;
case ANYTHING_BUT_IGNORE_CASE:
// only applies if at last character
if (valIndex == (val.length - 1)) {
addToAnythingButsMap(failedAnythingButs, match.getNextNameState(), match.getPattern());
}
break;
case ANYTHING_BUT_PREFIX:
addToAnythingButsMap(failedAnythingButs, match.getNextNameState(), match.getPattern());
break;
default:
throw new RuntimeException("Not implemented yet");
}
}
}
trans = nextTrans.getTransitionForNextByteStates();
if (trans == null) {
break;
}
}
// This may look like premature optimization, but the first "if" here yields roughly 10x performance
// improvement.
if (!anythingButs.isEmpty()) {
for (Map.Entry<NameState, List<Patterns>> entry : anythingButs.entrySet()) {
boolean failedAnythingButsContainsKey = failedAnythingButs.containsKey(entry.getKey());
for (Patterns pattern : entry.getValue()) {
if (!failedAnythingButsContainsKey ||
!failedAnythingButs.get(entry.getKey()).contains(pattern)) {
transitionTo.add(new NameStateWithPattern(entry.getKey(), pattern));
}
}
}
}
}
private void addToAnythingButsMap(Map<NameState, List<Patterns>> map, NameState nameState, Patterns pattern) {
if (!map.containsKey(nameState)) {
map.put(nameState, new ArrayList<>());
}
map.get(nameState).add(pattern);
}
private void removeFromAnythingButsMap(Map<NameState, List<Patterns>> map, NameState nameState, Patterns pattern) {
List<Patterns> patterns = map.get(nameState);
if (patterns != null) {
patterns.remove(pattern);
if (patterns.isEmpty()) {
map.remove(nameState);
}
}
}
private void addExistenceMatch(final Set<NameStateWithPattern> transitionTo) {
final byte[] val = Patterns.EXISTS_BYTE_STRING.getBytes(StandardCharsets.UTF_8);
ByteTransition trans = startState;
ByteTransition nextTrans = null;
for (int valIndex = 0; valIndex < val.length && trans != null; valIndex++) {
nextTrans = getTransition(trans, val[valIndex]);
trans = nextTrans.getTransitionForNextByteStates();
}
if (nextTrans == null) {
return;
}
for (ByteMatch match : nextTrans.getMatches()) {
if (match.getPattern().type() == EXISTS) {
transitionTo.add(new NameStateWithPattern(match.getNextNameState(), match.getPattern()));
break;
}
}
}
private void addSuffixMatch(final byte[] val, final Set<NameStateWithPattern> transitionTo,
final Map<NameState, List<Patterns>> failedAnythingButs) {
// we only attempt to evaluate suffix matches when there is suffix match in current byte machine instance.
// it works as performance level to avoid other type of matches from being affected by suffix checking.
if (hasSuffix.get() > 0) {
ByteTransition trans = startState;
// check the byte in reverse order in order to harvest suffix matches
for (int valIndex = val.length - 1; valIndex >= 0; valIndex--) {
final ByteTransition nextTrans = getTransition(trans, val[valIndex]);
for (ByteMatch match : nextTrans.getMatches()) {
// given we are traversing in reverse order (from right to left), only suffix matches are eligible
// to be collected.
MatchType patternType = match.getPattern().type();
if (patternType == SUFFIX || patternType == SUFFIX_EQUALS_IGNORE_CASE) {
transitionTo.add(new NameStateWithPattern(match.getNextNameState(), match.getPattern()));
} else if (patternType == ANYTHING_BUT_SUFFIX) {
addToAnythingButsMap(failedAnythingButs, match.getNextNameState(), match.getPattern());
}
}
trans = nextTrans.getTransitionForNextByteStates();
if (trans == null) {
break;
}
}
}
}
/**
* Evaluates if a provided transition is a shortcut transition with a match having a given match type and value. If
* so, adds match to transitionTo Set. Used to short-circuit traversal.
*
* Note: The adjustment mode can ensure the shortcut transition (if exists) is always at the tail of path. Refer to
* addEndOfMatch() function for details.
*
* @param transition Transition to evaluate.
* @param value Value desired in match's pattern.
* @param expectedMatchType Match type expected in match's pattern.
* @param transitionTo Set that match's next name state will be added to if desired match is found.
* @return True iff match was added to transitionTo Set.
*/
private boolean attemptAddShortcutTransitionMatch(final ByteTransition transition, final String value,
final MatchType expectedMatchType, final Set<NameStateWithPattern> transitionTo) {
for (ShortcutTransition shortcut : transition.getShortcuts()) {
ByteMatch match = shortcut.getMatch();
assert match != null;
if (match.getPattern().type() == expectedMatchType) {
ValuePatterns valuePatterns = (ValuePatterns) match.getPattern();
if (valuePatterns.pattern().equals(value)) {
// Only one match is possible for shortcut transition
transitionTo.add(new NameStateWithPattern(match.getNextNameState(), match.getPattern()));
return true;
}
}
}
return false;
}
NameState addPattern(final Patterns pattern) {
return addPattern(pattern, null);
}
/**
* Adds one pattern to a byte machine.
*
* @param pattern The pattern to add.
* @param nameState If non-null, attempt to transition to this NameState from the ByteMatch. May be ignored if the
* ByteMatch already exists with its own NameState.
* @return NameState transitioned to from ByteMatch. May or may not equal provided NameState if it wasn't null.
*/
NameState addPattern(final Patterns pattern, final NameState nameState) {
switch (pattern.type()) {
case NUMERIC_RANGE:
assert pattern instanceof Range;
return addRangePattern((Range) pattern, nameState);
case ANYTHING_BUT:
assert pattern instanceof AnythingBut;
return addAnythingButPattern((AnythingBut) pattern, nameState);
case ANYTHING_BUT_IGNORE_CASE:
assert pattern instanceof AnythingButEqualsIgnoreCase;
return addAnythingButEqualsIgnoreCasePattern((AnythingButEqualsIgnoreCase) pattern, nameState);
case ANYTHING_BUT_SUFFIX:
case ANYTHING_BUT_PREFIX:
case EXACT:
case NUMERIC_EQ:
case PREFIX:
case PREFIX_EQUALS_IGNORE_CASE:
case SUFFIX:
case SUFFIX_EQUALS_IGNORE_CASE:
case EQUALS_IGNORE_CASE:
case WILDCARD:
assert pattern instanceof ValuePatterns;
return addMatchPattern((ValuePatterns) pattern, nameState);
case EXISTS:
return addExistencePattern(pattern, nameState);
default:
throw new AssertionError(pattern + " is not implemented yet");
}
}
private NameState addExistencePattern(Patterns pattern, NameState nameState) {
return addMatchValue(pattern, Patterns.EXISTS_BYTE_STRING, nameState);
}
private NameState addAnythingButPattern(AnythingBut pattern, NameState nameState) {
NameState nameStateToBeReturned = nameState;
NameState nameStateChecker = null;
for(String value : pattern.getValues()) {
nameStateToBeReturned = addMatchValue(pattern, value, nameStateToBeReturned);
if (nameStateChecker == null) {
nameStateChecker = nameStateToBeReturned;
}
// all the values in the list must point to the same NameState because they are sharing the same pattern
// object.
assert nameStateChecker == null || nameStateChecker == nameStateToBeReturned : " nameStateChecker == nameStateToBeReturned";
}
return nameStateToBeReturned;
}
private NameState addAnythingButEqualsIgnoreCasePattern(AnythingButEqualsIgnoreCase pattern, NameState nameState) {
NameState nameStateToBeReturned = nameState;
NameState nameStateChecker = null;
for(String value : pattern.getValues()) {
nameStateToBeReturned = addMatchValue(pattern, value, nameStateToBeReturned);
if (nameStateChecker == null) {
nameStateChecker = nameStateToBeReturned;
}
// all the values in the list must point to the same NameState because they are sharing the same pattern
// object.
assert nameStateChecker == null || nameStateChecker == nameStateToBeReturned : " nameStateChecker == nameStateToBeReturned";
}
return nameStateToBeReturned;
}
private NameState addMatchValue(Patterns pattern, String value, NameState nameStateToBeReturned) {
final InputCharacter[] characters = getParser().parse(pattern.type(), value);
ByteState byteState = startState;
ByteState prevByteState = null;
int i = 0;
for (; i < characters.length - 1; i++) {
ByteTransition trans = getTransition(byteState, characters[i]);
if (trans.isEmpty()) {
break;
}
ByteState stateToReuse = null;
for (SingleByteTransition single : trans.expand()) {
ByteState nextByteState = single.getNextByteState();
if (canReuseNextByteState(byteState, nextByteState, characters, i)) {
stateToReuse = nextByteState;
break;
}
}
if (stateToReuse == null) {
break;
}
prevByteState = byteState;
byteState = stateToReuse;
}
// we found our way through the machine with all characters except the last having matches or shortcut.
return addEndOfMatch(byteState, prevByteState, characters, i, pattern, nameStateToBeReturned);
}
private boolean canReuseNextByteState(ByteState byteState, ByteState nextByteState, InputCharacter[] characters,
int i) {
// We cannot re-use nextByteState if it is non-existent (null) or if it is the same as the current byteState,
// meaning we are looping on a self-referencing transition.
if (nextByteState == null || nextByteState == byteState) {
return false;
}
// Case 1: When we have a determinate prefix, we can re-use nextByteState except for the special case where we
// are on the second-last character with a final character wildcard. A composite is required for this
// case, so we will create a new state.
//
// Example 1: Take the following machine representing an exact match pattern.
// a b c
// -----> A -----> B -----> C
// With a byteState of A, a current char of b, and a next and final char of *, we would be unable to
// re-use B as nextByteState, since we need to create a new self-referencing composite state D.
if (!nextByteState.hasIndeterminatePrefix()) {
return !(i == characters.length - 2 && isWildcard(characters[i + 1]));
// Case 2: nextByteState has an indeterminate prefix and current character is not a wildcard. We can re-use
// nextByteState only if byteState does not have at least two transitions, one using the next
// InputCharacter, that eventually converge to a common state.
//
// Example 2a: Take the following machine representing a wildcard pattern.
// ____
// a * | * |
// -----> A -----> B <--
// | b b |
// --> C <--
// With a byteState of A, and a current char of b, we would be unable to re-use C as nextByteState,
// since A has a second transition to B that eventually leads to C as well. But we could re-use B.
//
// Example 2b: Take the following machine representing an equals_ignore_case pattern.
// x Y
// -----> A ------
// | y v
// -----> B
// With a byteState of A, and a current char of y, we would be unable to re-use B as nextByteState,
// since A has a second transition to B using char Y.
} else {
return !doMultipleTransitionsConvergeForInputByte(byteState, characters, i);
}
}
/**
* Returns true if the current InputCharacter is the first InputByte of a Java character and there exists at least
* two transitions, one using the next InputCharacter, away from byteState leading down paths that eventually
* converge to a common state.
*
* @param byteState State where we look for at least two transitions that eventually converge to a common state.
* @param characters The array of InputCharacters.
* @param i The current index in the characters array.
* @return True if and only if multiple transitions eventually converge to a common state.
*/
private boolean doMultipleTransitionsConvergeForInputByte(ByteState byteState, InputCharacter[] characters, int i) {
if (!isByte(characters[i])) {
return false;
}
boolean isNextCharacterForSuffixMatch = isNextCharacterFirstContinuationByteForSuffixMatch(characters, i);
if (!isNextCharacterFirstByteOfMultiByte(characters, i) && !isNextCharacterForSuffixMatch) {
// If we are in the midst of a multi-byte sequence, we know that we are dealing with single transitions.
return false;
}
// Scenario 1 where multiple transitions will later converge: wildcard leads to wildcard state and following
// character can be used to skip wildcard state. Check for a non-self-referencing wildcard transition.
ByteTransition byteStateTransitionForAllBytes = byteState.getTransitionForAllBytes();
if (!byteStateTransitionForAllBytes.isEmpty() && byteStateTransitionForAllBytes != byteState) {
return true;
}
// Scenario 2 where multiple transitions will later converge: equals_ignore_case lower and upper case paths.
// Parse the next Java character into lower and upper case representations. Check if there are multiple
// multibytes (paths) and that there exists a transition that both lead to.
String value = extractNextJavaCharacterFromInputCharacters(characters, i);
MatchType matchType = isNextCharacterForSuffixMatch ? SUFFIX_EQUALS_IGNORE_CASE : EQUALS_IGNORE_CASE;
InputCharacter[] inputCharacters = getParser().parse(matchType, value);
ByteTransition transition = getTransition(byteState, inputCharacters[0]);
return inputCharacters[0] instanceof InputMultiByteSet && transition != null;
}
private boolean isNextCharacterFirstByteOfMultiByte(InputCharacter[] characters, int i) {
byte firstByte = InputByte.cast(characters[i]).getByte();
// Since MIN_NON_FIRST_BYTE is (byte) 0x80 = -128 = Byte.MIN_VALUE, we can simply compare against
// MAX_NON_FIRST_BYTE to see if this is a first byte or not.
return firstByte > MAX_NON_FIRST_BYTE;
}
private boolean isNextCharacterFirstContinuationByteForSuffixMatch(InputCharacter[] characters, int i) {
if (hasSuffix.get() <= 0) {
return false;
}
// If the previous byte is a continuation byte, this means that we're in the middle of a multi-byte sequence.
return isContinuationByte(characters, i) && !isContinuationByte(characters, i - 1);
}
private boolean isContinuationByte(InputCharacter[] characters, int i) {
if (i < 0) {
return false;
}
byte continuationByte = InputByte.cast(characters[i]).getByte();
// Continuation bytes have bit 7 set, and bit 6 should be unset
return continuationByte >= MIN_CONTINUATION_BYTE && continuationByte <= MAX_CONTINUATION_BYTE;
}
private String extractNextJavaCharacterFromInputCharacters(InputCharacter[] characters, int i) {
if (isNextCharacterFirstByteOfMultiByte(characters, i)) {
return extractNextJavaCharacterFromInputCharactersForForwardArrays(characters, i);
} else {
return extractNextJavaCharacterFromInputCharactersForBackwardsArrays(characters, i);
}
}
private String extractNextJavaCharacterFromInputCharactersForBackwardsArrays(InputCharacter[] characters, int i) {
List<Byte> bytesList = new ArrayList<>();
for (int multiByteIndex = i; multiByteIndex < characters.length; multiByteIndex++) {
if (!isContinuationByte(characters, multiByteIndex)) {
// This is the last byte of the suffix char
bytesList.add(InputByte.cast(characters[multiByteIndex]).getByte());
break;
}
bytesList.add(InputByte.cast(characters[multiByteIndex]).getByte());
}
// Undoing the reverse on the byte array to get the valid char
return new String(reverseBytesList(bytesList), StandardCharsets.UTF_8);
}
private byte[] reverseBytesList(List<Byte> bytesList) {
byte[] byteArray = new byte[bytesList.size()];
for (int i = 0; i < bytesList.size(); i++) {
byteArray[bytesList.size() - i - 1] = bytesList.get(i);
}
return byteArray;
}
private static String extractNextJavaCharacterFromInputCharactersForForwardArrays(InputCharacter[] characters, int i) {
byte firstByte = InputByte.cast(characters[i]).getByte();
if (firstByte >= MIN_FIRST_BYTE_FOR_ONE_BYTE_CHAR && firstByte <= MAX_FIRST_BYTE_FOR_ONE_BYTE_CHAR) {
return new String(new byte[] { firstByte } , StandardCharsets.UTF_8);
} else if (firstByte >= MIN_FIRST_BYTE_FOR_TWO_BYTE_CHAR && firstByte <= MAX_FIRST_BYTE_FOR_TWO_BYTE_CHAR) {
return new String(new byte[] { firstByte, InputByte.cast(characters[i + 1]).getByte() },
StandardCharsets.UTF_8);
} else {
return new String(new byte[] { firstByte, InputByte.cast(characters[i + 1]).getByte(),
InputByte.cast(characters[i + 2]).getByte() }, StandardCharsets.UTF_8);
}
}
NameState findPattern(final Patterns pattern) {
switch (pattern.type()) {
case NUMERIC_RANGE:
assert pattern instanceof Range;
return findRangePattern((Range) pattern);
case ANYTHING_BUT:
assert pattern instanceof AnythingBut;
return findAnythingButPattern((AnythingBut) pattern);
case ANYTHING_BUT_IGNORE_CASE:
assert pattern instanceof AnythingButEqualsIgnoreCase;
return findAnythingButEqualsIgnoreCasePattern((AnythingButEqualsIgnoreCase) pattern);
case EXACT:
case NUMERIC_EQ:
case PREFIX:
case PREFIX_EQUALS_IGNORE_CASE:
case SUFFIX:
case SUFFIX_EQUALS_IGNORE_CASE:
case ANYTHING_BUT_SUFFIX:
case ANYTHING_BUT_PREFIX:
case EQUALS_IGNORE_CASE:
case WILDCARD:
assert pattern instanceof ValuePatterns;
return findMatchPattern((ValuePatterns) pattern);
case EXISTS:
return findMatchPattern(getParser().parse(pattern.type(), Patterns.EXISTS_BYTE_STRING), pattern);
default:
throw new AssertionError(pattern + " is not implemented yet");
}
}
private NameState findAnythingButPattern(AnythingBut pattern) {
Set<NameState> nextNameStates = new HashSet<>(pattern.getValues().size());
for (String value : pattern.getValues()) {
NameState matchPattern = findMatchPattern(getParser().parse(pattern.type(), value), pattern);
if (matchPattern != null) {
nextNameStates.add(matchPattern);
}
}
if (!nextNameStates.isEmpty()) {
assert nextNameStates.size() == 1 : "nextNameStates.size() == 1";
return nextNameStates.iterator().next();
}
return null;
}
private NameState findAnythingButEqualsIgnoreCasePattern(AnythingButEqualsIgnoreCase pattern) {
Set<NameState> nextNameStates = new HashSet<>(pattern.getValues().size());
for (String value : pattern.getValues()) {
NameState matchPattern = findMatchPattern(getParser().parse(pattern.type(), value), pattern);
if (matchPattern != null) {
nextNameStates.add(matchPattern);
}
}
if (!nextNameStates.isEmpty()) {
assert nextNameStates.size() == 1 : "nextNameStates.size() == 1";
return nextNameStates.iterator().next();
}
return null;
}
private NameState findMatchPattern(ValuePatterns pattern) {
return findMatchPattern(getParser().parse(pattern.type(), pattern.pattern()), pattern);
}
private NameState findMatchPattern(final InputCharacter[] characters, final Patterns pattern) {
Set<SingleByteTransition> transitionsToProcess = new HashSet<>();
transitionsToProcess.add(startState);
ByteTransition shortcutTrans = null;
// Iterate down all possible paths in machine that match characters.
outerLoop: for (int i = 0; i < characters.length - 1; i++) {
Set<SingleByteTransition> nextTransitionsToProcess = new HashSet<>();
for (SingleByteTransition trans : transitionsToProcess) {
ByteTransition nextTrans = getTransition(trans, characters[i]);
for (SingleByteTransition eachTrans : nextTrans.expand()) {
// Shortcut and stop outer character loop
if (SHORTCUT_MATCH_TYPES.contains(pattern.type()) && eachTrans.isShortcutTrans()) {
shortcutTrans = eachTrans;
break outerLoop;
}
SingleByteTransition nextByteState = eachTrans.getNextByteState();
if (nextByteState == null) {
continue;
}
// We are interested in the first state that hasn't simply led back to trans
if (trans != nextByteState) {
nextTransitionsToProcess.add(nextByteState);
}
}
}
transitionsToProcess = nextTransitionsToProcess;
}
// Get all possible transitions for final character.
Set<ByteTransition> finalTransitionsToProcess = new HashSet<>();
if (shortcutTrans != null) {
finalTransitionsToProcess.add(shortcutTrans);
} else {
for (SingleByteTransition trans : transitionsToProcess) {
finalTransitionsToProcess.add(getTransition(trans, characters[characters.length - 1]));
}
}
// Check matches for all possible final transitions until we find the pattern we are looking for.
for (ByteTransition nextTrans : finalTransitionsToProcess) {
for (ByteMatch match : nextTrans.getMatches()) {
if (match.getPattern().equals(pattern)) {
return match.getNextNameState();
}
}
}
return null;
}
// before we accept the delete range pattern, the input range pattern must exactly match Range ByteMatch
// in all path along the range.
private NameState findRangePattern(Range range) {
Set<NameState> nextNameStates = new HashSet<>();
NameState nextNameState = null;
ByteTransition forkTrans = startState;
int forkOffset = 0;
// bypass common prefix of range's bottom and top patterns
while (range.bottom[forkOffset] == range.top[forkOffset]) {
forkTrans = findNextByteStateForRangePattern(forkTrans, range.bottom[forkOffset++]);
if (forkTrans == null) {
return null;
}
}
// fill in matches in the fork state
for (byte bb : Range.digitSequence(range.bottom[forkOffset], range.top[forkOffset], false, false)) {
nextNameState = findMatchForRangePattern(bb, forkTrans, range);
if (nextNameState == null) {
return null;
}
nextNameStates.add(nextNameState);
}
// process all the transitions on the bottom range bytes
ByteTransition trans = forkTrans;
int lastMatchOffset = forkOffset;
for (int offsetB = forkOffset + 1; offsetB < (range.bottom.length - 1); offsetB++) {
byte b = range.bottom[offsetB];
if (b < Constants.MAX_DIGIT) {
while (lastMatchOffset < offsetB) {
trans = findNextByteStateForRangePattern(trans, range.bottom[lastMatchOffset++]);
if (trans == null) {
return null;
}
}
assert lastMatchOffset == offsetB : "lastMatchOffset == offsetB";
for (byte bb : Range.digitSequence(b, Constants.MAX_DIGIT, false, true)) {
nextNameState = findMatchForRangePattern(bb, trans, range);
if (nextNameState == null) {
return null;
}
nextNameStates.add(nextNameState);
}
}
}
// now for last "bottom" digit
final byte lastBottom = range.bottom[range.bottom.length - 1];
final byte lastTop = range.top[range.top.length - 1];
if ((lastBottom < Constants.MAX_DIGIT) || !range.openBottom) {
while (lastMatchOffset < range.bottom.length - 1) {
trans = findNextByteStateForRangePattern(trans, range.bottom[lastMatchOffset++]);
if (trans == null) {
return null;
}
}
assert lastMatchOffset == (range.bottom.length - 1) : "lastMatchOffset == (range.bottom.length - 1)";
if (!range.openBottom) {
nextNameState = findMatchForRangePattern(lastBottom, trans, range);
if (nextNameState == null) {
return null;
}
nextNameStates.add(nextNameState);
}
// unless the last digit is also at the fork position, fill in the extra matches due to
// the strictly-less-than condition (see discussion above)
if (forkOffset < (range.bottom.length - 1)) {
for (byte bb : Range.digitSequence(lastBottom, Constants.MAX_DIGIT, false, true)) {
nextNameState = findMatchForRangePattern(bb, trans, range);
if (nextNameState == null) {
return null;
}
nextNameStates.add(nextNameState);
}
}
}
// now process transitions along the top range bytes
trans = forkTrans;
lastMatchOffset = forkOffset;
for (int offsetT = forkOffset + 1; offsetT < (range.top.length - 1); offsetT++) {
byte b = range.top[offsetT];
if (b > '0') {
while (lastMatchOffset < offsetT) {
trans = findNextByteStateForRangePattern(trans, range.top[lastMatchOffset++]);
if (trans == null) {
return null;
}
}
assert lastMatchOffset == offsetT : "lastMatchOffset == offsetT";
for (byte bb : Range.digitSequence((byte) '0', range.top[offsetT], true, false)) {
nextNameState = findMatchForRangePattern(bb, trans, range);
if (nextNameState == null) {
return null;
}
nextNameStates.add(nextNameState);
}
}
}
// now for last "top" digit
if ((lastTop > '0') || !range.openTop) {
while (lastMatchOffset < range.top.length - 1) {
trans = findNextByteStateForRangePattern(trans, range.top[lastMatchOffset++]);
if (trans == null) {
return null;
}
}
assert lastMatchOffset == (range.top.length - 1) : "lastMatchOffset == (range.top.length - 1)";
if (!range.openTop) {
nextNameState = findMatchForRangePattern(lastTop, trans, range);
if (nextNameState == null) {
return null;
}
nextNameStates.add(nextNameState);
}
// unless the last digit is also at the fork position, fill in the extra matches due to
// the strictly-less-than condition (see discussion above)
if (forkOffset < (range.top.length - 1)) {
for (byte bb : Range.digitSequence((byte) '0', lastTop, true, false)) {
nextNameState = findMatchForRangePattern(bb, trans, range);
if (nextNameState == null) {
return null;
}
nextNameStates.add(nextNameState);
}
}
}
// There must only have one nextNameState object returned by this range pattern refer to
// addRangePattern() where only one nextNameState is used by one pattern.
assert nextNameStates.size() == 1 : "nextNameStates.size() == 1";
return nextNameState;
}
// add a numeric range expression to the byte machine. Note; the code assumes that the patterns
// are encoded as pure strings containing only decimal digits, and that the top and bottom values
// are equal in length.
private NameState addRangePattern(final Range range, final NameState nameState) {
// we prepare for one new NameSate here which will be used for range match to point to next NameSate.
// however, it will not be used if match is already existing. in that case, we will reuse NameSate
// from that match.
NameState nextNameState = nameState == null ? new NameState() : nameState;
ByteState forkState = startState;
int forkOffset = 0;
// bypass common prefix of range's bottom and top patterns
while (range.bottom[forkOffset] == range.top[forkOffset]) {
forkState = findOrMakeNextByteStateForRangePattern(forkState, range.bottom, forkOffset++);
}
// now we've bypassed any initial positions where the top and bottom patterns are the same, and arrived
// at a position where the 'top' and 'bottom' bytes differ. Such a position must occur because we require
// that the bottom number be strictly less than the top number. Let's call the current state the fork state.
// At the fork state, any byte between the top and bottom byte values means success, the value must be strictly
// greater than bottom and less than top. That leaves the transitions for the bottom and top values.
// After the fork state, we arrive at a state where any digit greater than the next bottom value
// means success, because after the fork state we are already strictly less than the top value, and we
// know then that we are greater than the bottom value. A digit equal to the bottom value leads us
// to another state where the same applies; anything greater than the bottom value is success. Finally,
// when we come to the last digit, as before, anything greater than the bottom value is success, and
// being equal to the bottom value means failure if the interval is open, because the value is strictly
// equal to the bottom of the range.
// Following the top-byte transition out of the fork state leads to a state where the story is reversed;
// any digit lower than the top value means success, successive matches to the top value lead to similar
// states, and a final byte that matches the top value means failure if the interval is open at the top.
// There is a further complication. Consider the case [ > 00299 < 00500 ]. The machine we need to
// build is like this:
// State0 =0=> State1 ; State1 =0=> State2 ; State2 =3=> MATCH ; State2 =4=> MATCH
// That's it. Once you've seen 002 in the input, there's nothing that can follow that will be
// strictly greater than the remaining 299. Once you've seen 005 there's nothing that can
// follow that will be strictly less than the remaining 500
// But this only works when the suffix of the bottom range pattern is all 9's or if the suffix of the
// top range pattern is all 0's
// What could be simpler?
// fill in matches in the fork state
for (byte bb : Range.digitSequence(range.bottom[forkOffset], range.top[forkOffset], false, false)) {
nextNameState = insertMatchForRangePattern(bb, forkState, nextNameState, range);
}
// process all the transitions on the bottom range bytes
ByteState state = forkState;
// lastMatchOffset is the last offset where we know we have to put in a match
int lastMatchOffset = forkOffset;
for (int offsetB = forkOffset + 1; offsetB < (range.bottom.length - 1); offsetB++) {
// if b is Constants.MAX_DIGIT, then we should hold off adding transitions until we see a non-maxDigit digit
// because of the special case described above.
byte b = range.bottom[offsetB];
if (b < Constants.MAX_DIGIT) {
// add transitions for any 9's we bypassed
while (lastMatchOffset < offsetB) {
state = findOrMakeNextByteStateForRangePattern(state, range.bottom, lastMatchOffset++);
}
assert lastMatchOffset == offsetB : "lastMatchOffset == offsetB";
assert state != null : "state != null";
// now add transitions for values greater than this non-9 digit
for (byte bb : Range.digitSequence(b, Constants.MAX_DIGIT, false, true)) {
nextNameState = insertMatchForRangePattern(bb, state, nextNameState, range);
}
}
}
// now for last "bottom" digit
final byte lastBottom = range.bottom[range.bottom.length - 1];
final byte lastTop = range.top[range.top.length - 1];
// similarly, if the last digit is 9 and we have openBottom, there can be no matches so we're done.
if ((lastBottom < Constants.MAX_DIGIT) || !range.openBottom) {
// add transitions for any 9's we bypassed
while (lastMatchOffset < range.bottom.length - 1) {
state = findOrMakeNextByteStateForRangePattern(state, range.bottom, lastMatchOffset++);
}
assert lastMatchOffset == (range.bottom.length - 1) : "lastMatchOffset == (range.bottom.length - 1)";
assert state != null : "state != null";
// now we insert matches for possible values of last digit
if (!range.openBottom) {
nextNameState = insertMatchForRangePattern(lastBottom, state, nextNameState, range);
}
// unless the last digit is also at the fork position, fill in the extra matches due to
// the strictly-less-than condition (see discussion above)
if (forkOffset < (range.bottom.length - 1)) {
for (byte bb : Range.digitSequence(lastBottom, Constants.MAX_DIGIT, false, true)) {
nextNameState = insertMatchForRangePattern(bb, state, nextNameState, range);
}
}
}
// now process transitions along the top range bytes
// restore the state and last match offset to fork position to start analyzing top value bytes ...
state = forkState;
lastMatchOffset = forkOffset;
for (int offsetT = forkOffset + 1; offsetT < (range.top.length - 1); offsetT++) {
// if b is '0', we should hold off adding transitions until we see a non-'0' digit.
byte b = range.top[offsetT];
// if need to add transition
if (b > '0') {
while (lastMatchOffset < offsetT) {
state = findOrMakeNextByteStateForRangePattern(state, range.top, lastMatchOffset++);
}
assert lastMatchOffset == offsetT : "lastMatchOffset == offsetT";
assert state != null : "state != null";
// now add transitions for values less than this non-0 digit
for (byte bb : Range.digitSequence((byte) '0', range.top[offsetT], true, false)) {
nextNameState = insertMatchForRangePattern(bb, state, nextNameState, range);
}
}
}
// now for last "top" digit
// similarly, if the last digit is 0 and we have openTop, there can be no matches so we're done.
if ((lastTop > '0') || !range.openTop) {
// add transitions for any 0's we bypassed
while (lastMatchOffset < range.top.length - 1) {
state = findOrMakeNextByteStateForRangePattern(state, range.top, lastMatchOffset++);
}
assert lastMatchOffset == (range.top.length - 1) : "lastMatchOffset == (range.top.length - 1)";
assert state != null : "state != null";
// now we insert matches for possible values of last digit
if (!range.openTop) {
nextNameState = insertMatchForRangePattern(lastTop, state, nextNameState, range);
}
// unless the last digit is also at the fork position, fill in the extra matches due to
// the strictly-less-than condition (see discussion above)
if (forkOffset < (range.top.length - 1)) {
for (byte bb : Range.digitSequence((byte) '0', lastTop, true, false)) {
nextNameState = insertMatchForRangePattern(bb, state, nextNameState, range);
}
}
}
return nextNameState;
}
// If we meet shortcut trans, that means Range have byte overlapped with shortcut matches,
// To simplify the logic, we extend the shortcut to normal byte state chain, then decide whether need create
// new byte state for current call.
private ByteTransition extendShortcutTransition(final ByteState state, final ByteTransition trans,
final InputCharacter character, final int currentIndex) {
if (!trans.isShortcutTrans()) {
return trans;
}
ShortcutTransition shortcut = (ShortcutTransition) trans;
Patterns shortcutPattern = shortcut.getMatch().getPattern();
String valueInCurrentPos = ((ValuePatterns) shortcutPattern).pattern();
final InputCharacter[] charactersInCurrentPos = getParser().parse(shortcutPattern.type(), valueInCurrentPos);
ByteState firstNewState = null;
ByteState currentState = state;
for (int k = currentIndex; k < charactersInCurrentPos.length-1; k++) {
// we need keep the current state always pointed to last character.
final ByteState newByteState = new ByteState();
newByteState.setIndeterminatePrefix(currentState.hasIndeterminatePrefix());
if (k != currentIndex) {
putTransitionNextState(currentState, charactersInCurrentPos[k], shortcut, newByteState);
} else {
firstNewState = newByteState;
}
currentState = newByteState;
}
putTransitionMatch(currentState, charactersInCurrentPos[charactersInCurrentPos.length-1],
EmptyByteTransition.INSTANCE, shortcut.getMatch());
removeTransition(currentState, charactersInCurrentPos[charactersInCurrentPos.length-1], shortcut);
putTransitionNextState(state, character, shortcut, firstNewState);
return getTransition(state, character);
}
private ByteState findOrMakeNextByteStateForRangePattern(ByteState state, final byte[] utf8bytes,
int currentIndex) {
final InputCharacter character = getParser().parse(utf8bytes[currentIndex]);
ByteTransition trans = getTransition(state, character);
ByteState nextState = trans.getNextByteState();
if (nextState == null) {
// the next state is null => create a new state, set the transition's next state to the new state
nextState = new ByteState();
nextState.setIndeterminatePrefix(state.hasIndeterminatePrefix());
putTransitionNextState(state, character, trans.expand().iterator().next(), nextState);
}
return nextState;
}
// Return the next byte state after transitioning from state using character at currentIndex. Will create it if it
// doesn't exist.
private ByteState findOrMakeNextByteState(ByteState state, ByteState prevState, final InputCharacter[] characters,
int currentIndex, Patterns pattern, NameState nameState) {
final InputCharacter character = characters[currentIndex];
ByteTransition trans = getTransition(state, character);
trans = extendShortcutTransition(state, trans, character, currentIndex);
ByteState nextState = trans.getNextByteState();
if (nextState == null || nextState.hasIndeterminatePrefix() ||
(currentIndex == characters.length - 2 && isWildcard(characters[currentIndex + 1]))) {
// There are three cases for which we cannot re-use the next state and must add a new next state.
// 1. Next state is null (does not exist).
// 2. Next state has an indeterminate prefix, so using it would create unintended matches.
// 3. We're on second last char and last char is wildcard: next state will be composite with match so empty
// substring satisfies wildcard. The composite will self-reference and would create unintended matches.
nextState = new ByteState();
nextState.setIndeterminatePrefix(state.hasIndeterminatePrefix());
addTransitionNextState(state, character, characters, currentIndex, prevState, pattern, nextState,
nameState);
}
return nextState;
}
private ByteTransition findNextByteStateForRangePattern(ByteTransition trans, final byte b) {
if (trans == null) {
return null;
}
ByteTransition nextTrans = getTransition(trans, b);
return nextTrans.getTransitionForNextByteStates();
}
// add a match type pattern, i.e. anything but a numeric range, to the byte machine.
private NameState addMatchPattern(final ValuePatterns pattern, final NameState nameState) {
return addMatchValue(pattern, pattern.pattern(), nameState);
}
// We can reach to this function when we have checked the existing characters array from left to right and found we
// need add the match in the tail character or we find we can shortcut to tail directly without creating new byte
// transition in the middle. If we met the shortcut transition, we need compare the input value to adjust it
// accordingly. Please refer to detail comments in ShortcutTransition.java.
private NameState addEndOfMatch(ByteState state,
ByteState prevState,
final InputCharacter[] characters,
final int charIndex,
final Patterns pattern,
final NameState nameStateCandidate) {
final int length = characters.length;
NameState nameState = (nameStateCandidate == null) ? new NameState() : nameStateCandidate;
if (length == 1 && isWildcard(characters[0])) {
// Only character is '*'. Make the start state a match so empty input is matched.
startStateMatch = new ByteMatch(pattern, nameState);
return nameState;
}
ByteTransition trans = getTransition(state, characters[charIndex]);
// If it is shortcut transition, we need do adjustment first.
if (!trans.isEmpty() && trans.isShortcutTrans()) {
ShortcutTransition shortcut = (ShortcutTransition) trans;
ByteMatch match = shortcut.getMatch();
// In add/delete rule path, match must not be null and must not have other match
assert match != null && SHORTCUT_MATCH_TYPES.contains(match.getPattern().type());
// If it is the same pattern, just return.
if (pattern.equals(match.getPattern())) {
return match.getNextNameState();
}
// Have asserted current match pattern must be value patterns
String valueInCurrentPos = ((ValuePatterns) match.getPattern()).pattern();
final InputCharacter[] charactersInCurrentPos = getParser().parse(match.getPattern().type(),
valueInCurrentPos);
// find the position <m> where the common prefix ends.
int m = charIndex;
for (; m < charactersInCurrentPos.length && m < length; m++) {
if (!charactersInCurrentPos[m].equals(characters[m])) {
break;
}
}
// Extend the prefix part in value to byte transitions, to avoid impact on concurrent read we need firstly
// make the new byte chain ready for using and leave the old transition removing to the last step.
// firstNewState will be head of new byte chain and, to avoid impact on concurrent match traffic in read
// path, it need be linked to current state chain after adjustment done.
ByteState firstNewState = null;
ByteState currentState = state;
for (int k = charIndex; k < m; k++) {
// we need keep the current state always pointed to last character.
if (k != charactersInCurrentPos.length -1) {
final ByteState newByteState = new ByteState();
newByteState.setIndeterminatePrefix(currentState.hasIndeterminatePrefix());
if (k != charIndex) {
putTransitionNextState(currentState, charactersInCurrentPos[k], shortcut, newByteState);
} else {
firstNewState = newByteState;
}
currentState = newByteState;
}
}
// If it reached to last character, link the previous read transition in this character, else create
// shortcut transition. Note: at this time, the previous transition can still keep working.
boolean isShortcutNeeded = m < charactersInCurrentPos.length - 1;
int indexToBeChange = isShortcutNeeded ? m : charactersInCurrentPos.length - 1;
putTransitionMatch(currentState, charactersInCurrentPos[indexToBeChange], isShortcutNeeded ?
new ShortcutTransition() : EmptyByteTransition.INSTANCE, match);
removeTransition(currentState, charactersInCurrentPos[indexToBeChange], shortcut);
// At last, we link the new created chain to the byte state path, so no uncompleted change can be felt by
// reading thread. Note: we already confirmed there is only old shortcut transition at charIndex position,
// now we have move it to new position, so we can directly replace previous transition with new transition
// pointed to new byte state chain.
putTransitionNextState(state, characters[charIndex], shortcut, firstNewState);
}
// If there is a exact match transition on tail of path, after adjustment target transitions, we start
// looking at current remaining characters.
// If this is tail transition, go directly analyse the remaining characters, traverse to tail of chain:
boolean isEligibleForShortcut = true;
int j = charIndex;
for (; j < (length - 1); j++) {
// We do not want to re-use an existing state for the second last character in the case of a final-character
// wildcard pattern. In this case, we will have a self-referencing composite match state, which allows zero
// or many character to satisfy the wildcard. The self-reference would lead to unintended matches for the
// existing patterns.
if (j == length - 2 && isWildcard(characters[j + 1])) {
break;
}
trans = getTransition(state, characters[j]);
if (trans.isEmpty()) {
break;
}
ByteState nextByteState = trans.getNextByteState();
if (nextByteState != null) {
// We cannot re-use a state with an indeterminate prefix without creating unintended matches.
if (nextByteState.hasIndeterminatePrefix()) {
// Since there is more path we are unable to traverse, this means we cannot insert shortcut without
// potentially ignoring matches further down path.
isEligibleForShortcut = false;
break;
}
prevState = state;
state = nextByteState;
} else {
// trans has match but no next state, we need prepare a next next state to add trans for either last
// character or shortcut byte.
final ByteState newByteState = new ByteState();
newByteState.setIndeterminatePrefix(state.hasIndeterminatePrefix());
// Stream will not be empty since trans has been verified as non-empty
SingleByteTransition single = trans.expand().iterator().next();
putTransitionNextState(state, characters[j], single, newByteState);
prevState = state;
state = newByteState;
}
}
// look for a chance to put in a shortcut transition.
// However, for the moment, we only do this for a JSON string match i.e beginning with ", not literals
// like true or false or numbers, because if we do this for numbers produced by
// ComparableNumber.generate(), they can be messed up by addRangePattern.
if (SHORTCUT_MATCH_TYPES.contains(pattern.type())) {
// For exactly match, if it is last character already, we just put the real transition with match there.
if (j == length - 1) {
return insertMatch(characters, j, state, nameState, pattern, prevState);
} else if (isEligibleForShortcut) {
// If current character is not last character, create the shortcut transition with the next
ByteMatch byteMatch = new ByteMatch(pattern, nameState);
addTransition(state, characters[j], new ShortcutTransition().setMatch(byteMatch));
addMatchReferences(byteMatch);
return nameState;
}
}
// For other match type, keep the old logic to extend all characters to byte state path and put the match in the
// tail state.
for (; j < (length - 1); j++) {
ByteState nextByteState = findOrMakeNextByteState(state, prevState, characters, j, pattern, nameState);
prevState = state;
state = nextByteState;
}
return insertMatch(characters, length - 1, state, nameState, pattern, prevState);
}
private NameState insertMatchForRangePattern(byte b, ByteState state, NameState nextNameState,
Patterns pattern) {
return insertMatch(new InputCharacter[] { getParser().parse(b) }, 0, state, nextNameState, pattern, null);
}
private NameState insertMatch(InputCharacter[] characters, int currentIndex, ByteState state,
NameState nextNameState, Patterns pattern, ByteState prevState) {
InputCharacter character = characters[currentIndex];
ByteMatch match = findMatch(getTransition(state, character).getMatches(), pattern);
if (match != null) {
// There is a match linked to the transition that's the same type, so we just re-use its nextNameState
return match.getNextNameState();
}
// we make a new NameState and hook it up
NameState nameState = nextNameState == null ? new NameState() : nextNameState;
match = new ByteMatch(pattern, nameState);
addMatchReferences(match);
if (isWildcard(character)) {
// Rule ends with '*'. Allow no characters up to many characters to match, using a composite match state
// that references a self-referencing composite match state. Two composite states are used so the count of
// matching rule prefixes is accurate in MachineComplexityEvaluator. If there is a previous state, then the
// first composite already exists and we will find it. Otherwise, create a brand new composite.
SingleByteTransition composite;
if (prevState != null) {
composite = getTransitionHavingNextByteState(prevState, state, characters[currentIndex - 1]);
assert composite != null : "Composite must exist";
} else {
composite = new ByteState().setMatch(match);
}
ByteState nextState = composite.getNextByteState();
CompositeByteTransition compositeClone = (CompositeByteTransition) composite.clone();
nextState.addTransitionForAllBytes(compositeClone);
nextState.setIndeterminatePrefix(true);
} else {
addTransition(state, character, match);
// If second last char was wildcard, the previous state will also need to transition to the match so that
// empty substring matches wildcard.
if (prevState != null && currentIndex == characters.length - 1 &&
isWildcard(characters[characters.length - 2])) {
addTransition(prevState, character, match);
}
}
return nameState;
}
/**
* Gets the first transition originating from origin on character that has a next byte state of toFind.
*
* @param origin The origin transition that we will explore transitions from.
* @param toFind The state that we are looking for from origin's transitions.
* @param character The character to retrieve transitions from origin.
* @return Origin's first transition on character that has a next byte state of toFind, or null if not found.
*/
private static SingleByteTransition getTransitionHavingNextByteState(SingleByteTransition origin,
SingleByteTransition toFind, InputCharacter character) {
for (SingleByteTransition eachTrans : getTransition(origin, character).expand()) {
if (eachTrans.getNextByteState() == toFind) {
return eachTrans;
}
}
return null;
}
private void addMatchReferences(ByteMatch match) {
Patterns pattern = match.getPattern();
switch (pattern.type()) {
case EXACT:
case PREFIX:
case PREFIX_EQUALS_IGNORE_CASE:
case EXISTS:
case EQUALS_IGNORE_CASE:
case WILDCARD:
break;
case SUFFIX:
case SUFFIX_EQUALS_IGNORE_CASE:
hasSuffix.incrementAndGet();
break;
case NUMERIC_EQ:
hasNumeric.incrementAndGet();
break;
case NUMERIC_RANGE:
final Range range = (Range) pattern;
if (range.isCIDR) {
hasIP.incrementAndGet();
} else {
hasNumeric.incrementAndGet();
}
break;
case ANYTHING_BUT:
addToAnythingButsMap(anythingButs, match.getNextNameState(), match.getPattern());
if (((AnythingBut) pattern).isNumeric()) {
hasNumeric.incrementAndGet();
}
break;
case ANYTHING_BUT_IGNORE_CASE:
addToAnythingButsMap(anythingButs, match.getNextNameState(), match.getPattern());
break;
case ANYTHING_BUT_SUFFIX:
hasSuffix.incrementAndGet();
addToAnythingButsMap(anythingButs, match.getNextNameState(), match.getPattern());
break;
case ANYTHING_BUT_PREFIX:
addToAnythingButsMap(anythingButs, match.getNextNameState(), match.getPattern());
break;
default:
throw new AssertionError("Not implemented yet");
}
}
private NameState findMatchForRangePattern(byte b, ByteTransition trans, Patterns pattern) {
if (trans == null) {
return null;
}
ByteTransition nextTrans = getTransition(trans, b);
ByteMatch match = findMatch(nextTrans.getMatches(), pattern);
return match == null ? null : match.getNextNameState();
}
/**
* Deletes any matches that exist on the given pattern that are accessed from ByteTransition transition using
* character.
*
* @param character The character used to transition.
* @param transition The transition we are transitioning from to look for matches.
* @param pattern The pattern whose match we are attempting to delete.
*/
private void deleteMatches(InputCharacter character, ByteTransition transition, Patterns pattern) {
if (transition == null) {
return;
}
for (SingleByteTransition single : transition.expand()) {
ByteTransition trans = getTransition(single, character);
for (SingleByteTransition eachTrans : trans.expand()) {
deleteMatch(character, single.getNextByteState(), pattern, eachTrans);
}
}
}
/**
* Deletes a match, if it exists, on the given pattern that is accessed from ByteState state using character to
* transition over SingleByteTransition trans.
*
* @param character The character used to transition.
* @param state The state we are transitioning from.
* @param pattern The pattern whose match we are attempting to delete.
* @param trans The transition to the match.
* @return The updated transition (may or may not be same object as trans) if the match was found. Null otherwise.
*/
private SingleByteTransition deleteMatch(InputCharacter character, ByteState state, Patterns pattern,
SingleByteTransition trans) {
if (state == null) {
return null;
}
ByteMatch match = trans.getMatch();
if (match != null && match.getPattern().equals(pattern)) {
updateMatchReferences(match);
return putTransitionMatch(state, character, trans, null);
}
return null;
}
private void updateMatchReferences(ByteMatch match) {
Patterns pattern = match.getPattern();
switch (pattern.type()) {
case EXACT:
case PREFIX:
case PREFIX_EQUALS_IGNORE_CASE:
case EXISTS:
case EQUALS_IGNORE_CASE:
case WILDCARD:
break;
case SUFFIX:
case SUFFIX_EQUALS_IGNORE_CASE:
hasSuffix.decrementAndGet();
break;
case NUMERIC_EQ:
hasNumeric.decrementAndGet();
break;
case NUMERIC_RANGE:
final Range range = (Range) pattern;
if (range.isCIDR) {
hasIP.decrementAndGet();
} else {
hasNumeric.decrementAndGet();
}
break;
case ANYTHING_BUT:
removeFromAnythingButsMap(anythingButs, match.getNextNameState(), match.getPattern());
if (((AnythingBut) pattern).isNumeric()) {
hasNumeric.decrementAndGet();
}
break;
case ANYTHING_BUT_IGNORE_CASE:
removeFromAnythingButsMap(anythingButs, match.getNextNameState(), match.getPattern());
break;
case ANYTHING_BUT_SUFFIX:
hasSuffix.decrementAndGet();
removeFromAnythingButsMap(anythingButs, match.getNextNameState(), match.getPattern());
break;
case ANYTHING_BUT_PREFIX:
removeFromAnythingButsMap(anythingButs, match.getNextNameState(), match.getPattern());
break;
default:
throw new AssertionError("Not implemented yet");
}
}
private static ByteTransition getTransition(ByteTransition trans, byte b) {
ByteTransition nextTrans = trans.getTransition(b);
return nextTrans == null ? EmptyByteTransition.INSTANCE : nextTrans;
}
private static ByteTransition getTransition(SingleByteTransition trans, InputCharacter character) {
switch (character.getType()) {
case WILDCARD:
return trans.getTransitionForAllBytes();
case MULTI_BYTE_SET:
return getTransitionForMultiBytes(trans, InputMultiByteSet.cast(character).getMultiBytes());
case BYTE:
return getTransition(trans, InputByte.cast(character).getByte());
default:
throw new AssertionError("Not implemented yet");
}
}
private static ByteTransition getTransitionForMultiBytes(SingleByteTransition trans, Set<MultiByte> multiBytes) {
Set<SingleByteTransition> candidates = new HashSet<>();
for (MultiByte multiByte : multiBytes) {
ByteTransition currentTransition = trans;
for (byte b : multiByte.getBytes()) {
ByteTransition nextTransition = currentTransition.getTransition(b);
if (nextTransition == null) {
return EmptyByteTransition.INSTANCE;
}
currentTransition = nextTransition;
}
if (candidates.isEmpty()) {
currentTransition.expand().forEach(t -> candidates.add(t));
} else {
Set<SingleByteTransition> retainThese = new HashSet<>();
currentTransition.expand().forEach(t -> retainThese.add(t));
candidates.retainAll(retainThese);
if (candidates.isEmpty()) {
return EmptyByteTransition.INSTANCE;
}
}
}
return coalesce(candidates);
}
private static void addTransitionNextState(ByteState state, InputCharacter character, InputCharacter[] characters,
int currentIndex, ByteState prevState, Patterns pattern,
ByteState nextState, NameState nameState) {
if (isWildcard(character)) {
addTransitionNextStateForWildcard(state, nextState);
} else {
// If the last character is the wildcard character, and we're on the second last character, set a match on
// the transition (turning it into a composite) before adding transitions from state and prevState.
SingleByteTransition single = nextState;
if (isWildcard(characters[characters.length - 1]) && currentIndex == characters.length - 2) {
ByteMatch match = new ByteMatch(pattern, nameState);
single = nextState.setMatch(match);
nextState.setIndeterminatePrefix(true);
} else if (isMultiByteSet(character)) {
nextState.setIndeterminatePrefix(true);
}
addTransition(state, character, single);
// If there was a previous state and it transitioned using the wildcard character, we need to add a
// transition from the previous state to allow wildcard match on empty substring.
if (prevState != null && isWildcard(characters[currentIndex - 1])) {
addTransition(prevState, character, single);
}
}
}
/**
* Assuming a current wildcard character, a next character of byte b, a current state of A, a next state of B, and a
* next next state of C, this function produces the following state machine:
*
* ____
* * | * |
* A ---> B <--
*
* When processing the next byte (b) of the current rule, which transitions to the next next state of C, the
* addTransitionNextState function will be invoked to transform the state machine to:
*
* ____ ____
* * | * | * | * |
* A ---> B <-- A -----> B <--
* b | =====> | b b |
* C <-- --> C <--
*
* A more naive implementation would skip B altogether, like:
*
* ____
* | * | b
* --> A ---> C
*
* But the naive implementation does not work in the case of multiple rules in one machine. Since the current state,
* A, may already have transitions for other rules, adding a self-referential * transition to A can lead to
* unintended matches using those existing rules. We must create a new state (B) that the wildcard byte transitions
* to so that we do not affect existing rules in the machine.
*
* @param state The current state.
* @param nextState The next state.
*/
private static void addTransitionNextStateForWildcard(ByteState state,
ByteState nextState) {
// Add self-referential * transition to next state (B).
nextState.addTransitionForAllBytes(nextState);
nextState.setIndeterminatePrefix(true);
// Add * transition from current state (A) to next state (B).
state.addTransitionForAllBytes(nextState);
}
private static void putTransitionNextState(ByteState state, InputCharacter character,
SingleByteTransition transition, ByteState nextState) {
// In order to avoid change being felt by the concurrent query thread in the middle of change, we clone the
// trans firstly and will not update state store until the changes have completely applied in the new trans.
ByteTransition trans = transition.clone();
SingleByteTransition single = trans.setNextByteState(nextState);
if (single != null && !single.isEmpty() && single != transition) {
addTransition(state, character, single);
}
removeTransition(state, character, transition);
}
/**
* Returns the cloned transition with the match set.
*/
private static SingleByteTransition putTransitionMatch(ByteState state, InputCharacter character,
SingleByteTransition transition, ByteMatch match) {
// In order to avoid change being felt by the concurrent query thread in the middle of change, we clone the
// trans firstly and will not update state store until the changes have completely applied in the new trans.
SingleByteTransition trans = (SingleByteTransition) transition.clone();
SingleByteTransition single = trans.setMatch(match);
if (single != null && !single.isEmpty() && single != transition) {
addTransition(state, character, single);
}
removeTransition(state, character, transition);
return single;
}
private static void removeTransition(ByteState state, InputCharacter character, SingleByteTransition transition) {
if (isWildcard(character)) {
state.removeTransitionForAllBytes(transition);
} else if (isMultiByteSet(character)) {
removeTransitionForMultiByteSet(state, InputMultiByteSet.cast(character), transition);
} else {
state.removeTransition(InputByte.cast(character).getByte(), transition);
}
}
private static void removeTransitionForMultiByteSet(ByteState state, InputMultiByteSet multiByteSet,
SingleByteTransition transition) {
for (MultiByte multiByte : multiByteSet.getMultiBytes()) {
removeTransitionForBytes(state, multiByte.getBytes(), 0, transition);
}
}
private static void removeTransitionForBytes(ByteState state, byte[] bytes, int index,
SingleByteTransition transition) {
if (index == bytes.length - 1) {
state.removeTransition(bytes[index], transition);
} else {
for (SingleByteTransition single : getTransition(state, bytes[index]).expand()) {
ByteState nextState = single.getNextByteState();
if (nextState != null) {
removeTransitionForBytes(nextState, bytes, index + 1, transition);
if (nextState.hasNoTransitions() || nextState.hasOnlySelfReferentialTransition()) {
state.removeTransition(bytes[index], single);
}
}
}
}
}
private static void addTransition(ByteState state, InputCharacter character, SingleByteTransition transition) {
if (isWildcard(character)) {
state.putTransitionForAllBytes(transition);
} else if (isMultiByteSet(character)) {
addTransitionForMultiByteSet(state, InputMultiByteSet.cast(character), transition);
} else {
state.addTransition(InputByte.cast(character).getByte(), transition);
}
}
private static void addTransitionForMultiByteSet(ByteState state, InputMultiByteSet multiByteSet,
SingleByteTransition transition) {
for (MultiByte multiByte : multiByteSet.getMultiBytes()) {
byte[] bytes = multiByte.getBytes();
ByteState currentState = state;
for (int i = 0; i < bytes.length - 1; i++) {
ByteState nextState = new ByteState();
nextState.setIndeterminatePrefix(true);
currentState.addTransition(bytes[i], nextState);
currentState = nextState;
}
currentState.addTransition(bytes[bytes.length - 1], transition);
}
}
private static ByteMatch findMatch(Iterable<ByteMatch> matches, Patterns pattern) {
for (ByteMatch match : matches) {
if (match.getPattern().equals(pattern)) {
return match;
}
}
return null;
}
private static boolean isByte(InputCharacter character) {
return character.getType() == InputCharacterType.BYTE;
}
private static boolean isWildcard(InputCharacter character) {
return character.getType() == InputCharacterType.WILDCARD;
}
private static boolean isMultiByteSet(InputCharacter character) {
return character.getType() == InputCharacterType.MULTI_BYTE_SET;
}
public int evaluateComplexity(MachineComplexityEvaluator evaluator) {
return (startStateMatch != null ? 1 : 0) + evaluator.evaluate(startState);
}
public void gatherObjects(Set<Object> objectSet, int maxObjectCount) {
if (!objectSet.contains(this) && objectSet.size() < maxObjectCount) { // stops looping
objectSet.add(this);
startState.gatherObjects(objectSet, maxObjectCount);
for (NameState states : anythingButs.keySet()) {
states.gatherObjects(objectSet, maxObjectCount);
}
}
}
public static final class EmptyByteTransition extends SingleByteTransition {
static final EmptyByteTransition INSTANCE = new EmptyByteTransition();
@Override
public ByteState getNextByteState() {
return null;
}
@Override
public SingleByteTransition setNextByteState(ByteState nextState) {
return nextState;
}
@Override
public ByteTransition getTransition(byte utf8byte) {
return null;
}
@Override
public ByteTransition getTransitionForAllBytes() {
return null;
}
@Override
public Set<ByteTransition> getTransitions() {
return Collections.emptySet();
}
@Override
public ByteMatch getMatch() {
return null;
}
@Override
public Set<ShortcutTransition> getShortcuts() {
return Collections.emptySet();
}
@Override
public SingleByteTransition setMatch(ByteMatch match) {
return match;
}
@Override
public void gatherObjects(Set<Object> objectSet, int maxObjectCount) {
if(objectSet.size() < maxObjectCount) {
objectSet.add(this);
}
}
}
@Override
public String toString() {
return "ByteMachine{" +
"startState=" + startState +
", hasNumeric=" + hasNumeric +
", hasIP=" + hasIP +
", hasSuffix=" + hasSuffix +
", anythingButs=" + anythingButs +
'}';
}
}
| 4,896 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/IntIntMap.java | package software.amazon.event.ruler;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A fast primitive int-int map implementation. Keys and values may only be positive.
*/
class IntIntMap implements Cloneable {
// taken from FastUtil
private static final int INT_PHI = 0x9E3779B9;
private static long KEY_MASK = 0xFFFFFFFFL;
private static final long EMPTY_CELL = -1 & KEY_MASK;
public static final int NO_VALUE = -1;
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* Capacity of 8, with data type long, translates to an initial {@link #table} of 64 bytes,
* which fits perfectly into the common cache line size.
*/
private static final int DEFAULT_INITIAL_CAPACITY = 8;
/**
* Holds key-value int pairs. The highest 32 bits hold the int value, and the lowest 32 bits
* hold the int key. Must always have a length that is a power of two so that {@link #mask} can
* be computed correctly.
*/
private long[] table;
/**
* Load factor, must be between (0 and 1)
*/
private final float loadFactor;
/**
* We will resize a map once it reaches this size
*/
private int threshold;
/**
* Current map size
*/
private int size;
/**
* Mask to calculate the position in the table for a key.
*/
private int mask;
IntIntMap() {
this(DEFAULT_INITIAL_CAPACITY);
}
IntIntMap(final int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
IntIntMap(final int initialCapacity, final float loadFactor) {
if (loadFactor <= 0 || loadFactor >= 1) {
throw new IllegalArgumentException("loadFactor must be in (0, 1)");
}
if (initialCapacity <= 0) {
throw new IllegalArgumentException("initialCapacity must be positive");
}
if (Integer.bitCount(initialCapacity) != 1) {
throw new IllegalArgumentException("initialCapacity must be a power of two");
}
this.mask = initialCapacity - 1;
this.loadFactor = loadFactor;
this.table = makeTable(initialCapacity);
this.threshold = (int) (initialCapacity * loadFactor);
}
/**
* Gets the value for {@code key}.
*
* @param key
* the non-negative key
* @return the value present at {@code key}, or {@link #NO_VALUE} if none is present.
*/
int get(final int key) {
int idx = getStartIndex(key);
do {
long cell = table[idx];
if (cell == EMPTY_CELL) {
// end of the chain, key does not exist
return NO_VALUE;
}
if (((int) (cell & KEY_MASK)) == key) {
// found the key
return (int) (cell >> 32);
}
// continue walking the chain
idx = getNextIndex(idx);
} while (true);
}
/**
* Puts {@code value} in {@code key}. {@code key} is restricted to positive integers to avoid an
* unresolvable collision with {@link #EMPTY_CELL}, while {@code value} is restricted to
* positive integers to avoid an unresolvable collision with {@link #NO_VALUE}.
*
* @param key
* the non-negative key
* @param value
* the non-negative value
* @return the value that was previously set for {@code key}, or {@link #NO_VALUE} if none was
* present.
* @throws IllegalArgumentException
* if {@code key} is negative
*/
int put(final int key, final int value) {
if (key < 0) {
throw new IllegalArgumentException("key cannot be negative");
}
if (value < 0) {
throw new IllegalArgumentException("value cannot be negative");
}
long cellToPut = (((long) key) & KEY_MASK) | (((long) value) << 32);
int idx = getStartIndex(key);
do {
long cell = table[idx];
if (cell == EMPTY_CELL) {
// found an empty cell
table[idx] = cellToPut;
if (size >= threshold) {
rehash(table.length * 2);
// 'size' is set inside rehash()
} else {
size++;
}
return NO_VALUE;
}
if (((int) (cell & KEY_MASK)) == key) {
// found a non-empty cell with a key matching the one we're writing, so overwrite it
table[idx] = cellToPut;
return (int) (cell >> 32);
}
// continue walking the chain
idx = getNextIndex(idx);
} while (true);
}
/**
* Removes {@code key}.
*
* @param key
* the non-negative key
* @return the removed value, or {@link #NO_VALUE} if none was present.
* @throws IllegalArgumentException
* if {@code key} is negative
*/
int remove(final int key) {
int idx = getStartIndex(key);
do {
long cell = table[idx];
if (cell == EMPTY_CELL) {
// end of the chain, key does not exist
return NO_VALUE;
}
if (((int) (cell & KEY_MASK)) == key) {
// found the key
size--;
shiftKeys(idx);
return (int) (cell >> 32);
}
// continue walking the chain
idx = getNextIndex(idx);
} while (true);
}
/**
* Returns the number of key-value mappings in this map.
*
* @return the number of key-value mappings in this map
*/
int size() {
return size;
}
boolean isEmpty() {
return size == 0;
}
public Iterable<Entry> entries() {
return new Iterable<Entry> () {
@Override
public Iterator<Entry> iterator() {
return new EntryIterator();
}
};
}
@Override
public Object clone() {
IntIntMap result;
try {
result = (IntIntMap) super.clone();
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
result.table = table.clone();
return result;
}
/**
* Shifts entries with the same hash.
*/
private void shiftKeys(final int index) {
int last;
int pos = index;
while (true) {
last = pos;
do {
pos = (pos + 1) & mask;
if (table[pos] == EMPTY_CELL) {
table[last] = EMPTY_CELL;
return;
}
int key = (int) (table[pos] & KEY_MASK);
int keyStartIndex = getStartIndex(key);
if (last < pos) { // did we wrap around?
/*
* (no) if the previous position is after the chain startIndex for key, *or* the
* chain startIndex of the key is after the position we're checking, then the
* position we're checking now cannot be a part of the current chain
*/
if (last >= keyStartIndex || keyStartIndex > pos) {
break;
}
} else {
/*
* (yes) if the previous position is after the chain startIndex for key, *and*
* the chain startIndex of key is after the position we're checking, then the
* position we're checking now cannot be a part of the current chain
*/
if (last >= keyStartIndex && keyStartIndex > pos) {
break;
}
}
} while (true);
table[last] = table[pos];
}
}
private void rehash(final int newCapacity) {
threshold = (int) (newCapacity * loadFactor);
mask = newCapacity - 1;
final int oldCapacity = table.length;
final long[] oldTable = table;
table = makeTable(newCapacity);
size = 0;
for (int i = oldCapacity - 1; i >= 0; i--) {
if (oldTable[i] != EMPTY_CELL) {
final int oldKey = (int) (oldTable[i] & KEY_MASK);
final int oldValue = (int) (oldTable[i] >> 32);
put(oldKey, oldValue);
}
}
}
private static long[] makeTable(final int capacity) {
long[] result = new long[capacity];
Arrays.fill(result, EMPTY_CELL);
return result;
}
private int getStartIndex(final int key) {
return phiMix(key) & mask;
}
private int getNextIndex(final int currentIndex) {
return (currentIndex + 1) & mask;
}
/**
* Computes hashcode for {@code val}.
*
* @param val
* @return the hashcode for {@code val}
*/
private static int phiMix(final int val) {
final int h = val * INT_PHI;
return h ^ (h >> 16);
}
static class Entry {
private final int key;
private final int value;
private Entry(final int key, final int value) {
this.key = key;
this.value = value;
}
public int getKey() {
return key;
}
public int getValue() {
return value;
}
}
private class EntryIterator implements Iterator<Entry> {
private static final int NO_NEXT_INDEX = -1;
private int nextIndex = findNextIndex(0);
@Override
public boolean hasNext() {
return nextIndex != NO_NEXT_INDEX;
}
@Override
public Entry next() {
if (nextIndex == NO_NEXT_INDEX) {
throw new NoSuchElementException();
}
Entry entry = new Entry((int) (table[nextIndex] & KEY_MASK), (int) (table[nextIndex] >> 32));
nextIndex = findNextIndex(nextIndex + 1);
return entry;
}
private int findNextIndex(int fromIndex) {
while (fromIndex < table.length) {
if (table[fromIndex] != EMPTY_CELL) {
return fromIndex;
}
fromIndex++;
}
return NO_NEXT_INDEX;
}
}
}
| 4,897 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/SingleStateNameMatcher.java | package software.amazon.event.ruler;
import javax.annotation.Nonnull;
/**
* Implements the { [ "exists" : false] } pattern by performing a binary search
* of the key in the event keys.
*/
public class SingleStateNameMatcher implements NameMatcher<NameState> {
/**
* We only have one pattern for name matcher today. Hence, we can just keep
* a single state here for simplicity. In the future, when multiple patterns
* come here, we need a byte match.
*/
private NameState nameState;
@Override
public boolean isEmpty() {
return nameState == null;
}
@Override
public NameState addPattern(@Nonnull final Patterns pattern, final NameState nameState) {
if (this.nameState == null) {
this.nameState = nameState;
}
return this.nameState;
}
@Override
public void deletePattern(@Nonnull final Patterns pattern) {
nameState = null;
}
@Override
public NameState findPattern(@Nonnull final Patterns pattern) {
return nameState;
}
@Override
public NameState getNextState() {
return nameState;
}
} | 4,898 |
0 | Create_ds/event-ruler/src/main/software/amazon/event | Create_ds/event-ruler/src/main/software/amazon/event/ruler/NameMatcher.java | package software.amazon.event.ruler;
import javax.annotation.Nonnull;
/**
* Matches the Keys in the flattened event with the { [ "exists" : false ] } pattern.
* and returns the next state if the <b>key does not exist</b> in the event.
*
* In the future, when we support multiple patterns, the matcher will return a set of
* name states matched instead of a single name state.
*
* @param <R> generic state type
*/
public interface NameMatcher<R> {
/**
* Returns {@code true} if this name matcher contains no patterns.
*/
boolean isEmpty();
/**
* Adds the given pattern to this name matcher and associate it with the existing or new match result.
*
* @param pattern the pattern to be added
* @param nameState the namestate
* @return the match result with which the added pattern is associated
*/
R addPattern(@Nonnull Patterns pattern, @Nonnull NameState nameState);
/**
* Removes the given pattern from this name matcher.
*
* @param pattern the pattern to be deleted
*/
void deletePattern(@Nonnull Patterns pattern);
/**
* Looks up for the given pattern.
*
* @param pattern the pattern to be looked up for
* @return the match result that is associated with the given pattern if the pattern exists; otherwise {@code null}
*/
R findPattern(@Nonnull Patterns pattern);
/**
* Gets the next state to transition to in case the NameMatcher matches the event.
*/
R getNextState();
}
| 4,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.