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/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/Ruler.java
package software.amazon.event.ruler; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Locale; import java.util.Map; import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.ThreadSafe; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * The core idea of Ruler is to match rules to events at a rate that's independent of the number of rules. This is * achieved by compiling the rules into an automaton, at some up-front cost for compilation and memory use. There * are some users who are unable to persist the compiled automaton but still like the "Event Pattern" idiom and want * to match events with those semantics. * The memory cost is proportional to the product of the number of possible values provided in the rule and can * grow surprisingly large * This class matches a single rule to a single event without any precompilation, using brute-force techniques, but * with no up-front compute or memory cost. */ @ThreadSafe @Immutable public class Ruler { private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private Ruler() { } /** * Return true if an event matches the provided rule. This is a thin wrapper around * rule machine and `rulesForJSONEvent` method. * * @param event The event, in JSON form * @param rule The rule, in JSON form * @return true or false depending on whether the rule matches the event */ public static boolean matchesRule(final String event, final String rule) throws Exception { Machine machine = new Machine(); machine.addRule("rule", rule); return !machine.rulesForJSONEvent(event).isEmpty(); } /** * Return true if an event matches the provided rule. * <p> * This method is deprecated. You should use `Ruler.match` instead in all but one cases: * this method will return false for ` {"detail" : { "state": { "state": "running" } } }` with * `{ "detail" : { "state.state": "running" } }` while `Ruler.matchesRule(...)` will return true. When this gap * has been addressed, we will remove this method as it doesn't handle many of the new matchers * and is not able to perform array consistency checks like rest of Ruler. This method also is * slower. * * @param event The event, in JSON form * @param rule The rule, in JSON form * @return true or false depending on whether the rule matches the event */ @Deprecated public static boolean matches(final String event, final String rule) throws IOException { final JsonNode eventRoot = OBJECT_MAPPER.readTree(event); final Map<List<String>, List<Patterns>> ruleMap = RuleCompiler.ListBasedRuleCompiler.flattenRule(rule); return matchesAllFields(eventRoot, ruleMap); } private static boolean matchesAllFields(final JsonNode event, final Map<List<String>, List<Patterns>> rule) { for (Map.Entry<List<String>, List<Patterns>> entry : rule.entrySet()) { final JsonNode fieldValue = tryToRetrievePath(event, entry.getKey()); if (!matchesOneOf(fieldValue, entry.getValue())) { return false; } } return true; } // TODO: Improve unit-test coverage private static boolean matchesOneOf(final JsonNode val, final List<Patterns> patterns) { for (Patterns pattern : patterns) { if (val == null) { // a non existent value matches the absent pattern, if (pattern.type() == MatchType.ABSENT) { return true; } } else if (val.isArray()) { for (final JsonNode element : val) { if (matches(element, pattern)) { return true; } } } else { if (matches(val, pattern)) { return true; } } } return false; } private static boolean matches(final JsonNode val, final Patterns pattern) { switch (pattern.type()) { case EXACT: ValuePatterns valuePattern = (ValuePatterns) pattern; // if it's a string we match the "-quoted form, otherwise (true, false, null) as-is. final String compareTo = (val.isTextual()) ? '"' + val.asText() + '"' : val.asText(); return compareTo.equals(valuePattern.pattern()); case PREFIX: valuePattern = (ValuePatterns) pattern; return val.isTextual() && ('"' + val.asText()).startsWith(valuePattern.pattern()); case PREFIX_EQUALS_IGNORE_CASE: valuePattern = (ValuePatterns) pattern; return val.isTextual() && ('"' + val.asText().toLowerCase(Locale.ROOT)) .startsWith(valuePattern.pattern().toLowerCase(Locale.ROOT)); case SUFFIX: valuePattern = (ValuePatterns) pattern; // Undoes the reverse on the pattern value to match against the provided value return val.isTextual() && (val.asText() + '"') .endsWith(new StringBuilder(valuePattern.pattern()).reverse().toString()); case SUFFIX_EQUALS_IGNORE_CASE: valuePattern = (ValuePatterns) pattern; // Undoes the reverse on the pattern value to match against the provided value return val.isTextual() && (val.asText().toLowerCase(Locale.ROOT) + '"') .endsWith(new StringBuilder(valuePattern.pattern().toLowerCase(Locale.ROOT)).reverse().toString()); case ANYTHING_BUT: assert (pattern instanceof AnythingBut); AnythingBut anythingButPattern = (AnythingBut) pattern; if (val.isTextual()) { return anythingButPattern.getValues().stream().noneMatch(v -> v.equals('"' + val.asText() + '"')); } else if (val.isNumber()) { return anythingButPattern.getValues().stream() .noneMatch(v -> v.equals(ComparableNumber.generate(val.asDouble()))); } return false; case ANYTHING_BUT_IGNORE_CASE: assert (pattern instanceof AnythingButEqualsIgnoreCase); AnythingButEqualsIgnoreCase anythingButIgnoreCasePattern = (AnythingButEqualsIgnoreCase) pattern; if (val.isTextual()) { return anythingButIgnoreCasePattern.getValues().stream().noneMatch(v -> v.equalsIgnoreCase('"' + val.asText() + '"')); } return false; case ANYTHING_BUT_SUFFIX: valuePattern = (ValuePatterns) pattern; return !(val.isTextual() && (val.asText() + '"').startsWith(valuePattern.pattern())); case ANYTHING_BUT_PREFIX: valuePattern = (ValuePatterns) pattern; return !(val.isTextual() && ('"' + val.asText()).startsWith(valuePattern.pattern())); case NUMERIC_EQ: valuePattern = (ValuePatterns) pattern; return val.isNumber() && ComparableNumber.generate(val.asDouble()).equals(valuePattern.pattern()); case EXISTS: return true; case ABSENT: return false; case NUMERIC_RANGE: final Range nr = (Range) pattern; byte[] bytes; if (nr.isCIDR) { if (!val.isTextual()) { return false; } try { bytes = CIDR.ipToString(val.asText()).getBytes(StandardCharsets.UTF_8); } catch (Exception e) { return false; } } else { if (!val.isNumber()) { return false; } bytes = ComparableNumber.generate(val.asDouble()).getBytes(StandardCharsets.UTF_8); } final int comparedToBottom = compare(bytes, nr.bottom); if ((comparedToBottom > 0) || (comparedToBottom == 0 && !nr.openBottom)) { final int comparedToTop = compare(bytes, nr.top); return comparedToTop < 0 || (comparedToTop == 0 && !nr.openTop); } return false; case EQUALS_IGNORE_CASE: valuePattern = (ValuePatterns) pattern; return val.isTextual() && ('"' + val.asText() + '"').equalsIgnoreCase(valuePattern.pattern()); case WILDCARD: valuePattern = (ValuePatterns) pattern; return val.isTextual() && ('"' + val.asText() + '"').matches(valuePattern.pattern().replaceAll("\\*", ".*")); default: throw new RuntimeException("Unsupported Pattern type " + pattern.type()); } } static JsonNode tryToRetrievePath(JsonNode node, final List<String> path) { for (final String step : path) { if ((node == null) || !node.isObject()) { return null; } node = node.get(step); } return node; } static int compare(final byte[] a, final byte[] b) { assert(a.length == b.length); for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return a[i] - b[i]; } } return 0; } }
4,900
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/ACTask.java
package software.amazon.event.ruler; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Queue; import java.util.Set; import static software.amazon.event.ruler.SetOperations.intersection; /** * Represents the state of an Array-Consistent rule-finding project. */ class ACTask { // the event we're matching rules to, and its fieldcount public final Event event; final int fieldCount; // the rules that matched the event, if we find any private final Set<Object> matchingRules = new HashSet<>(); // Steps queued up for processing private final Queue<ACStep> stepQueue = new ArrayDeque<>(); // the state machine private final GenericMachine<?> machine; ACTask(Event event, GenericMachine<?> machine) { this.event = event; this.machine = machine; fieldCount = event.fields.size(); } NameState startState() { return machine.getStartState(); } ACStep nextStep() { return stepQueue.remove(); } /* * Add a step to the queue for later consideration */ void addStep(final int fieldIndex, final NameState nameState, final Set<Double> candidateSubRuleIds, final ArrayMembership membershipSoFar) { stepQueue.add(new ACStep(fieldIndex, nameState, candidateSubRuleIds, membershipSoFar)); } boolean stepsRemain() { return !stepQueue.isEmpty(); } List<Object> getMatchedRules() { return new ArrayList<>(matchingRules); } void collectRules(final Set<Double> candidateSubRuleIds, final NameState nameState, final Patterns pattern) { Set<Double> terminalSubRuleIds = nameState.getTerminalSubRuleIdsForPattern(pattern); if (terminalSubRuleIds == null) { return; } // If no candidates, that means we're on the first step, so all sub-rules are candidates. if (candidateSubRuleIds == null || candidateSubRuleIds.isEmpty()) { for (Double terminalSubRuleId : terminalSubRuleIds) { matchingRules.add(nameState.getRule(terminalSubRuleId)); } } else { intersection(candidateSubRuleIds, terminalSubRuleIds, matchingRules, id -> nameState.getRule(id)); } } }
4,901
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/NameState.java
package software.amazon.event.ruler; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.concurrent.ThreadSafe; /** * Represents a state in the machine. * * The "valueTransitions" map is keyed by field name and yields a ByteMachine * that is used to match values. * * The "keyTransitions" map is keyed by field name and yields a NameMatcher * that is used to match keys for [ { exists: false } ]. */ @ThreadSafe class NameState { // the key is field name. the value is a value matcher which returns. These have to be // concurrent so they can be accessed while add/delete Rule is active in another thread, // without any locks. private final Map<String, ByteMachine> valueTransitions = new ConcurrentHashMap<>(); // the key is field name. the value is a name matcher which contains the next state after matching // an [ { exists: false } ]. These have to be concurrent so they can be accessed // while add/delete Rule is active in another thread, without any locks. private final Map<String, NameMatcher<NameState>> mustNotExistMatchers = new ConcurrentHashMap<>(1); // All rules, both terminal and non-terminal, keyed by pattern, that led to this NameState. private final Map<Patterns, Set<Object>> patternToRules = new ConcurrentHashMap<>(); // All terminal sub-rule IDs, keyed by pattern, that led to this NameState. private final Map<Patterns, Set<Double>> patternToTerminalSubRuleIds = new ConcurrentHashMap<>(); // All non-terminal sub-rule IDs, keyed by pattern, that led to this NameState. private final Map<Patterns, Set<Double>> patternToNonTerminalSubRuleIds = new ConcurrentHashMap<>(); // All sub-rule IDs mapped to the associated rule (name). private final Map<Double, Object> subRuleIdToRule = new ConcurrentHashMap<>(); // All sub-rule IDs mapped to the number of times that sub-rule has been added to this NameState. private final Map<Double, Integer> subRuleIdToCount = new ConcurrentHashMap<>(); ByteMachine getTransitionOn(final String token) { return valueTransitions.get(token); } /** * Get all the terminal patterns that have led to this NameState. "Terminal" means the pattern was used by the last * field of a rule to lead to this NameState, and thus, the rule's matching criteria have been fully satisfied. * * NOTE: This function returns the raw key set from one of NameState's internal maps. Mutating it will corrupt the * state of NameState. Although standard coding practice would warrant returning a copy of the set, or wrapping it * to be immutable, we instead return the raw key set as a performance optimization. This avoids creating new data * structures and/or copying elements between them. * * @return Set of all terminal patterns. */ Set<Patterns> getTerminalPatterns() { return patternToTerminalSubRuleIds.keySet(); } /** * Get all the non-terminal patterns that have led to this NameState. "Terminal" means the pattern was used by the * last field of a rule to lead to this NameState, and thus, the rule's matching criteria have been fully satisfied. * * NOTE: This function returns the raw key set from one of NameState's internal maps. Mutating it will corrupt the * state of NameState. Although standard coding practice would warrant returning a copy of the set, or wrapping it * to be immutable, we instead return the raw key set as a performance optimization. This avoids creating new data * structures and/or copying elements between them. * * @return Set of all non-terminal patterns. */ Set<Patterns> getNonTerminalPatterns() { return patternToNonTerminalSubRuleIds.keySet(); } /** * Get all the terminal sub-rule IDs that used a given pattern to lead to this NameState. "Terminal" means the last * field of the sub-rule led to this NameState, and thus, the sub-rule's matching criteria have been satisfied. * * NOTE: This function returns the raw key set from one of NameState's internal maps. Mutating it will corrupt the * state of NameState. Although standard coding practice would warrant returning a copy of the set, or wrapping it * to be immutable, we instead return the raw key set as a performance optimization since this is called repeatedly * on the critical matching path. This avoids creating new data structures and/or copying elements between them. * * @param pattern The pattern that the rules must use to get to this NameState. * @return The sub-rules, could be null if none for pattern. */ Set<Double> getTerminalSubRuleIdsForPattern(Patterns pattern) { return patternToTerminalSubRuleIds.get(pattern); } /** * Get all the non-terminal sub-rule IDs that used a given pattern to lead to this NameState. * * NOTE: This function returns the raw key set from one of NameState's internal maps. Mutating it will corrupt the * state of NameState. Although standard coding practice would warrant returning a copy of the set, or wrapping it * to be immutable, we instead return the raw key set as a performance optimization since this is called repeatedly * on the critical matching path. This avoids creating new data structures and/or copying elements between them. * * @param pattern The pattern that the rules must use to get to this NameState. * @return The sub-rule IDs, could be null if none for pattern. */ Set<Double> getNonTerminalSubRuleIdsForPattern(Patterns pattern) { return patternToNonTerminalSubRuleIds.get(pattern); } /** * Delete a sub-rule to indicate that it no longer transitions to this NameState using the provided pattern. * * @param subRuleId The ID of the sub-rule. * @param pattern The pattern used by the sub-rule to transition to this NameState. * @param isTerminal True indicates that the sub-rule is using pattern to match on the final event field. * @return True if and only if the sub-rule was found and deleted. */ boolean deleteSubRule(final double subRuleId, final Patterns pattern, final boolean isTerminal) { deleteFromPatternToSetMap(patternToRules, pattern, subRuleIdToRule.get(subRuleId)); Map<Patterns, ?> patternToSubRules = isTerminal ? patternToTerminalSubRuleIds : patternToNonTerminalSubRuleIds; boolean deleted = deleteFromPatternToSetMap(patternToSubRules, pattern, subRuleId); if (deleted) { Integer count = subRuleIdToCount.get(subRuleId); if (count == 1) { subRuleIdToCount.remove(subRuleId); subRuleIdToRule.remove(subRuleId); } else { subRuleIdToCount.put(subRuleId, count - 1); } } return deleted; } private static boolean deleteFromPatternToSetMap(final Map<Patterns, ?> map, final Patterns pattern, final Object setElement) { boolean deleted = false; Set<?> set = (Set<?>) map.get(pattern); if (set != null) { deleted = set.remove(setElement); if (set.isEmpty()) { map.remove(pattern); } } return deleted; } void removeTransition(String name) { valueTransitions.remove(name); } void removeKeyTransition(String name) { mustNotExistMatchers.remove(name); } boolean isEmpty() { return valueTransitions.isEmpty() && mustNotExistMatchers.isEmpty() && patternToRules.isEmpty() && patternToTerminalSubRuleIds.isEmpty() && patternToNonTerminalSubRuleIds.isEmpty() && subRuleIdToRule.isEmpty() && subRuleIdToCount.isEmpty(); } /** * Add a sub-rule to indicate that it transitions to this NameState using the provided pattern. * * @param rule The rule, which may have multiple sub-rules. * @param subRuleId The ID of the sub-rule. * @param pattern The pattern used by the sub-rule to transition to this NameState. * @param isTerminal True indicates that the sub-rule is using pattern to match on the final event field. */ void addSubRule(final Object rule, final double subRuleId, final Patterns pattern, final boolean isTerminal) { addToPatternToSetMap(patternToRules, pattern, rule); Map<Patterns, ?> patternToSubRules = isTerminal ? patternToTerminalSubRuleIds : patternToNonTerminalSubRuleIds; if (addToPatternToSetMap(patternToSubRules, pattern, subRuleId)) { Integer count = subRuleIdToCount.get(subRuleId); subRuleIdToCount.put(subRuleId, count == null ? 1 : count + 1); if (count == null) { subRuleIdToRule.put(subRuleId, rule); } } } private static boolean addToPatternToSetMap(final Map<Patterns, ?> map, final Patterns pattern, final Object setElement) { if (!map.containsKey(pattern)) { ((Map<Patterns, Set>) map).put(pattern, new HashSet<>()); } return ((Set) map.get(pattern)).add(setElement); } Object getRule(Double subRuleId) { return subRuleIdToRule.get(subRuleId); } /** * Determines whether this NameState contains the provided rule accessible via the provided pattern. * * @param rule The rule, which may have multiple sub-rules. * @param pattern The pattern used by the rule to transition to this NameState. * @return True indicates that this NameState the provided rule for the provided pattern. */ boolean containsRule(final Object rule, final Patterns pattern) { Set<Object> rules = patternToRules.get(pattern); return rules != null && rules.contains(rule); } void addTransition(final String key, final ByteMachine to) { valueTransitions.put(key, to); } void addKeyTransition(final String key, final NameMatcher<NameState> to) { mustNotExistMatchers.put(key, to); } NameMatcher<NameState> getKeyTransitionOn(final String token) { return mustNotExistMatchers.get(token); } boolean hasKeyTransitions() { return !mustNotExistMatchers.isEmpty(); } Set<NameState> getNameTransitions(final String[] event) { Set<NameState> nextNameStates = new HashSet<>(); if (mustNotExistMatchers.isEmpty()) { return nextNameStates; } Set<NameMatcher<NameState>> absentValues = new HashSet<>(mustNotExistMatchers.values()); for (int i = 0; i < event.length; i += 2) { NameMatcher<NameState> matcher = mustNotExistMatchers.get(event[i]); if (matcher != null) { absentValues.remove(matcher); if (absentValues.isEmpty()) { break; } } } for (NameMatcher<NameState> nameMatcher: absentValues) { nextNameStates.add(nameMatcher.getNextState()); } return nextNameStates; } Set<NameState> getNameTransitions(final Event event, final ArrayMembership membership) { final Set<NameState> nextNameStates = new HashSet<>(); if (mustNotExistMatchers.isEmpty()) { return nextNameStates; } Set<NameMatcher<NameState>> absentValues = new HashSet<>(mustNotExistMatchers.values()); for (Field field : event.fields) { NameMatcher<NameState> matcher = mustNotExistMatchers.get(field.name); if (matcher != null) { // we should only consider the field who doesn't violate array consistency. // normally, we should first check array consistency of field, then check mustNotExistMatchers, but // for performance optimization, we first check mustNotExistMatchers because the hashmap.get is cheaper // than AC check. if (ArrayMembership.checkArrayConsistency(membership, field.arrayMembership) != null) { absentValues.remove(matcher); if (absentValues.isEmpty()) { break; } } } } for (NameMatcher<NameState> nameMatcher: absentValues) { nextNameStates.add(nameMatcher.getNextState()); } return nextNameStates; } public int evaluateComplexity(MachineComplexityEvaluator evaluator) { int maxComplexity = evaluator.getMaxComplexity(); int complexity = 0; for (ByteMachine byteMachine : valueTransitions.values()) { complexity = Math.max(complexity, byteMachine.evaluateComplexity(evaluator)); if (complexity >= maxComplexity) { return maxComplexity; } } return complexity; } public void gatherObjects(Set<Object> objectSet, int maxObjectCount) { if (!objectSet.contains(this) && objectSet.size() < maxObjectCount) { // stops looping objectSet.add(this); for (ByteMachine byteMachine : valueTransitions.values()) { byteMachine.gatherObjects(objectSet, maxObjectCount); } for (Map.Entry<String, NameMatcher<NameState>> mustNotExistEntry : mustNotExistMatchers.entrySet()) { mustNotExistEntry.getValue().getNextState().gatherObjects(objectSet, maxObjectCount); } for (Map.Entry<Patterns, Set<Double>> entry : patternToTerminalSubRuleIds.entrySet()) { objectSet.add(entry.getKey()); objectSet.addAll(entry.getValue()); } for (Map.Entry<Patterns, Set<Double>> entry : patternToNonTerminalSubRuleIds.entrySet()) { objectSet.add(entry.getKey()); objectSet.addAll(entry.getValue()); } } } @Override public String toString() { return "NameState{" + "valueTransitions=" + valueTransitions + ", mustNotExistMatchers=" + mustNotExistMatchers + ", patternToRules=" + patternToRules + ", patternToTerminalSubRuleIds=" + patternToTerminalSubRuleIds + ", patternToNonTerminalSubRuleIds=" + patternToNonTerminalSubRuleIds + ", subRuleIdToRule=" + subRuleIdToRule + ", subRuleIdToCount=" + subRuleIdToCount + '}'; } }
4,902
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/Event.java
package software.amazon.event.ruler; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.ThreadSafe; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.StringJoiner; import java.util.TreeMap; /** * Prepares events for Ruler rule matching. * * There are three different implementations of code that have a similar goal: Prepare an Event, provided as JSON, * for processing by Ruler. * * There is the flatten() entry point, which generates a list of strings that alternately represent the fields * and values in an event, i.e. s[0] = name of first field, s[1] is value of that field, s[2] is name of 2nd field, * and so on. They are sorted in order of field name. Its chief tools are the flattenObject and FlattenArray methods. * This method cannot support array-consistent matching and is called only from the now-deprecated * rulesForEvent(String json) method. * * There are two Event constructors, both called from the rulesForJSONEvent method in GenericMachine. * Both generates a list of Field objects sorted by field name and equipped for matching with * array consistency * * One takes a parsed version of the JSON event, presumably constructed by ObjectMapper. Its chief tools are the * loadObject and loadArray methods. * * The constructor which takes a JSON string as argument uses the JsonParser's nextToken() method to traverse the * structure without parsing it into a tree, and is thus several times faster. Its chief tools are the * traverseObject and traverseArray methods. */ // TODO: Improve unit-test coverage, there are surprising gaps @Immutable @ThreadSafe class Event { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final JsonFactory JSON_FACTORY = new JsonFactory(); // the fields of the event final List<Field> fields = new ArrayList<>(); /** * represents the current state of an Event-constructor project */ static class Progress { final ArrayMembership membership = new ArrayMembership(); int arrayCount = 0; final Path path = new Path(); // final Stack<String> path = new Stack<>(); final GenericMachine<?> machine; Progress(final GenericMachine<?> m) { machine = m; } } /** * represents a field value during Event construction */ static class Value { final String val; final ArrayMembership membership; Value(String val, ArrayMembership membership) { this.val = val; this.membership = new ArrayMembership(membership); // clones the argument } } /** * Generates an Event with a structure that supports checking for consistent array membership. * * @param json JSON representation of the event * @throws IOException if the JSON can't be parsed * @throws IllegalArgumentException if the top level of the Event is not a JSON object */ Event(@Nonnull final String json, @Nonnull final GenericMachine<?> machine) throws IOException, IllegalArgumentException { final JsonParser parser = JSON_FACTORY.createParser(json); final Progress progress = new Progress(machine); final TreeMap<String, List<Value>> fieldMap = new TreeMap<>(); if (parser.nextToken() != JsonToken.START_OBJECT) { throw new IllegalArgumentException("Event must be a JSON object"); } traverseObject(parser, fieldMap, progress); parser.close(); for (Map.Entry<String, List<Value>> entry : fieldMap.entrySet()) { for (Value val : entry.getValue()) { fields.add(new Field(entry.getKey(), val.val, val.membership)); } } } // as above, only with the JSON already parsed into a ObjectMapper tree Event(@Nonnull final JsonNode eventRoot, @Nonnull final GenericMachine<?> machine) throws IllegalArgumentException { if (!eventRoot.isObject()) { throw new IllegalArgumentException("Event must be a JSON object"); } final TreeMap<String, List<Value>> fieldMap = new TreeMap<>(); final Progress progress = new Progress(machine); loadObject(eventRoot, fieldMap, progress); for (Map.Entry<String, List<Value>> entry : fieldMap.entrySet()) { for (Value val : entry.getValue()) { fields.add(new Field(entry.getKey(), val.val, val.membership)); } } } private void traverseObject(final JsonParser parser, final TreeMap<String, List<Value>> fieldMap, final Progress progress) throws IOException { while (parser.nextToken() != JsonToken.END_OBJECT) { // step name final String stepName = parser.getCurrentName(); JsonToken nextToken = parser.nextToken(); // If we know current step name hasn't been used by any rules, we don't parse into this step. if (!progress.machine.isFieldStepUsed(stepName)) { ignoreCurrentStep(parser); continue; } progress.path.push(stepName); switch (nextToken) { case START_OBJECT: traverseObject(parser, fieldMap, progress); break; case START_ARRAY: traverseArray(parser, fieldMap, progress); break; case VALUE_STRING: addField(fieldMap, progress, '"' + parser.getText() + '"'); break; default: addField(fieldMap, progress, parser.getText()); break; } progress.path.pop(); } } private void traverseArray(final JsonParser parser, final TreeMap<String, List<Value>> fieldMap, final Progress progress) throws IOException { final int arrayID = progress.arrayCount++; JsonToken token; int arrayIndex = 0; while ((token = parser.nextToken()) != JsonToken.END_ARRAY) { switch (token) { case START_OBJECT: progress.membership.putMembership(arrayID, arrayIndex); traverseObject(parser, fieldMap, progress); progress.membership.deleteMembership(arrayID); break; case START_ARRAY: progress.membership.putMembership(arrayID, arrayIndex); traverseArray(parser, fieldMap, progress); progress.membership.deleteMembership(arrayID); break; case VALUE_STRING: addField(fieldMap, progress, '"' + parser.getText() + '"'); break; default: addField(fieldMap, progress, parser.getText()); break; } arrayIndex++; } } /** * Flattens a json String for matching rules in the state machine. * @param json the json string * @return flattened json event */ static List<String> flatten(@Nonnull final String json) throws IllegalArgumentException { try { final JsonNode eventRoot = OBJECT_MAPPER.readTree(json); return doFlatten(eventRoot); } catch (Throwable e) { // should be IOException, but the @Nonnull annotation doesn't work in some scenarios // catch all throwable exceptions throw new IllegalArgumentException(e); } } /** * Flattens a parsed json for matching rules in the state machine. * @param eventRoot root node for the parsed json * @return flattened json event */ static List<String> flatten(@Nonnull final JsonNode eventRoot) throws IllegalArgumentException { try { return doFlatten(eventRoot); } catch (Throwable e) { // should be IOException, but the @Nonnull annotation doesn't work in some scenarios // catch all throwable exceptions throw new IllegalArgumentException(e); } } private static List<String> doFlatten(final JsonNode eventRoot) throws IllegalArgumentException { final TreeMap<String, List<String>> fields = new TreeMap<>(); if (!eventRoot.isObject()) { throw new IllegalArgumentException("Event must be a JSON object"); } final Stack<String> path = new Stack<>(); flattenObject(eventRoot, fields, path); // Ruler algorithm will explore all possible matches based on field (key value pair) in event, duplicated fields // in event do NOT impact final matches but it will downgrade the performance by producing duplicated // checking Steps, in worse case, those the duplicated steps can stuck the process and use up all memory, so when // building the event, dedupe the fields from event can low such risk. final Set<String> uniqueValues = new HashSet<>(); final List<String> nameVals = new ArrayList<>(); for (Map.Entry<String, List<String>> entry : fields.entrySet()) { String k = entry.getKey(); List<String> vs = entry.getValue(); if(vs.size() != 1) { uniqueValues.clear(); for (String v : vs) { if (uniqueValues.add(v)) { nameVals.add(k); nameVals.add(v); } } } else { nameVals.add(k); nameVals.add(vs.get(0)); } } return nameVals; } private void loadObject(final JsonNode object, final Map<String, List<Value>> fieldMap, final Progress progress) { final Iterator<Map.Entry<String, JsonNode>> fields = object.fields(); while (fields.hasNext()) { final Map.Entry<String, JsonNode> field = fields.next(); final JsonNode val = field.getValue(); // If we know current step name hasn't been used by any rules, we don't parse into this step. if (!progress.machine.isFieldStepUsed(field.getKey())) { continue; } progress.path.push(field.getKey()); switch (val.getNodeType()) { case OBJECT: loadObject(val, fieldMap, progress); break; case ARRAY: loadArray(val, fieldMap, progress); break; case STRING: addField(fieldMap, progress, '"' + val.asText() + '"'); break; case NULL: case BOOLEAN: case NUMBER: addField(fieldMap, progress, val.asText()); break; default: throw new RuntimeException("Unknown JsonNode type for: " + val.asText()); } progress.path.pop(); } } private static void flattenObject(final JsonNode object, final Map<String, List<String>> map, final Stack<String> path) { final Iterator<Map.Entry<String, JsonNode>> fields = object.fields(); while (fields.hasNext()) { final Map.Entry<String, JsonNode> field = fields.next(); final JsonNode val = field.getValue(); path.push(field.getKey()); switch (val.getNodeType()) { case OBJECT: flattenObject(val, map, path); break; case ARRAY: flattenArray(val, map, path); break; case STRING: recordNameVal(map, path, '"' + val.asText() + '"'); break; case NULL: case BOOLEAN: case NUMBER: recordNameVal(map, path, val.asText()); break; default: throw new RuntimeException("Unknown JsonNode type for: " + val.asText()); } path.pop(); } } private void loadArray(final JsonNode array, final Map<String, List<Value>> fieldMap, final Progress progress) { final int arrayID = progress.arrayCount++; final Iterator<JsonNode> elements = array.elements(); int arrayIndex = 0; while (elements.hasNext()) { final JsonNode element = elements.next(); switch (element.getNodeType()) { case OBJECT: progress.membership.putMembership(arrayID, arrayIndex); loadObject(element, fieldMap, progress); progress.membership.deleteMembership(arrayID); break; case ARRAY: progress.membership.putMembership(arrayID, arrayIndex); loadArray(element, fieldMap, progress); progress.membership.deleteMembership(arrayID); break; case STRING: addField(fieldMap, progress, '"' + element.asText() + '"'); break; case NULL: case BOOLEAN: case NUMBER: addField(fieldMap, progress, element.asText()); break; default: throw new RuntimeException("Unknown JsonNode type for: " + element.asText()); } arrayIndex++; } } private static void flattenArray(final JsonNode array, final Map<String, List<String>> map, final Stack<String> path) { final Iterator<JsonNode> elements = array.elements(); while (elements.hasNext()) { final JsonNode element = elements.next(); switch (element.getNodeType()) { case OBJECT: flattenObject(element, map, path); break; case ARRAY: flattenArray(element, map, path); break; case STRING: recordNameVal(map, path, '"' + element.asText() + '"'); break; case NULL: case BOOLEAN: case NUMBER: recordNameVal(map, path, element.asText()); break; default: throw new RuntimeException("Unknown JsonNode type for: " + element.asText()); } } } private void addField(final Map<String, List<Value>> fieldMap, final Progress progress, final String val) { final String key = progress.path.name(); final List<Value> vals = fieldMap.computeIfAbsent(key, k -> new ArrayList<>()); vals.add(new Value(val, progress.membership)); } static void recordNameVal(final Map<String, List<String>> map, final Stack<String> path, final String val) { final String key = pathName(path); List<String> vals = map.computeIfAbsent(key, k -> new ArrayList<>()); vals.add(val); } static String pathName(final Stack<String> path) { final StringJoiner joiner = new StringJoiner("."); for (String step : path) { joiner.add(step); } return joiner.toString(); } private void ignoreCurrentStep(JsonParser jsonParser) throws IOException { JsonToken token = jsonParser.getCurrentToken(); if (token == JsonToken.START_OBJECT) { advanceToClosingToken(jsonParser, JsonToken.START_OBJECT, JsonToken.END_OBJECT); } else if (token == JsonToken.START_ARRAY) { advanceToClosingToken(jsonParser, JsonToken.START_ARRAY, JsonToken.END_ARRAY); } } private void advanceToClosingToken(JsonParser jsonParser, JsonToken openingToken, JsonToken closingToken) throws IOException { int count = 1; do { JsonToken currentToken = jsonParser.nextToken(); if (currentToken == openingToken) { count++; } else if (currentToken == closingToken) { count--; } } while (count > 0); } }
4,903
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/ACFinder.java
package software.amazon.event.ruler; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import static software.amazon.event.ruler.SetOperations.intersection; /** * Matches rules to events as does Finder, but in an array-consistent fashion, thus the AC prefix on the class name. */ class ACFinder { private static final Patterns ABSENCE_PATTERN = Patterns.absencePatterns(); private ACFinder() { } /** * Return any rules that match the fields in the event, but enforce array consistency, i.e. reject * matches where different matches come from the different elements in the same array in the event. * * @param event the Event structure containing the flattened event information * @param machine the compiled state machine * @return list of rule names that match. The list may be empty but never null. */ static List<Object> matchRules(final Event event, final GenericMachine<?> machine) { return find(new ACTask(event, machine)); } private static List<Object> find(final ACTask task) { // bootstrap the machine: Start state, first field NameState startState = task.startState(); if (startState == null) { return Collections.emptyList(); } moveFrom(null, startState, 0, task, new ArrayMembership()); // each iteration removes a Step and adds zero or more new ones while (task.stepsRemain()) { tryStep(task); } return task.getMatchedRules(); } // remove a step from the work queue and see if there's a transition private static void tryStep(final ACTask task) { final ACStep step = task.nextStep(); final Field field = task.event.fields.get(step.fieldIndex); // if we can step from where we are to the new field without violating array consistency final ArrayMembership newMembership = ArrayMembership.checkArrayConsistency(step.membershipSoFar, field.arrayMembership); if (newMembership != null) { // if there are some possible value pattern matches for this key final ByteMachine valueMatcher = step.nameState.getTransitionOn(field.name); if (valueMatcher != null) { // loop through the value pattern matches, if any final int nextFieldIndex = step.fieldIndex + 1; for (NameStateWithPattern nextNameStateWithPattern : valueMatcher.transitionOn(field.val)) { // we have moved to a new NameState // this NameState might imply a rule match task.collectRules(step.candidateSubRuleIds, nextNameStateWithPattern.getNameState(), nextNameStateWithPattern.getPattern()); // set up for attempting to move on from the new state moveFromWithPriorCandidates(step.candidateSubRuleIds, nextNameStateWithPattern.getNameState(), nextNameStateWithPattern.getPattern(), nextFieldIndex, task, newMembership); } } } } private static void tryMustNotExistMatch(final Set<Double> candidateSubRuleIds, final NameState nameState, final ACTask task, int nextKeyIndex, final ArrayMembership arrayMembership) { if (!nameState.hasKeyTransitions()) { return; } for (NameState nextNameState : nameState.getNameTransitions(task.event, arrayMembership)) { if (nextNameState != null) { addNameState(candidateSubRuleIds, nextNameState, ABSENCE_PATTERN, task, nextKeyIndex, arrayMembership); } } } // Move from a state. Give all the remaining event fields a chance to transition from it. private static void moveFrom(final Set<Double> candidateSubRuleIdsForNextStep, final NameState nameState, int fieldIndex, final ACTask task, final ArrayMembership arrayMembership) { /* * The Name Matchers look for an [ { exists: false } ] match. They * will match if a particular key is not present * in the event. Hence, if the name state has any matches configured * for the [ { exists: false } ] case, we need to evaluate these * matches regardless. The fields in the event can be completely * disconnected from the fields configured for [ { exists: false } ], * and it does not matter if the current field is used in machine. * * Another possibility is that there can be a final state configured for * [ { exists: false } ] match. This state needs to be evaluated for a match * even if we have matched all the keys in the event. This is needed because * the final state can still be evaluated to true if the particular event * does not have the key configured for [ { exists: false } ]. */ tryMustNotExistMatch(candidateSubRuleIdsForNextStep, nameState, task, fieldIndex, arrayMembership); while (fieldIndex < task.fieldCount) { task.addStep(fieldIndex++, nameState, candidateSubRuleIdsForNextStep, arrayMembership); } } private static void moveFromWithPriorCandidates(final Set<Double> candidateSubRuleIds, final NameState fromState, final Patterns fromPattern, final int fieldIndex, final ACTask task, final ArrayMembership arrayMembership) { Set<Double> candidateSubRuleIdsForNextStep = calculateCandidateSubRuleIdsForNextStep(candidateSubRuleIds, fromState, fromPattern); // If there are no more candidate sub-rules, there is no need to proceed further. if (candidateSubRuleIdsForNextStep != null && !candidateSubRuleIdsForNextStep.isEmpty()) { moveFrom(candidateSubRuleIdsForNextStep, fromState, fieldIndex, task, arrayMembership); } } /** * Calculate the candidate sub-rule IDs for the next step. * * @param currentCandidateSubRuleIds The candidate sub-rule IDs for the current step. Use null to indicate that we * are on first step and so there are not yet any candidate sub-rules. * @param fromState The NameState we are transitioning from. * @param fromPattern The pattern we used to transition from fromState. * @return The set of candidate sub-rule IDs for the next step. Null means there are no candidates and thus, there * is no point to evaluating subsequent steps. */ private static Set<Double> calculateCandidateSubRuleIdsForNextStep(final Set<Double> currentCandidateSubRuleIds, final NameState fromState, final Patterns fromPattern) { // These are all the sub-rules that use the matched pattern to transition to the next NameState. Note that they // are not all candidates as they may have required different values for previously evaluated fields. Set<Double> subRuleIds = fromState.getNonTerminalSubRuleIdsForPattern(fromPattern); // If no sub-rules used the matched pattern to transition to the next NameState, then there are no matches to be // found by going further. if (subRuleIds == null) { return null; } // If there are no candidate sub-rules, this means we are on the first NameState and must initialize the // candidate sub-rules to those that used the matched pattern to transition to the next NameState. if (currentCandidateSubRuleIds == null || currentCandidateSubRuleIds.isEmpty()) { return subRuleIds; } // There are candidate sub-rules, so retain only those that used the matched pattern to transition to the next // NameState. Set<Double> candidateSubRuleIdsForNextStep = new HashSet<>(); intersection(subRuleIds, currentCandidateSubRuleIds, candidateSubRuleIdsForNextStep); return candidateSubRuleIdsForNextStep; } private static void addNameState(Set<Double> candidateSubRuleIds, NameState nameState, Patterns pattern, ACTask task, int nextKeyIndex, final ArrayMembership arrayMembership) { // one of the matches might imply a rule match task.collectRules(candidateSubRuleIds, nameState, pattern); moveFromWithPriorCandidates(candidateSubRuleIds, nameState, pattern, nextKeyIndex, task, arrayMembership); } }
4,904
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/CompositeByteTransition.java
package software.amazon.event.ruler; import javax.annotation.Nonnull; import java.util.Collections; import java.util.Set; /** * Represents a composite transition that has a next state and a match. */ final class CompositeByteTransition extends SingleByteTransition { /** * The state to transfer to. */ private volatile ByteState nextState; /** * The first match of a linked list of matches that are triggered if this transition is made. */ private volatile ByteMatch match; /** * Constructs a {@code CompositeByteTransition} instance with the given next state and the given match. * * @param nextState the next state * @param match the match */ CompositeByteTransition(@Nonnull ByteState nextState, @Nonnull ByteMatch match) { this.nextState = nextState; this.match = match; } @Override public ByteState getNextByteState() { return nextState; } @Override public SingleByteTransition setNextByteState(ByteState nextState) { if (nextState == null) { return match; } else { this.nextState = nextState; return this; } } @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 public SingleByteTransition setMatch(ByteMatch match) { if (match == null) { return nextState; } else { this.match = match; return this; } } @Override public Set<ShortcutTransition> getShortcuts() { return Collections.emptySet(); } @Override boolean hasIndeterminatePrefix() { return nextState == null ? false : nextState.hasIndeterminatePrefix(); } @Override boolean isMatchTrans() { return true; } }
4,905
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/RuleCompiler.java
package software.amazon.event.ruler; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import software.amazon.event.ruler.input.ParseException; import static software.amazon.event.ruler.input.DefaultParser.getParser; /** * Compiles Rules, expressed in JSON, for use in Ruler. * There are two flavors of compilation: * 1. Compile a JSON-based Rule into Map of String to List of Patterns which can be used in rulesForEvent, * and has a "check" variant that just checks rules for syntactic accuracy * 2. Starting in ListBasedRuleCompiler, does the same thing but expresses field names as List ofString * rather than "."-separated strings for use in the Ruler class, which does not use state machines and * needs to step into the event field by field. * * Is public so clients can call the check() method to syntax-check filters */ public final class RuleCompiler { private static final JsonFactory JSON_FACTORY = new JsonFactory(); private RuleCompiler() { throw new UnsupportedOperationException("You can't create instance of utility class."); } /** * Verify the syntax of a rule * @param source rule, as a Reader * @return null if the rule is valid, otherwise an error message */ public static String check(final Reader source) { try { doCompile(JSON_FACTORY.createParser(source)); return null; } catch (Exception e) { return e.getLocalizedMessage(); } } /** * Verify the syntax of a rule * @param source rule, as a String * @return null if the rule is valid, otherwise an error message */ public static String check(final String source) { try { doCompile(JSON_FACTORY.createParser(source)); return null; } catch (Exception e) { return e.getLocalizedMessage(); } } /** * Verify the syntax of a rule * @param source rule, as a byte array * @return null if the rule is valid, otherwise an error message */ public static String check(final byte[] source) { try { doCompile(JSON_FACTORY.createParser(source)); return null; } catch (Exception e) { return e.getLocalizedMessage(); } } /** * Verify the syntax of a rule * @param source rule, as an InputStream * @return null if the rule is valid, otherwise an error message */ public static String check(final InputStream source) { try { doCompile(JSON_FACTORY.createParser(source)); return null; } catch (Exception e) { return e.getLocalizedMessage(); } } /** * Compile a rule from its JSON form to a Map suitable for use by events.ruler.Ruler (elements are surrounded by quotes). * * @param source rule, as a Reader * @return Map form of rule * @throws IOException if the rule isn't syntactically valid */ public static Map<String, List<Patterns>> compile(final Reader source) throws IOException { return doCompile(JSON_FACTORY.createParser(source)); } /** * Compile a rule from its JSON form to a Map suitable for use by events.ruler.Ruler (elements are surrounded by quotes). * * @param source rule, as a String * @return Map form of rule * @throws IOException if the rule isn't syntactically valid */ public static Map<String, List<Patterns>> compile(final String source) throws IOException { return doCompile(JSON_FACTORY.createParser(source)); } /** * Compile a rule from its JSON form to a Map suitable for use by events.ruler.Ruler (elements are surrounded by quotes). * * @param source rule, as a byte array * @return Map form of rule * @throws IOException if the rule isn't syntactically valid */ public static Map<String, List<Patterns>> compile(final byte[] source) throws IOException { return doCompile(JSON_FACTORY.createParser(source)); } /** * Compile a rule from its JSON form to a Map suitable for use by events.ruler.Ruler (elements are surrounded by quotes). * * @param source rule, as an InputStream * @return Map form of rule * @throws IOException if the rule isn't syntactically valid */ public static Map<String, List<Patterns>> compile(final InputStream source) throws IOException { return doCompile(JSON_FACTORY.createParser(source)); } private static Map<String, List<Patterns>> doCompile(final JsonParser parser) throws IOException { final Path path = new Path(); final Map<String, List<Patterns>> rule = new HashMap<>(); if (parser.nextToken() != JsonToken.START_OBJECT) { barf(parser, "Filter is not an object"); } parseObject(rule, path, parser, true); parser.close(); return rule; } private static void parseObject(final Map<String, List<Patterns>> rule, final Path path, final JsonParser parser, final boolean withQuotes) throws IOException { boolean fieldsPresent = false; while (parser.nextToken() != JsonToken.END_OBJECT) { fieldsPresent = true; // field name final String stepName = parser.getCurrentName(); switch (parser.nextToken()) { case START_OBJECT: path.push(stepName); parseObject(rule, path, parser, withQuotes); path.pop(); break; case START_ARRAY: writeRules(rule, path.extendedName(stepName), parser, withQuotes); break; default: barf(parser, String.format("\"%s\" must be an object or an array", stepName)); } } if (!fieldsPresent) { barf(parser, "Empty objects are not allowed"); } } private static void writeRules(final Map<String, List<Patterns>> rule, final String name, final JsonParser parser, final boolean withQuotes) throws IOException { JsonToken token; final List<Patterns> values = new ArrayList<>(); while ((token = parser.nextToken()) != JsonToken.END_ARRAY) { switch (token) { case START_OBJECT: values.add(processMatchExpression(parser)); break; case VALUE_STRING: final String toMatch = parser.getText(); final Range ipRange = CIDR.ipToRangeIfPossible(toMatch); if (ipRange != null) { values.add(ipRange); } else if (withQuotes) { values.add(Patterns.exactMatch('"' + toMatch + '"')); } else { values.add(Patterns.exactMatch(toMatch)); } break; case VALUE_NUMBER_FLOAT: case VALUE_NUMBER_INT: /* * If the rule specifies a match to a number, we'll insert matchers for both the * literal expression and the ComparableNumber form. But the number might not * be representble as a ComparableNumber, for example an AWS account number, * so make that condition survivable. */ try { values.add(Patterns.numericEquals(parser.getDoubleValue())); } catch (Exception e) { // no-op } values.add(Patterns.exactMatch(parser.getText())); break; case VALUE_NULL: case VALUE_TRUE: case VALUE_FALSE: values.add(Patterns.exactMatch(parser.getText())); break; default: barf(parser, "Match value must be String, number, true, false, or null"); } } if (values.isEmpty()) { barf(parser, "Empty arrays are not allowed"); } rule.put(name, values); } // Used to be, the format was // "field-name": [ "val1", "val2" ] // now it's like // "field-name": [ "val1", { "prefix": "pref1" }, { "anything-but": "not-this" } ] // private static Patterns processMatchExpression(final JsonParser parser) throws IOException { final JsonToken matchTypeToken = parser.nextToken(); if (matchTypeToken != JsonToken.FIELD_NAME) { barf(parser, "Match expression name not found"); } final String matchTypeName = parser.getCurrentName(); if (Constants.EXACT_MATCH.equals(matchTypeName)) { final JsonToken prefixToken = parser.nextToken(); if (prefixToken != JsonToken.VALUE_STRING) { barf(parser, "exact match pattern must be a string"); } final Patterns pattern = Patterns.exactMatch('"' + parser.getText() + '"'); if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return pattern; } else if (Constants.PREFIX_MATCH.equals(matchTypeName)) { final JsonToken prefixToken = parser.nextToken(); if (prefixToken == JsonToken.START_OBJECT) { return processPrefixEqualsIgnoreCaseExpression(parser); } if (prefixToken != JsonToken.VALUE_STRING) { barf(parser, "prefix match pattern must be a string"); } final Patterns pattern = Patterns.prefixMatch('"' + parser.getText()); // note no trailing quote if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return pattern; } else if (Constants.SUFFIX_MATCH.equals(matchTypeName)) { final JsonToken suffixToken = parser.nextToken(); if (suffixToken == JsonToken.START_OBJECT) { return processSuffixEqualsIgnoreCaseExpression(parser); } if (suffixToken != JsonToken.VALUE_STRING) { barf(parser, "suffix match pattern must be a string"); } final Patterns pattern = Patterns.suffixMatch(parser.getText() + '"'); // note no beginning quote if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return pattern; } else if (Constants.NUMERIC.equals(matchTypeName)) { final JsonToken numericalExpressionToken = parser.nextToken(); if (numericalExpressionToken != JsonToken.START_ARRAY) { barf(parser, "Value of " + Constants.NUMERIC + " must be an array."); } Patterns range = processNumericMatchExpression(parser); if (parser.nextToken() != JsonToken.END_OBJECT) { tooManyElements(parser); } return range; } else if (Constants.ANYTHING_BUT_MATCH.equals(matchTypeName)) { boolean isIgnoreCase = false; JsonToken anythingButExpressionToken = parser.nextToken(); if (anythingButExpressionToken == JsonToken.START_OBJECT) { // there are a limited set of things we can apply Anything-But to final JsonToken anythingButObject = parser.nextToken(); if (anythingButObject != JsonToken.FIELD_NAME) { barf(parser, "Anything-But expression name not found"); } final String anythingButObjectOp = parser.getCurrentName(); final boolean isPrefix = Constants.PREFIX_MATCH.equals(anythingButObjectOp); final boolean isSuffix = Constants.SUFFIX_MATCH.equals(anythingButObjectOp); isIgnoreCase = Constants.EQUALS_IGNORE_CASE.equals(anythingButObjectOp); if(!isIgnoreCase) { if (!isPrefix && !isSuffix) { barf(parser, "Unsupported anything-but pattern: " + anythingButObjectOp); } final JsonToken anythingButParamType = parser.nextToken(); if (anythingButParamType != JsonToken.VALUE_STRING) { barf(parser, "prefix/suffix match pattern must be a string"); } final String text = parser.getText(); if (text.isEmpty()) { barf(parser, "Null prefix/suffix not allowed"); } if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } if(isPrefix) { return Patterns.anythingButPrefix('"' + text); // note no trailing quote } else { return Patterns.anythingButSuffix(text + '"'); // note no leading quote } } else { // Step into the anything-but's ignore-case anythingButExpressionToken = parser.nextToken(); } } if (anythingButExpressionToken != JsonToken.START_ARRAY && anythingButExpressionToken != JsonToken.VALUE_STRING && anythingButExpressionToken != JsonToken.VALUE_NUMBER_FLOAT && anythingButExpressionToken != JsonToken.VALUE_NUMBER_INT) { barf(parser, "Value of " + Constants.ANYTHING_BUT_MATCH + " must be an array or single string/number value."); } Patterns anythingBut; if (anythingButExpressionToken == JsonToken.START_ARRAY) { if(isIgnoreCase) { anythingBut = processAnythingButEqualsIgnoreCaseListMatchExpression(parser); } else { anythingBut = processAnythingButListMatchExpression(parser); } } else { if(isIgnoreCase) { anythingBut = processAnythingButEqualsIgnoreCaseMatchExpression(parser, anythingButExpressionToken); } else { anythingBut = processAnythingButMatchExpression(parser, anythingButExpressionToken); } } if (parser.nextToken() != JsonToken.END_OBJECT) { tooManyElements(parser); } // If its an ignore-case, we have another // object end to consume... if(isIgnoreCase && parser.nextToken() != JsonToken.END_OBJECT) { tooManyElements(parser); } return anythingBut; } else if (Constants.EXISTS_MATCH.equals(matchTypeName)) { return processExistsExpression(parser); } else if (Constants.CIDR.equals(matchTypeName)) { final JsonToken cidrToken = parser.nextToken(); if (cidrToken != JsonToken.VALUE_STRING) { barf(parser, "prefix match pattern must be a string"); } final Range cidr = CIDR.cidr(parser.getText()); if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return cidr; } else if (Constants.EQUALS_IGNORE_CASE.equals(matchTypeName)) { final JsonToken equalsIgnoreCaseToken = parser.nextToken(); if (equalsIgnoreCaseToken != JsonToken.VALUE_STRING) { barf(parser, "equals-ignore-case match pattern must be a string"); } final Patterns pattern = Patterns.equalsIgnoreCaseMatch('"' + parser.getText() + '"'); if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return pattern; } else if (Constants.WILDCARD.equals(matchTypeName)) { final JsonToken wildcardToken = parser.nextToken(); if (wildcardToken != JsonToken.VALUE_STRING) { barf(parser, "wildcard match pattern must be a string"); } final String parserText = parser.getText(); String value = '"' + parserText + '"'; try { getParser().parse(MatchType.WILDCARD, value); } catch (ParseException e) { barf(parser, e.getLocalizedMessage()); } final Patterns pattern = Patterns.wildcardMatch(value); if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return pattern; } else { barf(parser, "Unrecognized match type " + matchTypeName); return null; // unreachable statement, but java can't see that? } } private static Patterns processPrefixEqualsIgnoreCaseExpression(final JsonParser parser) throws IOException { final JsonToken prefixObject = parser.nextToken(); if (prefixObject != JsonToken.FIELD_NAME) { barf(parser, "Prefix expression name not found"); } final String prefixObjectOp = parser.getCurrentName(); if (!Constants.EQUALS_IGNORE_CASE.equals(prefixObjectOp)) { barf(parser, "Unsupported prefix pattern: " + prefixObjectOp); } final JsonToken prefixEqualsIgnoreCase = parser.nextToken(); if (prefixEqualsIgnoreCase != JsonToken.VALUE_STRING) { barf(parser, "equals-ignore-case match pattern must be a string"); } final Patterns pattern = Patterns.prefixEqualsIgnoreCaseMatch('"' + parser.getText()); if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return pattern; } private static Patterns processSuffixEqualsIgnoreCaseExpression(final JsonParser parser) throws IOException { final JsonToken suffixObject = parser.nextToken(); if (suffixObject != JsonToken.FIELD_NAME) { barf(parser, "Suffix expression name not found"); } final String suffixObjectOp = parser.getCurrentName(); if (!Constants.EQUALS_IGNORE_CASE.equals(suffixObjectOp)) { barf(parser, "Unsupported suffix pattern: " + suffixObjectOp); } final JsonToken suffixEqualsIgnoreCase = parser.nextToken(); if (suffixEqualsIgnoreCase != JsonToken.VALUE_STRING) { barf(parser, "equals-ignore-case match pattern must be a string"); } final Patterns pattern = Patterns.suffixEqualsIgnoreCaseMatch(parser.getText() + '"'); if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return pattern; } private static Patterns processAnythingButListMatchExpression(JsonParser parser) throws JsonParseException { JsonToken token; Set<String> values = new HashSet<>(); boolean hasNumber = false; boolean hasString = false; try { while ((token = parser.nextToken()) != JsonToken.END_ARRAY) { switch (token) { case VALUE_STRING: values.add('"' + parser.getText() + '"'); hasString = true; break; case VALUE_NUMBER_FLOAT: case VALUE_NUMBER_INT: values.add(ComparableNumber.generate(parser.getDoubleValue())); hasNumber = true; break; default: barf(parser, "Inside anything but list, start|null|boolean is not supported."); } } } catch (IllegalArgumentException | IOException e) { barf(parser, e.getMessage()); } if ((hasNumber && hasString) || (!hasNumber && !hasString)) { barf(parser, "Inside anything but list, either all values are number or string, " + "mixed type is not supported"); } return AnythingBut.anythingButMatch(values, hasNumber); } private static Patterns processAnythingButEqualsIgnoreCaseListMatchExpression(JsonParser parser) throws JsonParseException { JsonToken token; Set<String> values = new HashSet<>(); boolean hasNumber = false; try { while ((token = parser.nextToken()) != JsonToken.END_ARRAY) { switch (token) { case VALUE_STRING: values.add('"' + parser.getText() + '"'); break; default: barf(parser, "Inside anything-but/ignore-case list, number|start|null|boolean is not supported."); } } } catch (IllegalArgumentException | IOException e) { barf(parser, e.getMessage()); } return AnythingButEqualsIgnoreCase.anythingButIgnoreCaseMatch(values); } private static Patterns processAnythingButMatchExpression(JsonParser parser, JsonToken anythingButExpressionToken) throws IOException { Set<String> values = new HashSet<>(); boolean hasNumber = false; switch (anythingButExpressionToken) { case VALUE_STRING: values.add('"' + parser.getText() + '"'); break; case VALUE_NUMBER_FLOAT: case VALUE_NUMBER_INT: values.add(ComparableNumber.generate(parser.getDoubleValue())); hasNumber = true; break; default: barf(parser, "Inside anything-but list, start|null|boolean is not supported."); } return AnythingBut.anythingButMatch(values, hasNumber); } private static Patterns processAnythingButEqualsIgnoreCaseMatchExpression(JsonParser parser, JsonToken anythingButExpressionToken) throws IOException { Set<String> values = new HashSet<>(); switch (anythingButExpressionToken) { case VALUE_STRING: values.add('"' + parser.getText() + '"'); break; default: barf(parser, "Inside anything-but/ignore-case list, number|start|null|boolean is not supported."); } return AnythingButEqualsIgnoreCase.anythingButIgnoreCaseMatch(values); } private static Patterns processNumericMatchExpression(final JsonParser parser) throws IOException { JsonToken token = parser.nextToken(); if (token != JsonToken.VALUE_STRING) { barf(parser, "Invalid member in numeric match: " + parser.getText()); } String operator = parser.getText(); token = parser.nextToken(); try { if (Constants.EQ.equals(operator)) { if (!token.isNumeric()) { barf(parser, "Value of equals must be numeric"); } final double val = parser.getDoubleValue(); if (parser.nextToken() != JsonToken.END_ARRAY) { tooManyElements(parser); } return Patterns.numericEquals(val); } else if (Constants.GE.equals(operator)) { if (!token.isNumeric()) { barf(parser, "Value of >= must be numeric"); } final double val = parser.getDoubleValue(); token = parser.nextToken(); if (token == JsonToken.END_ARRAY) { return Range.greaterThanOrEqualTo(val); } return completeNumericRange(parser, token, val, false); } else if (Constants.GT.equals(operator)) { if (!token.isNumeric()) { barf(parser, "Value of > must be numeric"); } final double val = parser.getDoubleValue(); token = parser.nextToken(); if (token == JsonToken.END_ARRAY) { return Range.greaterThan(val); } return completeNumericRange(parser, token, val, true); } else if (Constants.LE.equals(operator)) { if (!token.isNumeric()) { barf(parser, "Value of <= must be numeric"); } final double top = parser.getDoubleValue(); if (parser.nextToken() != JsonToken.END_ARRAY) { tooManyElements(parser); } return Range.lessThanOrEqualTo(top); } else if (Constants.LT.equals(operator)) { if (!token.isNumeric()) { barf(parser, "Value of < must be numeric"); } final double top = parser.getDoubleValue(); if (parser.nextToken() != JsonToken.END_ARRAY) { tooManyElements(parser); } return Range.lessThan(top); } else { barf(parser, "Unrecognized numeric range operator: " + operator); } } catch (IllegalArgumentException e) { barf(parser, e.getMessage()); } return null; // completely unreachable } private static Patterns completeNumericRange(final JsonParser parser, final JsonToken token, final double bottom, final boolean openBottom) throws IOException { if (token != JsonToken.VALUE_STRING) { barf(parser, "Bad value in numeric range: " + parser.getText()); } final String operator = parser.getText(); boolean openTop = false; if (Constants.LT.equals(operator)) { openTop = true; } else if (!Constants.LE.equals(operator)) { barf(parser, "Bad numeric range operator: " + operator); } if (!parser.nextToken().isNumeric()) { barf(parser, "Value of " + operator + " must be numeric"); } final double top = parser.getDoubleValue(); if (parser.nextToken() != JsonToken.END_ARRAY) { barf(parser, "Too many terms in numeric range expression"); } return Range.between(bottom, openBottom, top, openTop); } private static Patterns processExistsExpression(final JsonParser parser) throws IOException { final JsonToken existsToken = parser.nextToken(); Patterns existsPattern; if (existsToken == JsonToken.VALUE_TRUE) { existsPattern = Patterns.existencePatterns(); } else if (existsToken == JsonToken.VALUE_FALSE) { existsPattern = Patterns.absencePatterns(); } else { barf(parser, "exists match pattern must be either true or false."); return null; } if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); return null; } return existsPattern; } private static void tooManyElements(final JsonParser parser) throws JsonParseException { barf(parser, "Too many elements in numeric expression"); } private static void barf(final JsonParser parser, final String message) throws JsonParseException { throw new JsonParseException(parser, message, parser.getCurrentLocation()); } /** * This is a rule parser which will parse rule of JSON format into a map of string list to Patterns list structure * which is suitable to be used by Ruler.matches. * The only difference in output between ListBasedRuleCompiler.flattenRule and Filter.compile is type and format of * Map.key. * For example, if input rule is below JSON string: * { * "detail" : { * "state" : [ "initializing" ] * } * } * The key of output MAP by ListBasedRuleCompiler.flattenRule will be a list like: ["detail","state"]. * The key of output MAP by Filter.compile will be a String: "detail.state". */ public static class ListBasedRuleCompiler { private static final JsonFactory JSON_FACTORY = new JsonFactory(); /** * Compile a rule from its JSON form to a Map suitable for use by events.ruler.Ruler * * @param source rule, as a String * @return Map form of rule * @throws IOException if the rule isn't syntactically valid */ public static Map<List<String>, List<Patterns>> flattenRule(final String source) throws IOException { return doFlattenRule(JSON_FACTORY.createParser(source)); } private static Map<List<String>, List<Patterns>> doFlattenRule(final JsonParser parser) throws IOException { final Deque<String> stack = new ArrayDeque<>(); final Map<List<String>, List<Patterns>> rule = new HashMap<>(); if (parser.nextToken() != JsonToken.START_OBJECT) { barf(parser, "Filter is not an object"); } parseRuleObject(rule, stack, parser, true); parser.close(); return rule; } private static void parseRuleObject(final Map<List<String>, List<Patterns>> rule, final Deque<String> stack, final JsonParser parser, final boolean withQuotes) throws IOException { boolean fieldsPresent = false; while (parser.nextToken() != JsonToken.END_OBJECT) { fieldsPresent = true; // field name final String stepName = parser.getCurrentName(); switch (parser.nextToken()) { case START_OBJECT: stack.addLast(stepName); parseRuleObject(rule, stack, parser, withQuotes); stack.removeLast(); break; case START_ARRAY: writeRules(rule, rulePathname(stack, stepName), parser, withQuotes); break; default: barf(parser, String.format("\"%s\" must be an object or an array", stepName)); } } if (!fieldsPresent) { barf(parser, "Empty objects are not allowed"); } } private static void writeRules(final Map<List<String>, List<Patterns>> rule, final List<String> name, final JsonParser parser, final boolean withQuotes) throws IOException { JsonToken token; final List<Patterns> values = new ArrayList<>(); while ((token = parser.nextToken()) != JsonToken.END_ARRAY) { switch (token) { case START_OBJECT: values.add(processMatchExpression(parser)); break; case VALUE_STRING: if (withQuotes) { values.add(Patterns.exactMatch('"' + parser.getText() + '"')); } else { values.add(Patterns.exactMatch(parser.getText())); } break; case VALUE_NUMBER_FLOAT: case VALUE_NUMBER_INT: values.add(Patterns.numericEquals(parser.getDoubleValue())); values.add(Patterns.exactMatch(parser.getText())); break; case VALUE_NULL: case VALUE_TRUE: case VALUE_FALSE: values.add(Patterns.exactMatch(parser.getText())); break; default: barf(parser, "Match value must be String, number, true, false, or null"); } } if (values.isEmpty()) { barf(parser, "Empty arrays are not allowed"); } rule.put(name, values); } private static List<String> rulePathname(final Deque<String> path, final String stepName) { List<String> sb = new ArrayList<>(path); sb.add(stepName); return sb; } } }
4,906
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/ByteState.java
package software.amazon.event.ruler; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Represents a state in a state machine and maps utf-8 bytes to transitions. One byte can have many transitions, * meaning this is an NFA state as opposed to a DFA state. */ @ThreadSafe class ByteState extends SingleByteTransition { /** * The field is a {@link ByteMap}, however, to optimize on memory, this field may be {@code null} when this state * contains no transitions, and may be a {@link SingleByteTransitionEntry} when this state contains one transition. */ @Nullable private volatile Object transitionStore; /* True if this state's placement in the machine means there is more than one possible value that can be matched on * a traversal from the start state to this state. This will happen, for example, when a wildcard or regex * expression occurs between the start state and this state. */ private boolean hasIndeterminatePrefix = false; ByteState getNextByteState() { return this; } @Override public SingleByteTransition setNextByteState(ByteState nextState) { return nextState; } @Override ByteMatch getMatch() { return null; } @Override public SingleByteTransition setMatch(ByteMatch match) { return match == null ? this : new CompositeByteTransition(this, match); } @Override public Set<ShortcutTransition> getShortcuts() { return Collections.emptySet(); } /** * Returns {@code true} if this state contains no transitions. * * @return {@code true} if this state contains no transitions */ boolean hasNoTransitions() { return transitionStore == null; } /** * Returns the transition to which the given byte value is mapped, or {@code null} if this state contains no * transitions for the given byte value. * * @param utf8byte the byte value whose associated transition is to be returned * @return the transition to which the given byte value is mapped, or {@code null} if this state contains no * transitions for the given byte value */ @Override ByteTransition getTransition(byte utf8byte) { // Saving the value to avoid reading an updated value Object transitionStore = this.transitionStore; if (transitionStore == null) { return null; } else if (transitionStore instanceof SingleByteTransitionEntry) { SingleByteTransitionEntry entry = (SingleByteTransitionEntry) transitionStore; return utf8byte == entry.utf8byte ? entry.transition : null; } ByteMap map = (ByteMap) transitionStore; return map.getTransition(utf8byte); } @Override ByteTransition getTransitionForAllBytes() { // Saving the value to avoid reading an updated value Object transitionStore = this.transitionStore; if (transitionStore == null || transitionStore instanceof SingleByteTransitionEntry) { return ByteMachine.EmptyByteTransition.INSTANCE; } ByteMap map = (ByteMap) transitionStore; return map.getTransitionForAllBytes(); } @Override Iterable<ByteTransition> getTransitions() { // Saving the value to avoid reading an updated value Object transitionStore = this.transitionStore; if (transitionStore == null) { return Collections.emptySet(); } else if (transitionStore instanceof SingleByteTransitionEntry) { SingleByteTransitionEntry entry = (SingleByteTransitionEntry) transitionStore; return entry.transition; } ByteMap map = (ByteMap) transitionStore; return map.getTransitions(); } /** * Associates the given transition with the given byte value in this state. If the state previously contained any * transitions for the byte value, the old transitions are replaced by the given transition. * * @param utf8byte the byte value with which the given transition is to be associated * @param transition the transition to be associated with the given byte value */ void putTransition(byte utf8byte, @Nonnull SingleByteTransition transition) { // Saving the value to avoid reading an updated value Object transitionStore = this.transitionStore; if (transitionStore == null) { this.transitionStore = new SingleByteTransitionEntry(utf8byte, transition); } else if (transitionStore instanceof SingleByteTransitionEntry) { SingleByteTransitionEntry entry = (SingleByteTransitionEntry) transitionStore; if (utf8byte == entry.utf8byte) { entry.transition = transition; } else { ByteMap map = new ByteMap(); map.putTransition(entry.utf8byte, entry.transition); map.putTransition(utf8byte, transition); this.transitionStore = map; } } else { ByteMap map = (ByteMap) transitionStore; map.putTransition(utf8byte, transition); } } /** * Associates the given transition with all possible byte values in this state. If the state previously contained * any transitions for any of the byte values, the old transitions are replaced by the given transition. * * @param transition the transition to be associated with the given byte value */ void putTransitionForAllBytes(@Nonnull SingleByteTransition transition) { ByteMap map = new ByteMap(); map.putTransitionForAllBytes(transition); this.transitionStore = map; } /** * Associates the given transition with the given byte value in this state. If the state previously contained any * transitions for the byte value, the given transition is added to these old transitions. * * @param utf8byte the byte value with which the given transition is to be associated * @param transition the transition to be associated with the given byte value */ void addTransition(byte utf8byte, @Nonnull SingleByteTransition transition) { // Saving the value to avoid reading an updated value Object transitionStore = this.transitionStore; if (transitionStore == null) { this.transitionStore = new SingleByteTransitionEntry(utf8byte, transition); } else if (transitionStore instanceof SingleByteTransitionEntry) { SingleByteTransitionEntry entry = (SingleByteTransitionEntry) transitionStore; ByteMap map = new ByteMap(); map.addTransition(entry.utf8byte, entry.transition); map.addTransition(utf8byte, transition); this.transitionStore = map; } else { ByteMap map = (ByteMap) transitionStore; map.addTransition(utf8byte, transition); } } /** * Associates the given transition with all possible byte values in this state. If the state previously contained * any transitions for any of the byte values, the given transition is added to these old transitions. * * @param transition the transition to be associated with all possible byte values */ void addTransitionForAllBytes(final SingleByteTransition transition) { // Saving the value to avoid reading an updated value Object transitionStore = this.transitionStore; ByteMap map; if (transitionStore instanceof ByteMap) { map = (ByteMap) transitionStore; } else { map = new ByteMap(); } if (transitionStore instanceof SingleByteTransitionEntry) { SingleByteTransitionEntry entry = (SingleByteTransitionEntry) transitionStore; map.addTransition(entry.utf8byte, entry.transition); } map.addTransitionForAllBytes(transition); this.transitionStore = map; } /** * Removes provided transition for the given byte value from this state. * * @param utf8byte the byte value for which to remove transition from the state * @param transition remove this transition for provided byte value from the state */ void removeTransition(byte utf8byte, SingleByteTransition transition) { // Saving the value to avoid reading an updated value Object transitionStore = this.transitionStore; if (transitionStore == null) { return; } if (transitionStore instanceof SingleByteTransitionEntry) { SingleByteTransitionEntry entry = (SingleByteTransitionEntry) transitionStore; if (utf8byte == entry.utf8byte && transition.equals(entry.transition)) { this.transitionStore = null; } } else { ByteMap map = (ByteMap) transitionStore; map.removeTransition(utf8byte, transition); if (map.isEmpty()) { this.transitionStore = null; } } } /** * Removes the given transition for all possible byte values from this state. * * @param transition the transition to be removed for all possible byte values */ void removeTransitionForAllBytes(final SingleByteTransition transition) { // Saving the value to avoid reading an updated value Object transitionStore = this.transitionStore; if (transitionStore == null) { return; } if (transitionStore instanceof SingleByteTransitionEntry) { SingleByteTransitionEntry entry = (SingleByteTransitionEntry) transitionStore; if (transition.equals(entry.transition)) { this.transitionStore = null; } } else { ByteMap map = (ByteMap) transitionStore; map.removeTransitionForAllBytes(transition); if (map.isEmpty()) { this.transitionStore = null; } } } @Override boolean hasIndeterminatePrefix() { return hasIndeterminatePrefix; } void setIndeterminatePrefix(boolean hasIndeterminatePrefix) { this.hasIndeterminatePrefix = hasIndeterminatePrefix; } /** * Return true if this state has a self-referential transition and no others. * * @return True if this state has a self-referential transition and no others, false otherwise. */ boolean hasOnlySelfReferentialTransition() { // Saving the value to avoid reading an updated value Object transitionStore = this.transitionStore; if (transitionStore == null) { return false; } else if (transitionStore instanceof SingleByteTransitionEntry) { SingleByteTransitionEntry entry = (SingleByteTransitionEntry) transitionStore; return this.equals(entry.transition); } ByteMap map = (ByteMap) transitionStore; return map.numberOfTransitions() == 1 && map.hasTransition(this); } /** * Gets all the ceiling values contained in the ByteMap or SingleByteTransitionEntry. * * @return All the ceiling values contained in the ByteMap or SingleByteTransitionEntry. */ Set<Integer> getCeilings() { // Saving the value to avoid reading an updated value Object transitionStore = this.transitionStore; if (transitionStore == null) { return Collections.emptySet(); } else if (transitionStore instanceof SingleByteTransitionEntry) { SingleByteTransitionEntry entry = (SingleByteTransitionEntry) transitionStore; int index = entry.utf8byte & 0xFF; if (index == 0) { return Stream.of(index + 1, 256).collect(Collectors.toSet()); } else if (index == 255) { return Stream.of(index, index + 1).collect(Collectors.toSet()); } else { return Stream.of(index, index + 1, 256).collect(Collectors.toSet()); } } ByteMap map = (ByteMap) transitionStore; return map.getCeilings(); } @Override public String toString() { return "BS: " + transitionStore; } private static final class SingleByteTransitionEntry { final byte utf8byte; volatile SingleByteTransition transition; SingleByteTransitionEntry(byte utf8byte, SingleByteTransition transition) { this.utf8byte = utf8byte; this.transition = transition; } @Override public String toString() { ByteState next = transition.getNextByteState(); String nextLabel = (next == null) ? "null" : Integer.toString(next.hashCode()); return "SBTE: " + (char) utf8byte + "=>" + nextLabel; } } }
4,907
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/Task.java
package software.amazon.event.ruler; import javax.annotation.concurrent.ThreadSafe; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Queue; import java.util.Set; import static software.amazon.event.ruler.SetOperations.intersection; /** * Represents the state of a rule-finding project. */ @ThreadSafe class Task { // What we're trying to match rules to public final String[] event; // the rules that matched the event, if we find any private final Set<Object> matchingRules = new HashSet<>(); // Steps queued up for processing private final Queue<Step> stepQueue = new ArrayDeque<>(); // Visiting the same Step multiple times will give the same outcome for all visits, // as we are not mutating the state of Task nor Step nor GenericMachine as part of the visit. // To prevent explosion of complexity we need to prevent queueing up steps that are still // waiting in the stepQueue or we have already ran. We end up holding on to some amount // of memory during Task evaluation to track this, but it has an upper bound that is O(n * m) where // n = number of values in input event // m = number of nodes in the compiled state machine private final Set<Step> seenSteps = new HashSet<>(); // the state machine private final GenericMachine<?> machine; Task(final List<String> event, final GenericMachine<?> machine) { this(event.toArray(new String[0]), machine); } Task(final String[] event, final GenericMachine<?> machine) { this.event = event; this.machine = machine; } NameState startState() { return machine.getStartState(); } // The field used means all steps in the field must be all used individually. boolean isFieldUsed(final String field) { if (field.contains(".")) { String[] steps = field.split("\\."); return Arrays.stream(steps).allMatch(machine::isFieldStepUsed); } return machine.isFieldStepUsed(field); } Step nextStep() { return stepQueue.remove(); } void addStep(final Step step) { // queue it up only if it's the first time we're trying to queue it up // otherwise bad things happen, see comment on seenSteps collection if (seenSteps.add(step)) { stepQueue.add(step); } } boolean stepsRemain() { return !stepQueue.isEmpty(); } List<Object> getMatchedRules() { return new ArrayList<>(matchingRules); } void collectRules(final Set<Double> candidateSubRuleIds, final NameState nameState, final Patterns pattern) { Set<Double> terminalSubRuleIds = nameState.getTerminalSubRuleIdsForPattern(pattern); if (terminalSubRuleIds == null) { return; } // If no candidates, that means we're on the first step, so all sub-rules are candidates. if (candidateSubRuleIds == null || candidateSubRuleIds.isEmpty()) { for (Double terminalSubRuleId : terminalSubRuleIds) { matchingRules.add(nameState.getRule(terminalSubRuleId)); } } else { intersection(candidateSubRuleIds, terminalSubRuleIds, matchingRules, id -> nameState.getRule(id)); } } }
4,908
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/Range.java
package software.amazon.event.ruler; import java.nio.charset.StandardCharsets; import java.util.Arrays; /** * Represents a range of numeric values to match against. * "Numeric" means that the character repertoire is "digits"; initially, either 0-9 or 0-9a-f. In the current * implementation, the number of digits in the top and bottom of the range is the same. */ public class Range extends Patterns { /** * Bottom and top of the range. openBottom true means we're looking for > bottom, false means >= * Similarly, openTop true means we're looking for < top, false means <= top. */ final byte[] bottom; final boolean openBottom; final byte[] top; final boolean openTop; final boolean isCIDR; private static final int HEX_DIGIT_A_DECIMAL_VALUE = 10; private Range(final double bottom, final boolean openBottom, final double top, final boolean openTop) { super(MatchType.NUMERIC_RANGE); if (bottom >= top) { throw new IllegalArgumentException("Bottom must be less than top"); } this.bottom = ComparableNumber.generate(bottom).getBytes(StandardCharsets.UTF_8); this.openBottom = openBottom; this.top = ComparableNumber.generate(top).getBytes(StandardCharsets.UTF_8); this.openTop = openTop; isCIDR = false; } Range(final byte[] bottom, final boolean openBottom, final byte[] top, final boolean openTop, final boolean isCIDR) { super(MatchType.NUMERIC_RANGE); this.bottom = bottom; this.top = top; this.openBottom = openBottom; this.openTop = openTop; this.isCIDR = isCIDR; } private Range(Range range) { super(MatchType.NUMERIC_RANGE); this.bottom = range.bottom.clone(); this.openBottom = range.openBottom; this.top = range.top.clone(); this.openTop = range.openTop; this.isCIDR = range.isCIDR; } public static Range lessThan(final double val) { return new Range(-Constants.FIVE_BILLION, false, val, true); } public static Range lessThanOrEqualTo(final double val) { return new Range(-Constants.FIVE_BILLION, false, val, false); } public static Range greaterThan(final double val) { return new Range(val, true, Constants.FIVE_BILLION, false); } public static Range greaterThanOrEqualTo(final double val) { return new Range(val, false, Constants.FIVE_BILLION, false); } public static Range between(final double bottom, final boolean openBottom, final double top, final boolean openTop) { return new Range(bottom, openBottom, top, openTop); } private static Range deepCopy(final Range range) { return new Range(range); } /** * This is necessitated by the fact that we do range comparisons of numbers, fixed-length strings of digits, and * in the case where the numbers represent IP addresses, they are hex digits. So we need to be able to say * "for all digits between '3' and 'C'". This is for that. * * @param first Start one digit higher than this, for example '4' * @param last Stop one digit lower than this, for example 'B' * @return The digit list, for example [ '4', '5', '6', '7', '8', '9', '9', 'A' ] (with 'B' for longDigitSequence) */ static byte[] digitSequence(byte first, byte last, boolean includeFirst, boolean includeLast) { assert first <= last && first <= 'F' && first >= '0' && last <= 'F'; assert !((first == last) && !includeFirst && !includeLast); int i = getHexByteIndex(first); int j = getHexByteIndex(last); if ((!includeFirst) && (i < (Constants.HEX_DIGITS.length - 1))) { i++; } if (includeLast) { j++; } byte[] bytes = new byte[j - i]; System.arraycopy(Constants.HEX_DIGITS, i, bytes, 0, j - i); return bytes; } private static int getHexByteIndex(byte value) { // ['0'-'9'] maps to [0-9] indexes if (value >= '0' && value <= '9') { return value - '0'; } // ['A'-'F'] maps to [10-15] indexes return (value - 'A') + HEX_DIGIT_A_DECIMAL_VALUE; } @Override public Object clone() { super.clone(); return Range.deepCopy(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || !o.getClass().equals(getClass())) { return false; } if (!super.equals(o)) { return false; } Range range = (Range) o; return openBottom == range.openBottom && openTop == range.openTop && Arrays.equals(bottom, range.bottom) && Arrays.equals(top, range.top); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + Arrays.hashCode(bottom); result = 31 * result + Boolean.hashCode(openBottom); result = 31 * result + Arrays.hashCode(top); result = 31 * result + Boolean.hashCode(openTop); return result; } public String toString() { return (new String(bottom, StandardCharsets.UTF_8)) + '/' + (new String(top, StandardCharsets.UTF_8)) + ':' + openBottom + '/' + openTop + " (" + super.toString() + ")"; } }
4,909
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/Step.java
package software.amazon.event.ruler; import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.ThreadSafe; import java.util.Objects; import java.util.Set; /** * Represents a suggestion of a state/token combo from which there might be a transition. The event token * indexed is always the key of a key/value combination */ @Immutable @ThreadSafe class Step { final int keyIndex; final NameState nameState; final Set<Double> candidateSubRuleIds; Step(final int keyIndex, final NameState nameState, final Set<Double> candidateSubRuleIds) { this.keyIndex = keyIndex; this.nameState = nameState; this.candidateSubRuleIds = candidateSubRuleIds; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Step step = (Step) o; return keyIndex == step.keyIndex && Objects.equals(nameState, step.nameState) && Objects.equals(candidateSubRuleIds, step.candidateSubRuleIds); } @Override public int hashCode() { return Objects.hash(keyIndex, nameState, candidateSubRuleIds); } }
4,910
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/Field.java
package software.amazon.event.ruler; /** * Represents the name and value of a data field in an event that Ruler will match. * * Both name and value are represented as strings. Also provided for each field is information about its position * in any arrays the event may contain. This is used to guard against a rule matching a set of fields which are in * peer elements of an array, a situation which it turns out is perceived by users as a bug. */ class Field { final String name; final String val; final ArrayMembership arrayMembership; Field(final String name, final String val, final ArrayMembership arrayMembership) { this.name = name; this.val = val; this.arrayMembership = arrayMembership; } }
4,911
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/ByteMatch.java
package software.amazon.event.ruler; import java.util.Collections; import java.util.Set; /** * Represents a place in a ByteMachine where we have to do something in addition to just transitioning to another step. */ final class ByteMatch extends SingleByteTransition { private final Patterns pattern; private final NameState nextNameState; // the next state in the higher-level name/value machine ByteMatch(Patterns pattern, NameState nextNameState) { this.pattern = pattern; this.nextNameState = nextNameState; } @Override public ByteState getNextByteState() { return null; } @Override public SingleByteTransition setNextByteState(ByteState nextState) { return nextState == null ? this : new CompositeByteTransition(nextState, this); } @Override public ByteTransition getTransition(byte utf8byte) { return null; } @Override public ByteTransition getTransitionForAllBytes() { return null; } @Override public Set<ByteTransition> getTransitions() { return Collections.emptySet(); } @Override ByteMatch getMatch() { return this; } @Override public SingleByteTransition setMatch(ByteMatch match) { return match; } @Override public Set<ShortcutTransition> getShortcuts() { return Collections.emptySet(); } Patterns getPattern() { return pattern; } NameState getNextNameState() { return nextNameState; } @Override boolean isMatchTrans() { return true; } public void gatherObjects(Set<Object> objectSet, int maxObjectCount) { if (!objectSet.contains(this) && objectSet.size() < maxObjectCount) { // stops looping objectSet.add(this); nextNameState.gatherObjects(objectSet, maxObjectCount); } } @Override public String toString() { return "BM: HC=" + hashCode() + " P=" + pattern + "(" + pattern.pattern() + ") NNS=" + nextNameState; } }
4,912
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/CompoundByteTransition.java
package software.amazon.event.ruler; import javax.annotation.Nullable; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Objects; import java.util.Set; import java.util.TreeSet; /** * An implementation of ByteTransition that represents having taken multiple ByteTransitions simultaneously. This is * useful for traversing an NFA, i.e. when a single byte could lead you down multiple different transitions. */ public final class CompoundByteTransition extends ByteTransition { /** * The transitions that have all been simultaneously traversed. */ private final Set<SingleByteTransition> byteTransitions; /** * A view of byteTransitions containing just the shortcuts. */ private Set<ShortcutTransition> shortcutTransitions; /** * A view of byteTransitions containing just the ones that can contain matches. */ private Set<SingleByteTransition> matchableTransitions; /** * A ByteTransition representing all nextByteStates from byteTransitions. */ private ByteTransition transitionForNextByteState; private CompoundByteTransition(Set<SingleByteTransition> byteTransitions) { this.byteTransitions = Collections.unmodifiableSet(byteTransitions); Set<ShortcutTransition> shortcutTransitions = new HashSet<>(); Set<SingleByteTransition> matchableTransitions = new HashSet<>(); Set<SingleByteTransition> nextByteStates = new HashSet<>(); this.byteTransitions.forEach(t -> { if (t.isShortcutTrans()) { shortcutTransitions.add((ShortcutTransition) t); } if (t.isMatchTrans()) { matchableTransitions.add(t); } ByteState nextByteState = t.getNextByteState(); if (nextByteState != null) { nextByteStates.add(nextByteState); } }); this.shortcutTransitions = Collections.unmodifiableSet(shortcutTransitions); this.matchableTransitions = Collections.unmodifiableSet(matchableTransitions); if (nextByteStates.equals(byteTransitions)) { this.transitionForNextByteState = this; } else { this.transitionForNextByteState = coalesce(nextByteStates); } } static <T extends ByteTransition> T coalesce(Iterable<SingleByteTransition> singles) { Iterator<SingleByteTransition> iterator = singles.iterator(); if (!iterator.hasNext()) { return null; } SingleByteTransition firstElement = iterator.next(); if (!iterator.hasNext()) { return (T) firstElement; } else if (singles instanceof Set) { return (T) new CompoundByteTransition((Set) singles); } else { // We expect Iterables with more than one element to always be Sets, so this should be dead code, but adding // it here for future-proofing. Set<SingleByteTransition> set = new HashSet(); singles.forEach(single -> set.add(single)); return (T) new CompoundByteTransition(set); } } /** * Returns the nextByteState from all byteTransitions with a preference to states that have determinate prefixes. * These states are re-usable when adding rules to the machine. * * @return First byte state with a preference to re-usable states. */ @Override @Nullable ByteState getNextByteState() { ByteState firstNonNull = null; for (ByteTransition trans : byteTransitions) { for (SingleByteTransition single : trans.expand()) { ByteState nextByteState = single.getNextByteState(); if (nextByteState != null) { if (!nextByteState.hasIndeterminatePrefix()) { return nextByteState; } if (firstNonNull == null) { firstNonNull = nextByteState; } } } } return firstNonNull; } @Override public SingleByteTransition setNextByteState(ByteState nextState) { return nextState; } /** * Get all transitions represented by this compound transition. * * @return A set of all transitions represented by this transition. */ @Override Set<SingleByteTransition> expand() { return byteTransitions; } @Override ByteTransition getTransitionForNextByteStates() { return transitionForNextByteState; } /** * Get the matches given all of the transitions that have been simultaneously traversed. Excludes matches from * shortcut transitions as these are not actual matches based on the characters seen so far during the current * traversal. * * @return All matches from all of the simultaneously traversed transitions. */ @Override public Set<ByteMatch> getMatches() { Set<ByteMatch> matches = new HashSet<>(); for (SingleByteTransition single : matchableTransitions) { single.getMatches().forEach(match -> matches.add(match)); } return matches; } @Override public Set<ShortcutTransition> getShortcuts() { return shortcutTransitions; } /** * Get the next transition for a UTF-8 byte given all of the transitions that have been simultaneously traversed. * * @param utf8byte The byte to transition on * @return Null if there are no transitions, the actual transition if 1, or a CompoundByteTransition if 2+ */ @Override public ByteTransition getTransition(byte utf8byte) { Set<SingleByteTransition> singles = new HashSet<>(); for (SingleByteTransition transition : this.byteTransitions) { ByteTransition nextTransition = transition.getTransition(utf8byte); if (nextTransition != null) { nextTransition.expand().forEach(t -> singles.add(t)); } } return coalesce(singles); } @Override public Set<ByteTransition> getTransitions() { // Determine all unique ceilings held in the ByteMaps of all nextByteStates. Set<Integer> allCeilings = new TreeSet<>(); for (SingleByteTransition transition : byteTransitions) { ByteState nextByteState = transition.getNextByteState(); if (nextByteState != null) { allCeilings.addAll(nextByteState.getCeilings()); } } // For each unique ceiling, determine all singular transitions accessible for that byte value, then add // coalesced version to final result. Set<ByteTransition> result = new HashSet<>(); for (Integer ceiling : allCeilings) { Set<SingleByteTransition> singles = new HashSet<>(); for (SingleByteTransition transition : byteTransitions) { ByteTransition nextTransition = transition.getTransition((byte) (ceiling - 1)); if (nextTransition != null) { nextTransition.expand().forEach(t -> singles.add(t)); } } ByteTransition coalesced = coalesce(singles); if (coalesced != null) { result.add(coalesced); } } return result; } @Override public boolean equals(Object o) { if (o == null || o.getClass() != getClass()) { return false; } CompoundByteTransition other = (CompoundByteTransition) o; return Objects.equals(byteTransitions, other.byteTransitions); } @Override public int hashCode() { return Objects.hash(byteTransitions); } @Override public String toString() { return "CBT: " + byteTransitions.toString(); } }
4,913
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/ByteTransition.java
package software.amazon.event.ruler; import java.util.Set; /** * Represents a transition (on a particular byte value) from a state to a state. */ abstract class ByteTransition implements Cloneable { /** * Returns the state to transfer to. * * @return the state to transfer to, or {@code null} if this transition does not transfer to a state */ abstract ByteState getNextByteState(); /** * Sets the next state. The method returns this or a new transition that contains the given next state if the * next state is not {@code null}. Otherwise, the method returns {@code null} or a new transition that does not * support transfer. * * @param nextState the next state * @return this or a new transition that contains the given next state if the next state is not {@code null}; * otherwise, the method returns {@code null} or a new transition that does not support transfer */ abstract SingleByteTransition setNextByteState(ByteState nextState); /** * Get a subsequent transition from this transition for the given UTF-8 byte. * * @param utf8byte The byte to transition on * @return The next transition given the byte, or {@code null} if there is not a next transition */ abstract ByteTransition getTransition(byte utf8byte); /** * Get all the unique transitions (single or compound) reachable from this transition by any UTF-8 byte value. * * @return Iterable of all transitions reachable from this transition. */ abstract Iterable<ByteTransition> getTransitions(); /** * Returns matches that are triggered if this transition is made. This is a convenience function that traverses the * linked list of matches and returns all of them in an Iterable. * * @return matches that are triggered if this transition is made. */ abstract Iterable<ByteMatch> getMatches(); /** * Returns all shortcuts that are available if this transition is made. * * @return all shortcuts */ abstract Iterable<ShortcutTransition> getShortcuts(); /** * Get all transitions represented by this transition (can be more than one if this is a compound transition). * * @return An iterable of all transitions represented by this transition. */ abstract Iterable<SingleByteTransition> expand(); /** * Get a transition that represents all of the next byte states for this transition. * * @return A transition that represents all of the next byte states for this transition. */ abstract ByteTransition getTransitionForNextByteStates(); /** * Tell if current transition is a shortcut transition or not. * * @return True if and only if this is a shortcut transition. */ boolean isShortcutTrans() { return false; } /** * Tell if current transition is a match transition or not. Does not include shortcut transitions. Only includes * transitions that are matches after processing the entire pattern value. * * @return True if and only if there is a match on this transition. */ boolean isMatchTrans() { return false; } /** * Tell if current transition is empty which means doesn't has match nor next state. * @return boolean */ boolean isEmpty() { return !getMatches().iterator().hasNext() && getNextByteState() == null; } /** * Indicates if it is possible to traverse from the machine's start state to this transition using more than one * possible prefix/character-sequence. * * @return True if prefix is indeterminate; false otherwise. */ boolean hasIndeterminatePrefix() { return false; } public void gatherObjects(Set<Object> objectSet, int maxObjectCount) { if (!objectSet.contains(this) && objectSet.size() < maxObjectCount) { // stops looping objectSet.add(this); for (ByteMatch match : getMatches()) { match.gatherObjects(objectSet, maxObjectCount); } final ByteState nextByteState = getNextByteState(); if (nextByteState != null) { nextByteState.gatherObjects(objectSet, maxObjectCount); } } } @Override public ByteTransition clone() { try { return (ByteTransition) super.clone(); } catch (CloneNotSupportedException e) { return null; } } }
4,914
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/Finder.java
package software.amazon.event.ruler; import javax.annotation.concurrent.ThreadSafe; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import static software.amazon.event.ruler.SetOperations.intersection; /* * Notes on the implementation: * * This is finite-automaton based. The state machine matches field names exactly using a <String, String> * map in the NameState class. The value matching uses the "ByteMachine" class which, as its name suggests, * runs a different kind of state machine over the bytes in the String-valued fields. * * Trying to make moveTo() faster by keeping unused Step structs around turns out to make it * run slower. Let Java manage its memory. * * The Step processing could be done in parallel rather than sequentially; the use of a Queue for * Steps has this in mind. This could be done by having multiple threads reading * from the task queue. But it might be more straightforward to run multiple Finders in parallel. * In which case you might want to share the machine; perhaps either static or a singleton. * * In this class and the other internal classes, we use rule names of type Object while in GenericMachine the rule name * is of generic type T. This is safe as we only operate rule names of the same type T provided by a user. We use a * generic type for rule names in GenericMachine for convenience and to avoid explicit type casts. */ /** * Uses a state machine created by software.amazon.event.ruler.Machine to process tokens * representing key-value pairs in an event, and return any matching Rules. */ @ThreadSafe class Finder { private static final Patterns ABSENCE_PATTERN = Patterns.absencePatterns(); private Finder() { } /** * 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. * @param machine the compiled state machine * @return list of rule names that match. The list may be empty but never null. */ static List<Object> rulesForEvent(final String[] event, final GenericMachine<?> machine) { return find(new Task(event, machine)); } /** * 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. * @param machine the compiled state machine * @return list of rule names that match. The list may be empty but never null. */ static List<Object> rulesForEvent(final List<String> event, final GenericMachine<?> machine) { return find(new Task(event, machine)); } private static List<Object> find(final Task task) { // bootstrap the machine: Start state, first token NameState startState = task.startState(); if (startState == null) { return Collections.emptyList(); } moveFrom(null, startState, 0, task); // each iteration removes a Step and adds zero or more new ones while (task.stepsRemain()) { tryStep(task); } return task.getMatchedRules(); } // Move from a state. Give all the remaining tokens a chance to transition from it private static void moveFrom(final Set<Double> candidateSubRuleIdsForNextStep, final NameState nameState, final int tokenIndex, final Task task) { /* * The Name Matchers look for an [ { exists: false } ] match. They * will match if a particular key is not present * in the event. Hence, if the name state has any matches configured * for the [ { exists: false } ] case, we need to evaluate these * matches regardless. The fields in the event can be completely * disconnected from the fields configured for [ { exists: false } ], * and it does not matter if the current field is used in machine. * * Another possibility is that there can be a final state configured for * [ { exists: false } ] match. This state needs to be evaluated for a match * even if we have matched all the keys in the event. This is needed because * the final state can still be evaluated to true if the particular event * does not have the key configured for [ { exists: false } ]. */ tryNameMatching(candidateSubRuleIdsForNextStep, nameState, task, tokenIndex); // Add more steps using our new set of candidate sub-rules. for (int i = tokenIndex; i < task.event.length; i += 2) { if (task.isFieldUsed(task.event[i])) { task.addStep(new Step(i, nameState, candidateSubRuleIdsForNextStep)); } } } private static void moveFromWithPriorCandidates(final Set<Double> candidateSubRuleIds, final NameState fromState, final Patterns fromPattern, final int tokenIndex, final Task task) { Set<Double> candidateSubRuleIdsForNextStep = calculateCandidateSubRuleIdsForNextStep(candidateSubRuleIds, fromState, fromPattern); // If there are no more candidate sub-rules, there is no need to proceed further. if (candidateSubRuleIdsForNextStep != null && !candidateSubRuleIdsForNextStep.isEmpty()) { moveFrom(candidateSubRuleIdsForNextStep, fromState, tokenIndex, task); } } /** * Calculate the candidate sub-rule IDs for the next step. * * @param currentCandidateSubRuleIds The candidate sub-rule IDs for the current step. Use null to indicate that we * are on first step and so there are not yet any candidate sub-rules. * @param fromState The NameState we are transitioning from. * @param fromPattern The pattern we used to transition from fromState. * @return The set of candidate sub-rule IDs for the next step. Null means there are no candidates and thus, there * is no point to evaluating subsequent steps. */ private static Set<Double> calculateCandidateSubRuleIdsForNextStep(final Set<Double> currentCandidateSubRuleIds, final NameState fromState, final Patterns fromPattern) { // These are all the sub-rules that use the matched pattern to transition to the next NameState. Note that they // are not all candidates as they may have required different values for previously evaluated fields. Set<Double> subRuleIds = fromState.getNonTerminalSubRuleIdsForPattern(fromPattern); // If no sub-rules used the matched pattern to transition to the next NameState, then there are no matches to be // found by going further. if (subRuleIds == null) { return null; } // If there are no candidate sub-rules, this means we are on the first NameState and must initialize the // candidate sub-rules to those that used the matched pattern to transition to the next NameState. if (currentCandidateSubRuleIds == null || currentCandidateSubRuleIds.isEmpty()) { return subRuleIds; } // There are candidate sub-rules, so retain only those that used the matched pattern to transition to the next // NameState. Set<Double> candidateSubRuleIdsForNextStep = new HashSet<>(); intersection(subRuleIds, currentCandidateSubRuleIds, candidateSubRuleIdsForNextStep); return candidateSubRuleIdsForNextStep; } // remove a step from the work queue and see if there's a transition private static void tryStep(final Task task) { final Step step = task.nextStep(); tryValueMatching(task, step); } private static void tryValueMatching(final Task task, Step step) { if (step.keyIndex >= task.event.length) { return; } String value = task.event[step.keyIndex]; if (!task.isFieldUsed(value)) { return; } // if there are some possible value pattern matches for this key final ByteMachine valueMatcher = step.nameState.getTransitionOn(value); if (valueMatcher != null) { final int nextKeyIndex = step.keyIndex + 2; // loop through the value pattern matches for (NameStateWithPattern nextNameStateWithPattern : valueMatcher.transitionOn(task.event[step.keyIndex + 1])) { addNameState(step.candidateSubRuleIds, nextNameStateWithPattern.getNameState(), nextNameStateWithPattern.getPattern(), task, nextKeyIndex); } } } private static void tryNameMatching(final Set<Double> candidateSubRuleIds, final NameState nameState, final Task task, int keyIndex) { if (!nameState.hasKeyTransitions()) { return; } for (NameState nextNameState : nameState.getNameTransitions(task.event)) { if (nextNameState != null) { addNameState(candidateSubRuleIds, nextNameState, ABSENCE_PATTERN, task, keyIndex); } } } private static void addNameState(Set<Double> candidateSubRuleIds, NameState nameState, Patterns pattern, Task task, int nextKeyIndex) { // one of the matches might imply a rule match task.collectRules(candidateSubRuleIds, nameState, pattern); moveFromWithPriorCandidates(candidateSubRuleIds, nameState, pattern, nextKeyIndex, task); } }
4,915
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/JsonRuleCompiler.java
package software.amazon.event.ruler; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import software.amazon.event.ruler.input.ParseException; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import static software.amazon.event.ruler.input.DefaultParser.getParser; /** * Represents a updated compiler comparing to RuleCompiler class, it parses a rule described by a JSON string into * a list of Map which is composed of field Patterns, each Map represents one dedicated match branch in the rule. * By default, fields in the rule will be interpreted as "And" relationship implicitly and will result into one Map with * fields of Patterns, but once it comes across the "$or" relationship which is explicitly decorated by "$or" primitive * array, for each object in "$or" array, this Compiler will fork a new Map to include all fields of patterns in * that "or" branch, and when it goes over all branches in "$or" relationship, it will end up with the list of Map * and each Map represents a match branch composed of fields of patterns. * i.e.: a rule which describe the effect of ("source" AND ("metricName" OR ("metricType AND "namespace") OR "scope")) * its JSON format String is: * { * "source": [ "aws.cloudwatch" ], * "$or": [ * { "metricName": [ "CPUUtilization", "ReadLatency" ] }, * { * "metricType": [ "MetricType" ] , * "namespace": [ "AWS/EC2", "AWS/ES" ] * }, * { "scope": [ "Service" ] } * ] * } * It will be parsed to a list of match branches composed by a Map of fields patterns, e.g. for above rule, there will * result 3 match branches: * [ * {source=[\"aws.cloudwatch\"], metricName=[\"CPUUtilization\",\"ReadLatency\"]}, * {namespace=[\"AWS/EC2\", \"AWS/ES\"], metricType=[\"MetricType\"], source=[\"aws.cloudwatch\"]}, * {source=[\"aws.cloudwatch\"], scope=[\"Service\"]} * ] */ public class JsonRuleCompiler { private static final JsonFactory JSON_FACTORY = new JsonFactory(); private JsonRuleCompiler() { } /** * Verify the syntax of a rule * @param source rule, as a String * @return null if the rule is valid, otherwise an error message */ public static String check(final Reader source) { try { doCompile(JSON_FACTORY.createParser(source)); return null; } catch (Exception e) { return e.getLocalizedMessage(); } } public static String check(final String source) { try { doCompile(JSON_FACTORY.createParser(source)); return null; } catch (Exception e) { return e.getLocalizedMessage(); } } public static String check(final byte[] source) { try { doCompile(JSON_FACTORY.createParser(source)); return null; } catch (Exception e) { return e.getLocalizedMessage(); } } public static String check(final InputStream source) { try { doCompile(JSON_FACTORY.createParser(source)); return null; } catch (Exception e) { return e.getLocalizedMessage(); } } /** * Compile a rule from its JSON form to a Map suitable for use by event.ruler.Ruler (elements are surrounded by quotes). * * @param source rule, as a String * @return List of Sub rule which represented as Map * @throws IOException if the rule isn't syntactically valid */ public static List<Map<String, List<Patterns>>> compile(final Reader source) throws IOException { return doCompile(JSON_FACTORY.createParser(source)); } public static List<Map<String, List<Patterns>>> compile(final String source) throws IOException { return doCompile(JSON_FACTORY.createParser(source)); } public static List<Map<String, List<Patterns>>> compile(final byte[] source) throws IOException { return doCompile(JSON_FACTORY.createParser(source)); } public static List<Map<String, List<Patterns>>> compile(final InputStream source) throws IOException { return doCompile(JSON_FACTORY.createParser(source)); } private static List<Map<String, List<Patterns>>> doCompile(final JsonParser parser) throws IOException { final Path path = new Path(); final List<Map<String, List<Patterns>>> rules = new ArrayList<>(); if (parser.nextToken() != JsonToken.START_OBJECT) { barf(parser, "Filter is not an object"); } parseObject(rules, path, parser, true); parser.close(); return rules; } private static void parseObject(final List<Map<String, List<Patterns>>> rules, final Path path, final JsonParser parser, final boolean withQuotes) throws IOException { boolean fieldsPresent = false; while (parser.nextToken() != JsonToken.END_OBJECT) { fieldsPresent = true; // field name final String stepName = parser.getCurrentName(); // If it is "$or" primitive, we should bypass that primitive itself in the path as it is not // a real field name, it is just used to describe the "$or" relationship among object in the followed array. if (stepName.equals(Constants.OR_RELATIONSHIP_KEYWORD)) { parseIntoOrRelationship(rules, path, parser, withQuotes); // all Objects in $or array have been handled in above function, just bypass below logic. continue; } switch (parser.nextToken()) { case START_OBJECT: path.push(stepName); parseObject(rules, path, parser, withQuotes); path.pop(); break; case START_ARRAY: writeRules(rules, path.extendedName(stepName), parser, withQuotes); break; default: barf(parser, String.format("\"%s\" must be an object or an array", stepName)); } } if (!fieldsPresent) { barf(parser, "Empty objects are not allowed"); } } private static void parseObjectInsideOrRelationship(final List<Map<String, List<Patterns>>> rules, final Path path, final JsonParser parser, final boolean withQuotes) throws IOException { boolean fieldsPresent = false; while (parser.nextToken() != JsonToken.END_OBJECT) { fieldsPresent = true; // field name final String stepName = parser.getCurrentName(); // If it is "$or" primitive, we should bypass the "$or" primitive itself in the path as it is not // a real step name, it is just used to describe the "$or" relationship among object in the followed Array. if (stepName.equals(Constants.OR_RELATIONSHIP_KEYWORD)) { parseIntoOrRelationship(rules, path, parser, withQuotes); continue; } if (Constants.RESERVED_FIELD_NAMES_IN_OR_RELATIONSHIP.contains(stepName)) { barf(parser, stepName + " is Ruler reserved fieldName which cannot be used inside " + Constants.OR_RELATIONSHIP_KEYWORD + "."); } switch (parser.nextToken()) { case START_OBJECT: path.push(stepName); parseObjectInsideOrRelationship(rules, path, parser, withQuotes); path.pop(); break; case START_ARRAY: writeRules(rules, path.extendedName(stepName), parser, withQuotes); break; default: barf(parser, String.format("\"%s\" must be an object or an array", stepName)); } } if (!fieldsPresent) { barf(parser, "Empty objects are not allowed"); } } /** * This function is to parse the "$or" relationship described as an array, each object in the array will be * interpreted as "$or" relationship, for example: * { * "detail": { * "$or" : [ * {"c-count": [ { "numeric": [ ">", 0, "<=", 5 ] } ]}, * {"d-count": [ { "numeric": [ "<", 10 ] } ]}, * {"x-limit": [ { "numeric": [ "=", 3.018e2 ] } ]} * ] * } * } * above rule will be interpreted as or effect: ("detail.c-count" || "detail.d-count" || detail.x-limit"), * The result will be described as the list of Map, each Map represents a sub rule composed of fields of patterns in * that or condition path, for example: * [ * {detail.c-count=[38D7EA4C68000/38D7EA512CB40:true/false]}, * {detail.d-count=[0000000000000/38D7EA55F1680:false/true]}, * {detail.x-limit=[VP:38D7EB6C39A40]} * ] * This List will be added into Ruler with the same rule name to demonstrate the "or" effects inside Ruler state * machine. */ private static void parseIntoOrRelationship(final List<Map<String, List<Patterns>>> rules, final Path path, final JsonParser parser, final boolean withQuotes) throws IOException { final List<Map<String, List<Patterns>>> currentRules = deepCopyRules(rules); rules.clear(); JsonToken token = parser.nextToken(); if (token != JsonToken.START_ARRAY) { barf(parser, "It must be an Array followed with " + Constants.OR_RELATIONSHIP_KEYWORD + "."); } int loopCnt = 0; while ((token = parser.nextToken()) != JsonToken.END_ARRAY) { loopCnt++; if (token == JsonToken.START_OBJECT) { final List<Map<String, List<Patterns>>> newRules = deepCopyRules(currentRules); if (newRules.isEmpty()) { newRules.add(new HashMap<>()); } parseObjectInsideOrRelationship(newRules, path, parser, withQuotes); rules.addAll(newRules); } else { barf(parser, "Only JSON object is allowed in array of " + Constants.OR_RELATIONSHIP_KEYWORD + " relationship."); } } if (loopCnt < 2) { barf(parser, "There must have at least 2 Objects in " + Constants.OR_RELATIONSHIP_KEYWORD + " relationship."); } } // This is not exactly the real deep copy because here we only need deep copy at List element level, private static List deepCopyRules(final List<Map<String, List<Patterns>>> rules) { return rules.stream().map(rule -> new HashMap(rule)).collect(Collectors.toList()); } private static void writeRules(final List<Map<String, List<Patterns>>> rules, final String name, final JsonParser parser, final boolean withQuotes) throws IOException { JsonToken token; final List<Patterns> values = new ArrayList<>(); while ((token = parser.nextToken()) != JsonToken.END_ARRAY) { switch (token) { case START_OBJECT: values.add(processMatchExpression(parser)); break; case VALUE_STRING: final String toMatch = parser.getText(); final Range ipRange = CIDR.ipToRangeIfPossible(toMatch); if (ipRange != null) { values.add(ipRange); } else if (withQuotes) { values.add(Patterns.exactMatch('"' + toMatch + '"')); } else { values.add(Patterns.exactMatch(toMatch)); } break; case VALUE_NUMBER_FLOAT: case VALUE_NUMBER_INT: /* * If the rule specifies a match to a number, we'll insert matchers for both the * literal expression and the ComparableNumber form. But the number might not * be representable as a ComparableNumber, for example an AWS account number, * so make that condition survivable. */ try { values.add(Patterns.numericEquals(parser.getDoubleValue())); } catch (Exception e) { // no-op } values.add(Patterns.exactMatch(parser.getText())); break; case VALUE_NULL: case VALUE_TRUE: case VALUE_FALSE: values.add(Patterns.exactMatch(parser.getText())); break; default: barf(parser, "Match value must be String, number, true, false, or null"); } } if (values.isEmpty()) { barf(parser, "Empty arrays are not allowed"); } // If the rules list is empty, add the first rule if (rules.isEmpty()) { rules.add(new HashMap<>()); } rules.forEach(rule -> rule.put(name, values)); } // Used to be, the format was // "field-name": [ "val1", "val2" ] // now it's like // "field-name": [ "val1", { "prefix": "pref1" }, { "anything-but": "not-this" } ] // private static Patterns processMatchExpression(final JsonParser parser) throws IOException { final JsonToken matchTypeToken = parser.nextToken(); if (matchTypeToken != JsonToken.FIELD_NAME) { barf(parser, "Match expression name not found"); } final String matchTypeName = parser.getCurrentName(); if (Constants.EXACT_MATCH.equals(matchTypeName)) { final JsonToken prefixToken = parser.nextToken(); if (prefixToken != JsonToken.VALUE_STRING) { barf(parser, "exact match pattern must be a string"); } final Patterns pattern = Patterns.exactMatch('"' + parser.getText() + '"'); if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return pattern; } else if (Constants.PREFIX_MATCH.equals(matchTypeName)) { final JsonToken prefixToken = parser.nextToken(); if (prefixToken == JsonToken.START_OBJECT) { return processPrefixEqualsIgnoreCaseExpression(parser); } if (prefixToken != JsonToken.VALUE_STRING) { barf(parser, "prefix match pattern must be a string"); } final Patterns pattern = Patterns.prefixMatch('"' + parser.getText()); // note no trailing quote if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return pattern; } else if (Constants.SUFFIX_MATCH.equals(matchTypeName)) { final JsonToken suffixToken = parser.nextToken(); if (suffixToken == JsonToken.START_OBJECT) { return processSuffixEqualsIgnoreCaseExpression(parser); } if (suffixToken != JsonToken.VALUE_STRING) { barf(parser, "suffix match pattern must be a string"); } final Patterns pattern = Patterns.suffixMatch(parser.getText() + '"'); // note no beginning quote if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return pattern; } else if (Constants.NUMERIC.equals(matchTypeName)) { final JsonToken numericalExpressionToken = parser.nextToken(); if (numericalExpressionToken != JsonToken.START_ARRAY) { barf(parser, "Value of " + Constants.NUMERIC + " must be an array."); } Patterns range = processNumericMatchExpression(parser); if (parser.nextToken() != JsonToken.END_OBJECT) { tooManyElements(parser); } return range; } else if (Constants.ANYTHING_BUT_MATCH.equals(matchTypeName)) { boolean isIgnoreCase = false; JsonToken anythingButExpressionToken = parser.nextToken(); if (anythingButExpressionToken == JsonToken.START_OBJECT) { // there are a limited set of things we can apply Anything-But to final JsonToken anythingButObject = parser.nextToken(); if (anythingButObject != JsonToken.FIELD_NAME) { barf(parser, "Anything-But expression name not found"); } final String anythingButObjectOp = parser.getCurrentName(); final boolean isPrefix = Constants.PREFIX_MATCH.equals(anythingButObjectOp); final boolean isSuffix = Constants.SUFFIX_MATCH.equals(anythingButObjectOp); isIgnoreCase = Constants.EQUALS_IGNORE_CASE.equals(anythingButObjectOp); if(!isIgnoreCase) { if (!isPrefix && !isSuffix) { barf(parser, "Unsupported anything-but pattern: " + anythingButObjectOp); } final JsonToken anythingButParamType = parser.nextToken(); if (anythingButParamType != JsonToken.VALUE_STRING) { barf(parser, "prefix/suffix match pattern must be a string"); } final String text = parser.getText(); if (text.isEmpty()) { barf(parser, "Null prefix/suffix not allowed"); } if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } if(isPrefix) { return Patterns.anythingButPrefix('"' + text); // note no trailing quote } else { return Patterns.anythingButSuffix(text + '"'); // note no leading quote } } else { // Step into anything-but's equals-ignore-case anythingButExpressionToken = parser.nextToken(); } } if (anythingButExpressionToken != JsonToken.START_ARRAY && anythingButExpressionToken != JsonToken.VALUE_STRING && anythingButExpressionToken != JsonToken.VALUE_NUMBER_FLOAT && anythingButExpressionToken != JsonToken.VALUE_NUMBER_INT) { barf(parser, "Value of " + Constants.ANYTHING_BUT_MATCH + " must be an array or single string/number value."); } Patterns anythingBut; if (anythingButExpressionToken == JsonToken.START_ARRAY) { if(isIgnoreCase) { anythingBut = processAnythingButEqualsIgnoreCaseListMatchExpression(parser); } else { anythingBut = processAnythingButListMatchExpression(parser); } } else { if(isIgnoreCase) { anythingBut = processAnythingButEqualsIgnoreCaseMatchExpression(parser, anythingButExpressionToken); } else { anythingBut = processAnythingButMatchExpression(parser, anythingButExpressionToken); } } if (parser.nextToken() != JsonToken.END_OBJECT) { tooManyElements(parser); } // Complete the object closure for equals-ignore-case if (isIgnoreCase && parser.nextToken() != JsonToken.END_OBJECT) { tooManyElements(parser); } return anythingBut; } else if (Constants.EXISTS_MATCH.equals(matchTypeName)) { return processExistsExpression(parser); } else if (Constants.CIDR.equals(matchTypeName)) { final JsonToken cidrToken = parser.nextToken(); if (cidrToken != JsonToken.VALUE_STRING) { barf(parser, "prefix match pattern must be a string"); } final Range cidr = CIDR.cidr(parser.getText()); if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return cidr; } else if (Constants.EQUALS_IGNORE_CASE.equals(matchTypeName)) { final JsonToken equalsIgnoreCaseToken = parser.nextToken(); if (equalsIgnoreCaseToken != JsonToken.VALUE_STRING) { barf(parser, "equals-ignore-case match pattern must be a string"); } final Patterns pattern = Patterns.equalsIgnoreCaseMatch('"' + parser.getText() + '"'); if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return pattern; } else if (Constants.WILDCARD.equals(matchTypeName)) { final JsonToken wildcardToken = parser.nextToken(); if (wildcardToken != JsonToken.VALUE_STRING) { barf(parser, "wildcard match pattern must be a string"); } final String parserText = parser.getText(); String value = '"' + parserText + '"'; try { getParser().parse(MatchType.WILDCARD, value); } catch (ParseException e) { barf(parser, e.getLocalizedMessage()); } final Patterns pattern = Patterns.wildcardMatch(value); if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return pattern; } else { barf(parser, "Unrecognized match type " + matchTypeName); return null; // unreachable statement, but java can't see that? } } private static Patterns processPrefixEqualsIgnoreCaseExpression(final JsonParser parser) throws IOException { final JsonToken prefixObject = parser.nextToken(); if (prefixObject != JsonToken.FIELD_NAME) { barf(parser, "Prefix expression name not found"); } final String prefixObjectOp = parser.getCurrentName(); if (!Constants.EQUALS_IGNORE_CASE.equals(prefixObjectOp)) { barf(parser, "Unsupported prefix pattern: " + prefixObjectOp); } final JsonToken prefixEqualsIgnoreCase = parser.nextToken(); if (prefixEqualsIgnoreCase != JsonToken.VALUE_STRING) { barf(parser, "equals-ignore-case match pattern must be a string"); } final Patterns pattern = Patterns.prefixEqualsIgnoreCaseMatch('"' + parser.getText()); if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return pattern; } private static Patterns processSuffixEqualsIgnoreCaseExpression(final JsonParser parser) throws IOException { final JsonToken suffixObject = parser.nextToken(); if (suffixObject != JsonToken.FIELD_NAME) { barf(parser, "Suffix expression name not found"); } final String suffixObjectOp = parser.getCurrentName(); if (!Constants.EQUALS_IGNORE_CASE.equals(suffixObjectOp)) { barf(parser, "Unsupported suffix pattern: " + suffixObjectOp); } final JsonToken suffixEqualsIgnoreCase = parser.nextToken(); if (suffixEqualsIgnoreCase != JsonToken.VALUE_STRING) { barf(parser, "equals-ignore-case match pattern must be a string"); } final Patterns pattern = Patterns.suffixEqualsIgnoreCaseMatch(parser.getText() + '"'); if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); } return pattern; } private static Patterns processAnythingButListMatchExpression(JsonParser parser) throws JsonParseException { JsonToken token; Set<String> values = new HashSet<>(); boolean hasNumber = false; boolean hasString = false; try { while ((token = parser.nextToken()) != JsonToken.END_ARRAY) { switch (token) { case VALUE_STRING: values.add('"' + parser.getText() + '"'); hasString = true; break; case VALUE_NUMBER_FLOAT: case VALUE_NUMBER_INT: values.add(ComparableNumber.generate(parser.getDoubleValue())); hasNumber = true; break; default: barf(parser, "Inside anything but list, start|null|boolean is not supported."); } } } catch (IllegalArgumentException | IOException e) { barf(parser, e.getMessage()); } if ((hasNumber && hasString) || (!hasNumber && !hasString)) { barf(parser, "Inside anything but list, either all values are number or string, " + "mixed type is not supported"); } return AnythingBut.anythingButMatch(values, hasNumber); } private static Patterns processAnythingButEqualsIgnoreCaseListMatchExpression(JsonParser parser) throws JsonParseException { JsonToken token; Set<String> values = new HashSet<>(); boolean hasNumber = false; try { while ((token = parser.nextToken()) != JsonToken.END_ARRAY) { switch (token) { case VALUE_STRING: values.add('"' + parser.getText() + '"'); break; default: barf(parser, "Inside anything-but/equals-ignore-case list, number|start|null|boolean is not supported."); } } } catch (IllegalArgumentException | IOException e) { barf(parser, e.getMessage()); } return AnythingButEqualsIgnoreCase.anythingButIgnoreCaseMatch(values); } private static Patterns processAnythingButMatchExpression(JsonParser parser, JsonToken anythingButExpressionToken) throws IOException { Set<String> values = new HashSet<>(); boolean hasNumber = false; switch (anythingButExpressionToken) { case VALUE_STRING: values.add('"' + parser.getText() + '"'); break; case VALUE_NUMBER_FLOAT: case VALUE_NUMBER_INT: values.add(ComparableNumber.generate(parser.getDoubleValue())); hasNumber = true; break; default: barf(parser, "Inside anything-but list, start|null|boolean is not supported."); } return AnythingBut.anythingButMatch(values, hasNumber); } private static Patterns processAnythingButEqualsIgnoreCaseMatchExpression(JsonParser parser, JsonToken anythingButExpressionToken) throws IOException { Set<String> values = new HashSet<>(); switch (anythingButExpressionToken) { case VALUE_STRING: values.add('"' + parser.getText() + '"'); break; default: barf(parser, "Inside anything-but/equals-ignore-case list, number|start|null|boolean is not supported."); } return AnythingButEqualsIgnoreCase.anythingButIgnoreCaseMatch(values); } private static Patterns processNumericMatchExpression(final JsonParser parser) throws IOException { JsonToken token = parser.nextToken(); if (token != JsonToken.VALUE_STRING) { barf(parser, "Invalid member in numeric match: " + parser.getText()); } String operator = parser.getText(); token = parser.nextToken(); try { if (Constants.EQ.equals(operator)) { if (!token.isNumeric()) { barf(parser, "Value of equals must be numeric"); } final double val = parser.getDoubleValue(); if (parser.nextToken() != JsonToken.END_ARRAY) { tooManyElements(parser); } return Patterns.numericEquals(val); } else if (Constants.GE.equals(operator)) { if (!token.isNumeric()) { barf(parser, "Value of >= must be numeric"); } final double val = parser.getDoubleValue(); token = parser.nextToken(); if (token == JsonToken.END_ARRAY) { return Range.greaterThanOrEqualTo(val); } return completeNumericRange(parser, token, val, false); } else if (Constants.GT.equals(operator)) { if (!token.isNumeric()) { barf(parser, "Value of > must be numeric"); } final double val = parser.getDoubleValue(); token = parser.nextToken(); if (token == JsonToken.END_ARRAY) { return Range.greaterThan(val); } return completeNumericRange(parser, token, val, true); } else if (Constants.LE.equals(operator)) { if (!token.isNumeric()) { barf(parser, "Value of <= must be numeric"); } final double top = parser.getDoubleValue(); if (parser.nextToken() != JsonToken.END_ARRAY) { tooManyElements(parser); } return Range.lessThanOrEqualTo(top); } else if (Constants.LT.equals(operator)) { if (!token.isNumeric()) { barf(parser, "Value of < must be numeric"); } final double top = parser.getDoubleValue(); if (parser.nextToken() != JsonToken.END_ARRAY) { tooManyElements(parser); } return Range.lessThan(top); } else { barf(parser, "Unrecognized numeric range operator: " + operator); } } catch (IllegalArgumentException e) { barf(parser, e.getMessage()); } barf(parser, "Reached a line which is supposed completely unreachable."); return null; // completely unreachable } private static Patterns completeNumericRange(final JsonParser parser, final JsonToken token, final double bottom, final boolean openBottom) throws IOException { if (token != JsonToken.VALUE_STRING) { barf(parser, "Bad value in numeric range: " + parser.getText()); } final String operator = parser.getText(); boolean openTop = false; if (Constants.LT.equals(operator)) { openTop = true; } else if (!Constants.LE.equals(operator)) { barf(parser, "Bad numeric range operator: " + operator); } if (!parser.nextToken().isNumeric()) { barf(parser, "Value of " + operator + " must be numeric"); } final double top = parser.getDoubleValue(); if (parser.nextToken() != JsonToken.END_ARRAY) { barf(parser, "Too many terms in numeric range expression"); } return Range.between(bottom, openBottom, top, openTop); } private static Patterns processExistsExpression(final JsonParser parser) throws IOException { final JsonToken existsToken = parser.nextToken(); Patterns existsPattern; if (existsToken == JsonToken.VALUE_TRUE) { existsPattern = Patterns.existencePatterns(); } else if (existsToken == JsonToken.VALUE_FALSE) { existsPattern = Patterns.absencePatterns(); } else { barf(parser, "exists match pattern must be either true or false."); return null; } if (parser.nextToken() != JsonToken.END_OBJECT) { barf(parser, "Only one key allowed in match expression"); return null; } return existsPattern; } private static void tooManyElements(final JsonParser parser) throws JsonParseException { barf(parser, "Too many elements in numeric expression"); } private static void barf(final JsonParser parser, final String message) throws JsonParseException { throw new JsonParseException(parser, message, parser.getCurrentLocation()); } }
4,916
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/ValuePatterns.java
package software.amazon.event.ruler; import java.util.Objects; /** * The ValuePatterns deal with matching a single value. The single value * is specified with the variable pattern. */ public class ValuePatterns extends Patterns { private final String pattern; ValuePatterns(final MatchType type, final String pattern) { super(type); this.pattern = pattern; } public String pattern() { return pattern; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || !o.getClass().equals(getClass())) { return false; } if (!super.equals(o)) { return false; } ValuePatterns that = (ValuePatterns) o; return Objects.equals(pattern, that.pattern); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (pattern != null ? pattern.hashCode() : 0); return result; } @Override public String toString() { return "VP:" + pattern + " (" + super.toString() + ")"; } }
4,917
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/Path.java
package software.amazon.event.ruler; import java.util.ArrayDeque; import java.util.Deque; /** * Represents the current location in a traversal of a JSON object. * Both rules and events need to be flattened into name/value pairs, where the name represents the path to the * object. */ class Path { private final static char SEPARATOR = '.'; private final Deque<String> path = new ArrayDeque<>(); // memo-ize private String memo = null; void push(final String s) { memo = null; path.add(s); } String pop() { memo = null; // in principle could remove null return path.removeLast(); } /** * return the pathname as a .-separated string. * This turns out to be a performance bottleneck so it's memoized and uses StringBuilder rather than StringJoiner. * @return the pathname */ String name() { if (memo == null) { final Object[] steps = path.toArray(); if (steps.length == 0) { memo = ""; } else { final StringBuilder sb = new StringBuilder(); sb.append(steps[0]); for (int i = 1; i < steps.length; i++) { sb.append(SEPARATOR).append(steps[i]); } memo = sb.toString(); } } return memo; } /** * return the pathname as a segmented-string with the indicated separator * @param lastStep The next step, which we want to use but not to push on to the path * @return the pathname */ String extendedName(final String lastStep) { String base = name(); if (!base.isEmpty()) { base += SEPARATOR; } return base + lastStep; } }
4,918
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/Constants.java
package software.amazon.event.ruler; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; final class Constants { private Constants() { throw new UnsupportedOperationException("You can't create instance of utility class."); } final static String EXACT_MATCH = "exactly"; final static String EQUALS_IGNORE_CASE = "equals-ignore-case"; final static String PREFIX_MATCH = "prefix"; final static String SUFFIX_MATCH = "suffix"; final static String ANYTHING_BUT_MATCH = "anything-but"; final static String EXISTS_MATCH = "exists"; final static String WILDCARD = "wildcard"; final static String NUMERIC = "numeric"; final static String CIDR = "cidr"; // This is Ruler reserved words to represent the $or relationship among the fields. final static String OR_RELATIONSHIP_KEYWORD = "$or"; final static String EQ = "="; final static String LT = "<"; final static String LE = "<="; final static String GT = ">"; final static String GE = ">="; // Use scientific notation to define the double number directly to avoid losing Precision by calculation // for example 5000 * 1000 *1000 will be wrongly parsed as 7.05032704E8 by computer. final static double FIVE_BILLION = 5E9; final static Pattern IPv4_REGEX = Pattern.compile("[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+"); final static Pattern IPv6_REGEX = Pattern.compile("[0-9a-fA-F:]*:[0-9a-fA-F:]*"); final static byte[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; final static byte MAX_DIGIT = 'F'; final static List<String> RESERVED_FIELD_NAMES_IN_OR_RELATIONSHIP = Arrays.asList( EXACT_MATCH, EQUALS_IGNORE_CASE, PREFIX_MATCH, SUFFIX_MATCH, ANYTHING_BUT_MATCH, EXISTS_MATCH, WILDCARD, NUMERIC, CIDR, // Numeric comparisons EQ, LT, LE, GT, GE, // reserve below keywords for future extension "regex", // String Comparisons "not-wildcard", "not-equals-ignore-case", // Date/Time comparisons "date-after", "date-on-or-after", "date-before", "date-on-or-before", "in-date-range", // IP Address Comparison "ip-address-in-range", "ip-address-not-in-range" ); }
4,919
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/ByteMap.java
package software.amazon.event.ruler; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.NavigableMap; import java.util.Set; import java.util.TreeMap; import static software.amazon.event.ruler.CompoundByteTransition.coalesce; /** * Maps byte values to ByteTransitions. Designed to perform well given the constraints that most ByteStates will have a * very small number of transitions, and that for support of wildcards and regexes, we need to efficiently represent the * condition where wide ranges of byte values (including *all* of them) will transition to a common next ByteState. */ class ByteMap { /* * Each map entry represents one or more byte values that share a transition. Null means no transition. The key is a * single integer which is the ceiling value; all byte values below that and greater than or equal to the floor * value map to the associated transition or null. The floor value for any transition is the ceiling from the * previous entry, or zero for the zeroth entry in the map. */ private volatile NavigableMap<Integer, ByteTransition> map = new TreeMap<>(); ByteMap() { map.put(256, null); } void putTransition(final byte utf8byte, final SingleByteTransition transition) { updateTransition(utf8byte, transition, Operation.PUT); } void putTransitionForAllBytes(final SingleByteTransition transition) { NavigableMap<Integer, ByteTransition> newMap = new TreeMap<>(); newMap.put(256, transition); map = newMap; } void addTransition(final byte utf8byte, final SingleByteTransition transition) { updateTransition(utf8byte, transition, Operation.ADD); } void addTransitionForAllBytes(final SingleByteTransition transition) { NavigableMap<Integer, ByteTransition> newMap = new TreeMap<>(map); for (Map.Entry<Integer, ByteTransition> entry : newMap.entrySet()) { Set<SingleByteTransition> newSingles = new HashSet<>(); ByteTransition storedTransition = entry.getValue(); expand(storedTransition).forEach(single -> newSingles.add(single)); newSingles.add(transition); entry.setValue(coalesce(newSingles)); } map = newMap; } void removeTransition(final byte utf8byte, final SingleByteTransition transition) { updateTransition(utf8byte, transition, Operation.REMOVE); } void removeTransitionForAllBytes(final SingleByteTransition transition) { NavigableMap<Integer, ByteTransition> newMap = new TreeMap<>(map); for (Map.Entry<Integer, ByteTransition> entry : newMap.entrySet()) { Set<SingleByteTransition> newSingles = new HashSet<>(); ByteTransition storedTransition = entry.getValue(); expand(storedTransition).forEach(single -> newSingles.add(single)); newSingles.remove(transition); entry.setValue(coalesce(newSingles)); } map = newMap; } /** * Updates one ceiling=>transition mapping and leaves the map in a consistent state. We go through the map and find * the entry that contains the byte value. If the new byte value is not at the bottom of the entry, we write a new * entry representing the part of the entry less than the byte value. Then we write a new entry for the byte value. * Then we merge entries mapping to the same transition. */ private void updateTransition(final byte utf8byte, final SingleByteTransition transition, Operation operation) { final int index = utf8byte & 0xFF; ByteTransition target = map.higherEntry(index).getValue(); ByteTransition coalesced; if (operation == Operation.PUT) { coalesced = coalesce(transition); } else { Iterable<SingleByteTransition> targetIterable = expand(target); if (!targetIterable.iterator().hasNext()) { coalesced = operation == Operation.ADD ? coalesce(transition) : null; } else { Set<SingleByteTransition> singles = new HashSet<>(); targetIterable.forEach(single -> singles.add(single)); if (operation == Operation.ADD) { singles.add(transition); } else { singles.remove(transition); } coalesced = coalesce(singles); } } final boolean atBottom = index == 0 || map.containsKey(index); if (!atBottom) { map.put(index, target); } map.put(index + 1, coalesced); // Merge adjacent mappings with the same transition. mergeAdjacentInMapIfNeeded(map); } /** * Merge adjacent entries with equal transitions in inputMap. * * @param inputMap The map on which we merge adjacent entries with equal transitions. */ private static void mergeAdjacentInMapIfNeeded(final NavigableMap<Integer, ByteTransition> inputMap) { Iterator<Map.Entry<Integer, ByteTransition>> iterator = inputMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Integer, ByteTransition> next1 = iterator.next(); Map.Entry<Integer, ByteTransition> next2 = inputMap.higherEntry(next1.getKey()); if (next2 != null && expand(next1.getValue()).equals(expand(next2.getValue()))) { iterator.remove(); } } } boolean isEmpty() { return numberOfTransitions() == 0; } int numberOfTransitions() { return getSingleByteTransitions().size(); } boolean hasTransition(final ByteTransition transition) { return getSingleByteTransitions().contains(transition); } ByteTransition getTransition(final byte utf8byte) { return map.higherEntry(utf8byte & 0xFF).getValue(); } /** * Get the transition that all bytes lead to. Could be compound if all bytes lead to more than one transition, or * could be the empty transition if there are no transitions that all bytes lead to. * * @return The transition that all bytes lead to. */ ByteTransition getTransitionForAllBytes() { Set<SingleByteTransition> candidates = new HashSet<>(); Iterator<ByteTransition> iterator = map.values().iterator(); ByteTransition firstByteTransition = iterator.next(); if (firstByteTransition == null) { return ByteMachine.EmptyByteTransition.INSTANCE; } firstByteTransition.expand().forEach(single -> candidates.add(single)); while (iterator.hasNext()) { ByteTransition nextByteTransition = iterator.next(); if (nextByteTransition == null) { return ByteMachine.EmptyByteTransition.INSTANCE; } Iterable<SingleByteTransition> singles = nextByteTransition.expand(); if (singles instanceof Set) { candidates.retainAll((Set) singles); } else if (singles instanceof SingleByteTransition) { SingleByteTransition single = (SingleByteTransition) singles; if (candidates.contains(single)) { if (candidates.size() > 1) { candidates.clear(); candidates.add(single); } } else { if (!candidates.isEmpty()) { candidates.clear(); } } } else { // singles should always be a Set or SingleByteTransition. Thus, this "else" is expected to be dead code // but it is here for logical correctness if anything changes in the future. Set<SingleByteTransition> set = new HashSet<>(); singles.forEach(single -> set.add(single)); candidates.retainAll(set); } if (candidates.isEmpty()) { return ByteMachine.EmptyByteTransition.INSTANCE; } } return coalesce(candidates); } /** * Get all transitions contained in this map, whether they are single or compound transitions. * * @return All transitions contained in this map. */ Set<ByteTransition> getTransitions() { Set<ByteTransition> result = new HashSet<>(map.values().size()); for (ByteTransition transition : map.values()) { if (transition != null) { result.add(transition); } } return result; } /** * Get the ceiling values contained in this map. * * @return Ceiling values. */ Set<Integer> getCeilings() { return map.keySet(); } /** * Get all transitions contained in this map, with the compound transitions expanded to singular form. * * @return All transitions contained in this map, with the compound transitions expanded to singular form. */ private Set<SingleByteTransition> getSingleByteTransitions() { Set<SingleByteTransition> allTransitions = new HashSet<>(); for (ByteTransition transition : map.values()) { if (transition != null) { expand(transition).forEach(single -> allTransitions.add(single)); } } return allTransitions; } private static Iterable<SingleByteTransition> expand(ByteTransition transition) { if (transition == null) { return Collections.EMPTY_SET; } return transition.expand(); } // for testing NavigableMap<Integer, ByteTransition> getMap() { return map; } @Override public String toString() { final NavigableMap<Integer, ByteTransition> thisMap = map; StringBuilder sb = new StringBuilder(); int floor = 0; for (Map.Entry<Integer, ByteTransition> entry : thisMap.entrySet()) { int ceiling = entry.getKey(); ByteTransition transition = entry.getValue(); for (int j = (char) floor; j < ceiling; j++) { StringBuilder targets = new StringBuilder(); for (ByteTransition trans : expand(transition)) { String target = trans.getClass().getName(); target = target.substring(target.lastIndexOf('.') + 1) + "/" + trans.hashCode(); targets.append(target + ","); } if (targets.length() > 0) { targets.deleteCharAt(targets.length() - 1); sb.append((char) j).append("->").append(targets).append(" // "); } } floor = ceiling; } return sb.toString(); } private enum Operation { ADD, PUT, REMOVE } }
4,920
0
Create_ds/event-ruler/src/main/software/amazon/event
Create_ds/event-ruler/src/main/software/amazon/event/ruler/SingleByteTransition.java
package software.amazon.event.ruler; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; /** * This class represents a singular ByteTransition. This is in contrast to a compound ByteTransition that represents * having taken multiple distinct transitions simultaneously (i.e. for NFA traversal). */ abstract class SingleByteTransition extends ByteTransition implements Iterable { /** * Returns the match that is triggered if this transition is made. * * @return the match, or {@code null} if this transition does not support matching */ abstract ByteMatch getMatch(); /** * Sets the match. The method returns this or a new transition that contains the given match if the match is not * {@code null}. Otherwise, the method returns {@code null} or a new transition that does not * support matching. * * @param match the match * @return this or a new transition that contains the given match if the match is not {@code null}; otherwise, * {@code null} or a new transition that does not support matching */ abstract SingleByteTransition setMatch(ByteMatch match); /** * Get the transition that all bytes lead to. Could be compound if all bytes lead to more than one single * transition, or could be the empty transition if there are no transitions that all bytes lead to. * * @return The transition that all bytes lead to. */ abstract ByteTransition getTransitionForAllBytes(); @Override Iterable<ByteMatch> getMatches() { ByteMatch match = getMatch(); if (match == null) { return Collections.emptySet(); } return match; } /** * Get all transitions represented by this transition, which is simply this as this is a single byte transition. * * @return An iterable of all transitions represented by this transition. */ @Override Iterable<SingleByteTransition> expand() { return this; } @Override public Iterator<SingleByteTransition> iterator() { return new Iterator<SingleByteTransition>() { private boolean hasNext = true; @Override public boolean hasNext() { return hasNext; } @Override public SingleByteTransition next() { if (!hasNext) { throw new NoSuchElementException(); } hasNext = false; return SingleByteTransition.this; } }; } @Override ByteTransition getTransitionForNextByteStates() { return getNextByteState(); } public void gatherObjects(Set<Object> objectSet, int maxObjectCount) { if (!objectSet.contains(this) && objectSet.size() < maxObjectCount) { // stops looping objectSet.add(this); final ByteMatch match = getMatch(); if (match != null) { match.gatherObjects(objectSet, maxObjectCount); } for (ByteTransition transition : getTransitions()) { transition.gatherObjects(objectSet, maxObjectCount); } final ByteTransition nextByteStates = getTransitionForNextByteStates(); if (nextByteStates != null) { nextByteStates.gatherObjects(objectSet, maxObjectCount); } } } }
4,921
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/InputByte.java
package software.amazon.event.ruler.input; import java.nio.charset.StandardCharsets; import static software.amazon.event.ruler.input.InputCharacterType.BYTE; /** * An InputCharacter that represents a single byte. */ public class InputByte extends InputCharacter { private final byte b; InputByte(final byte b) { this.b = b; } public static InputByte cast(InputCharacter character) { return (InputByte) character; } public byte getByte() { return b; } @Override public InputCharacterType getType() { return BYTE; } @Override public boolean equals(Object o) { if (o == null || !(o.getClass() == getClass())) { return false; } return ((InputByte) o).getByte() == getByte(); } @Override public int hashCode() { return Byte.valueOf(b).hashCode(); } @Override public String toString() { return new String(new byte[] { getByte() }, StandardCharsets.UTF_8); } }
4,922
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/InputCharacter.java
package software.amazon.event.ruler.input; public abstract class InputCharacter { public abstract InputCharacterType getType(); }
4,923
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/ByteParser.java
package software.amazon.event.ruler.input; /** * Transforms UTF-8 formatted bytes into InputCharacter * * @see InputCharacter * */ public interface ByteParser { /** * @param utf8byte byte that represent in UTF-8 encoding * @return processed and parsed Input Character */ InputCharacter parse(byte utf8byte); }
4,924
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/InputWildcard.java
package software.amazon.event.ruler.input; import static software.amazon.event.ruler.input.InputCharacterType.WILDCARD; /** * An InputCharacter that represents a wildcard. */ public class InputWildcard extends InputCharacter { InputWildcard() { } @Override public InputCharacterType getType() { return WILDCARD; } @Override public boolean equals(Object o) { return o != null && o.getClass() == getClass(); } @Override public int hashCode() { return InputWildcard.class.hashCode(); } @Override public String toString() { return "Wildcard"; } }
4,925
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/StringValueParser.java
package software.amazon.event.ruler.input; public interface StringValueParser { /** * @param value string value to parse * @return processed and parsed Input Character */ InputCharacter[] parse(String value); }
4,926
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/ParseException.java
package software.amazon.event.ruler.input; /** * A RuntimeException that indicates an error parsing a rule's value. */ public class ParseException extends RuntimeException { public ParseException(String msg) { super(msg); } }
4,927
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/DefaultParser.java
package software.amazon.event.ruler.input; import software.amazon.event.ruler.MatchType; import java.nio.charset.StandardCharsets; import static software.amazon.event.ruler.MatchType.ANYTHING_BUT_SUFFIX; import static software.amazon.event.ruler.MatchType.EQUALS_IGNORE_CASE; import static software.amazon.event.ruler.MatchType.ANYTHING_BUT_IGNORE_CASE; import static software.amazon.event.ruler.MatchType.PREFIX_EQUALS_IGNORE_CASE; import static software.amazon.event.ruler.MatchType.SUFFIX; import static software.amazon.event.ruler.MatchType.SUFFIX_EQUALS_IGNORE_CASE; import static software.amazon.event.ruler.MatchType.WILDCARD; /** * Parses the value for a rule into InputCharacters that are used to add the rule to the Machine. Most characters from a * rule's value will be treated by their byte representation, but certain characters, such as for wildcards or regexes, * need to be represented differently so the Machine understands their special meaning. */ public class DefaultParser implements MatchTypeParser, ByteParser { static final byte DOLLAR_SIGN_BYTE = 0x24; static final byte LEFT_PARENTHESIS_BYTE = 0x28; static final byte RIGHT_PARENTHESIS_BYTE = 0x29; static final byte ASTERISK_BYTE = 0x2A; static final byte PLUS_SIGN_BYTE = 0x2B; static final byte COMMA_BYTE = 0x2C; static final byte HYPHEN_BYTE = 0x2D; static final byte PERIOD_BYTE = 0x2E; static final byte ZERO_BYTE = 0x30; static final byte NINE_BYTE = 0x39; static final byte QUESTION_MARK_BYTE = 0x3F; static final byte LEFT_SQUARE_BRACKET_BYTE = 0x5B; static final byte BACKSLASH_BYTE = 0x5C; static final byte RIGHT_SQUARE_BRACKET_BYTE = 0x5D; static final byte CARET_BYTE = 0x5E; static final byte LEFT_CURLY_BRACKET_BYTE = 0x7B; static final byte VERTICAL_LINE_BYTE = 0x7C; static final byte RIGHT_CURLY_BRACKET_BYTE = 0x7D; private static final DefaultParser SINGLETON = new DefaultParser(); private final WildcardParser wildcardParser; private final EqualsIgnoreCaseParser equalsIgnoreCaseParser; private final SuffixParser suffixParser; private final SuffixEqualsIgnoreCaseParser suffixEqualsIgnoreCaseParser; DefaultParser() { this(new WildcardParser(), new EqualsIgnoreCaseParser(), new SuffixParser(), new SuffixEqualsIgnoreCaseParser()); } DefaultParser(WildcardParser wildcardParser, EqualsIgnoreCaseParser equalsIgnoreCaseParser, SuffixParser suffixParser, SuffixEqualsIgnoreCaseParser suffixEqualsIgnoreCaseParser) { this.wildcardParser = wildcardParser; this.equalsIgnoreCaseParser = equalsIgnoreCaseParser; this.suffixParser = suffixParser; this.suffixEqualsIgnoreCaseParser = suffixEqualsIgnoreCaseParser; } public static DefaultParser getParser() { return SINGLETON; } @Override public InputCharacter[] parse(final MatchType type, final String value) { if (type == WILDCARD) { return wildcardParser.parse(value); } else if (type == EQUALS_IGNORE_CASE || type == ANYTHING_BUT_IGNORE_CASE || type == PREFIX_EQUALS_IGNORE_CASE) { return equalsIgnoreCaseParser.parse(value); } else if (type == SUFFIX || type == ANYTHING_BUT_SUFFIX) { return suffixParser.parse(value); } else if (type == SUFFIX_EQUALS_IGNORE_CASE) { return suffixEqualsIgnoreCaseParser.parse(value); } final byte[] utf8bytes = value.getBytes(StandardCharsets.UTF_8); final InputCharacter[] result = new InputCharacter[utf8bytes.length]; for (int i = 0; i < utf8bytes.length; i++) { byte utf8byte = utf8bytes[i]; result[i] = new InputByte(utf8byte); } return result; } @Override public InputCharacter parse(final byte utf8byte) { return new InputByte(utf8byte); } }
4,928
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/EqualsIgnoreCaseParser.java
package software.amazon.event.ruler.input; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.function.Function; /** * A parser to be used specifically for equals-ignore-case rules. For Java characters where lower and upper case UTF-8 * representations do not differ, we will parse into InputBytes. Otherwise, we will use InputMultiByteSet. * * Note that there are actually characters whose upper-case/lower-case UTF-8 representations differ in number of bytes. * One example where length differs by 1: ⱥ, Ⱥ * One example where length differs by 4: ΰ, Ϋ́ * InputMultiByteSet handles differing byte lengths per Java character. */ public class EqualsIgnoreCaseParser { EqualsIgnoreCaseParser() { } public InputCharacter[] parse(String value) { return parse(value, false); } protected InputCharacter[] parse(String value, boolean reverseCharBytes) { List<InputCharacter> result = new ArrayList<>(value.length()); for (char c : value.toCharArray()) { byte[] lowerCaseUtf8bytes = getCharUtfBytes(c, (ch) -> ch.toLowerCase(Locale.ROOT), reverseCharBytes); byte[] upperCaseUtf8bytes = getCharUtfBytes(c, (ch) -> ch.toUpperCase(Locale.ROOT), reverseCharBytes); if (Arrays.equals(lowerCaseUtf8bytes, upperCaseUtf8bytes)) { for (int i = 0; i < lowerCaseUtf8bytes.length; i++) { result.add(new InputByte(lowerCaseUtf8bytes[i])); } } else { Set<MultiByte> multiBytes = new HashSet<>(); multiBytes.add(new MultiByte(lowerCaseUtf8bytes)); multiBytes.add(new MultiByte(upperCaseUtf8bytes)); result.add(new InputMultiByteSet(multiBytes)); } } return result.toArray(new InputCharacter[0]); } private static byte[] getCharUtfBytes(char c, Function<String, String> stringTransformer, boolean reverseCharBytes) { byte[] byteArray = stringTransformer.apply(String.valueOf(c)).getBytes(StandardCharsets.UTF_8); if (reverseCharBytes) { return reverseByteArray(byteArray); } return byteArray; } private static byte[] reverseByteArray(byte[] byteArray) { byte[] reversedByteArray = new byte[byteArray.length]; for (int i = 0; i < byteArray.length; i++) { reversedByteArray[i] = byteArray[byteArray.length - i - 1]; } return reversedByteArray; } }
4,929
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/MultiByte.java
package software.amazon.event.ruler.input; import java.util.Arrays; import static software.amazon.event.ruler.input.DefaultParser.NINE_BYTE; import static software.amazon.event.ruler.input.DefaultParser.ZERO_BYTE; /** * A grouping of multiple bytes. This can be used to represent a character that has a UTF-8 representation requiring * multiple bytes. */ public class MultiByte { public static final byte MIN_FIRST_BYTE_FOR_ONE_BYTE_CHAR = (byte) 0x00; public static final byte MAX_FIRST_BYTE_FOR_ONE_BYTE_CHAR = (byte) 0x7F; public static final byte MIN_FIRST_BYTE_FOR_TWO_BYTE_CHAR = (byte) 0xC2; public static final byte MAX_FIRST_BYTE_FOR_TWO_BYTE_CHAR = (byte) 0xDF; /** * A continuation byte is a byte that is not the first UTF-8 byte in a multibyte character. */ public static final byte MIN_CONTINUATION_BYTE = (byte) 0x80; public static final byte MAX_CONTINUATION_BYTE = (byte) 0xBF; public static final byte MAX_NON_FIRST_BYTE = (byte) 0xBF; private final byte[] bytes; MultiByte(byte ... bytes) { if (bytes.length == 0) { throw new IllegalArgumentException("Must provide at least one byte"); } this.bytes = bytes; } public byte[] getBytes() { return Arrays.copyOf(bytes, bytes.length); } public byte singular() { if (bytes.length != 1) { throw new IllegalStateException("Must be a singular byte"); } return bytes[0]; } public boolean is(byte ... bytes) { return Arrays.equals(this.bytes, bytes); } public boolean isNumeric() { return bytes.length == 1 && bytes[0] >= ZERO_BYTE && bytes[0] <= NINE_BYTE; } public boolean isLessThan(MultiByte other) { return isLessThan(other, false); } public boolean isLessThanOrEqualTo(MultiByte other) { return isLessThan(other, true); } public boolean isGreaterThan(MultiByte other) { return !isLessThanOrEqualTo(other); } public boolean isGreaterThanOrEqualTo(MultiByte other) { return !isLessThan(other); } private boolean isLessThan(MultiByte other, boolean orEqualTo) { byte[] otherBytes = other.getBytes(); for (int i = 0; i < bytes.length; i++) { if (i == otherBytes.length) { // otherBytes is a prefix of bytes. Thus, bytes is larger than otherBytes. return false; } if (bytes[i] != otherBytes[i]) { // Most significant differing byte - return if it is less for bytes than otherBytes. return (0xFF & bytes[i]) < (0xFF & otherBytes[i]); } } // bytes is equal to (return true if orEqualTo) or a prefix of (return true) otherBytes. return orEqualTo || (0xFF & bytes.length) < (0xFF & otherBytes.length); } @Override public boolean equals(Object o) { if (o == null || !(o.getClass() == getClass())) { return false; } return Arrays.equals(((MultiByte) o).getBytes(), getBytes()); } @Override public int hashCode() { return Arrays.hashCode(getBytes()); } @Override public String toString() { return Arrays.toString(getBytes()); } }
4,930
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/SuffixParser.java
package software.amazon.event.ruler.input; import java.nio.charset.StandardCharsets; /** * A parser to be used specifically for suffix rules. * * This undoes the `reverse()` from {@code software.amazon.event.ruler.Patterns} intentionally * to ensure we can correctly reverse utf-8 characters with 2+ bytes like '大' and '雨'. */ public class SuffixParser implements StringValueParser { SuffixParser() { } @Override public InputCharacter[] parse(String value) { final byte[] utf8bytes = new StringBuilder(value).reverse() .toString().getBytes(StandardCharsets.UTF_8); final InputCharacter[] result = new InputCharacter[utf8bytes.length]; for (int i = 0; i < utf8bytes.length; i++) { byte utf8byte = utf8bytes[utf8bytes.length - i - 1]; result[i] = new InputByte(utf8byte); } return result; } }
4,931
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/SuffixEqualsIgnoreCaseParser.java
package software.amazon.event.ruler.input; /** * A parser to be used specifically for suffix equals-ignore-case rules. * * This extends EqualsIgnoreCaseParser to parse and reverse char bytes into InputMultiByteSet * to account for lower-case and upper-case variants. * */ public class SuffixEqualsIgnoreCaseParser extends EqualsIgnoreCaseParser { SuffixEqualsIgnoreCaseParser() { } public InputCharacter[] parse(String value) { // By using EqualsIgnoreCaseParser, we reverse chars in one pass when getting the char bytes for // lower-case and upper-case values. return parse(value, true); } }
4,932
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/WildcardParser.java
package software.amazon.event.ruler.input; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import static software.amazon.event.ruler.input.DefaultParser.ASTERISK_BYTE; import static software.amazon.event.ruler.input.DefaultParser.BACKSLASH_BYTE; /** * A parser to be used specifically for wildcard rules. */ public class WildcardParser implements StringValueParser { WildcardParser() { } @Override public InputCharacter[] parse(final String value) { final byte[] utf8Bytes = value.getBytes(StandardCharsets.UTF_8); final List<InputCharacter> result = new ArrayList<>(utf8Bytes.length); for (int i = 0; i < utf8Bytes.length; i++) { byte utf8byte = utf8Bytes[i]; if (utf8byte == ASTERISK_BYTE) { if (i + 1 < utf8Bytes.length && utf8Bytes[i + 1] == ASTERISK_BYTE) { throw new ParseException("Consecutive wildcard characters at pos " + i); } result.add(new InputWildcard()); } else if (utf8byte == BACKSLASH_BYTE) { if (i + 1 < utf8Bytes.length) { byte nextUtf8byte = utf8Bytes[i + 1]; if (nextUtf8byte == ASTERISK_BYTE || nextUtf8byte == BACKSLASH_BYTE) { result.add(new InputByte(nextUtf8byte)); i++; continue; } } throw new ParseException("Invalid escape character at pos " + i); } else { result.add(new InputByte(utf8byte)); } } return result.toArray(new InputCharacter[0]); } }
4,933
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/InputCharacterType.java
package software.amazon.event.ruler.input; /** * The different types of InputCharacters, created from a rule, that will be used to add the rule to a ByteMachine. */ public enum InputCharacterType { BYTE, MULTI_BYTE_SET, WILDCARD }
4,934
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/InputMultiByteSet.java
package software.amazon.event.ruler.input; import java.util.Collections; import java.util.Objects; import java.util.Set; import static software.amazon.event.ruler.input.InputCharacterType.MULTI_BYTE_SET; /** * An InputCharacter that represents a set of MultiBytes. */ public class InputMultiByteSet extends InputCharacter { private final Set<MultiByte> multiBytes; InputMultiByteSet(Set<MultiByte> multiBytes) { this.multiBytes = Collections.unmodifiableSet(multiBytes); } public static InputMultiByteSet cast(InputCharacter character) { return (InputMultiByteSet) character; } public Set<MultiByte> getMultiBytes() { return multiBytes; } @Override public InputCharacterType getType() { return MULTI_BYTE_SET; } @Override public boolean equals(Object o) { if (o == null || !(o.getClass() == getClass())) { return false; } return ((InputMultiByteSet) o).getMultiBytes().equals(getMultiBytes()); } @Override public int hashCode() { return Objects.hash(getMultiBytes()); } @Override public String toString() { return getMultiBytes().toString(); } }
4,935
0
Create_ds/event-ruler/src/main/software/amazon/event/ruler
Create_ds/event-ruler/src/main/software/amazon/event/ruler/input/MatchTypeParser.java
package software.amazon.event.ruler.input; import software.amazon.event.ruler.MatchType; public interface MatchTypeParser { /** * @param type Match type * @param value string value to parse * @return processed and parsed Input Character */ InputCharacter[] parse(MatchType type, String value); }
4,936
0
Create_ds/aws-cdk/packages/aws-cdk/test/commands/test-resources
Create_ds/aws-cdk/packages/aws-cdk/test/commands/test-resources/stacks/S3Stack.java
package com.myorg; import software.constructs.Construct; import java.util.*; import software.amazon.awscdk.CfnMapping; import software.amazon.awscdk.CfnTag; import software.amazon.awscdk.Stack; import software.amazon.awscdk.StackProps; import software.amazon.awscdk.*; import software.amazon.awscdk.services.s3.*; class GoodJavaStack extends Stack { private Object websiteUrl; private Object s3BucketSecureUrl; public Object getWebsiteUrl() { return this.websiteUrl; } public Object getS3BucketSecureUrl() { return this.s3BucketSecureUrl; } public GoodJavaStack(final Construct scope, final String id) { super(scope, id, null); } public GoodJavaStack(final Construct scope, final String id, final StackProps props) { super(scope, id, props); CfnBucket s3Bucket = CfnBucket.Builder.create(this, "S3Bucket") .accessControl("PublicRead") .websiteConfiguration(CfnBucket.WebsiteConfigurationProperty.builder() .indexDocument("index.html") .errorDocument("error.html") .build()) .build(); s3Bucket.applyRemovalPolicy(RemovalPolicy.RETAIN); this.websiteUrl = s3Bucket.getAttrWebsiteUrl(); CfnOutput.Builder.create(this, "WebsiteURL") .value(this.websiteUrl.toString()) .description("URL for website hosted on S3") .build(); this.s3BucketSecureUrl = String.join("", "https://", s3Bucket.getAttrDomainName()); CfnOutput.Builder.create(this, "S3BucketSecureURL") .value(this.s3BucketSecureUrl.toString()) .description("Name of S3 bucket to hold website content") .build(); } }
4,937
0
Create_ds/aws-cdk/packages/aws-cdk/lib/init-templates/sample-app/java/src/test/java/com
Create_ds/aws-cdk/packages/aws-cdk/lib/init-templates/sample-app/java/src/test/java/com/myorg/%name.PascalCased%StackTest.template.java
package com.myorg; import software.amazon.awscdk.App; import software.amazon.awscdk.assertions.Template; import software.amazon.awscdk.assertions.Match; import java.io.IOException; import java.util.HashMap; import org.junit.jupiter.api.Test; public class %name.PascalCased%StackTest { @Test public void testStack() throws IOException { App app = new App(); %name.PascalCased%Stack stack = new %name.PascalCased%Stack(app, "test"); Template template = Template.fromStack(stack); template.hasResourceProperties("AWS::SQS::Queue", new HashMap<String, Number>() {{ put("VisibilityTimeout", 300); }}); template.resourceCountIs("AWS::SNS::Topic", 1); } }
4,938
0
Create_ds/aws-cdk/packages/aws-cdk/lib/init-templates/sample-app/java/src/main/java/com
Create_ds/aws-cdk/packages/aws-cdk/lib/init-templates/sample-app/java/src/main/java/com/myorg/%name.PascalCased%Stack.template.java
package com.myorg; import software.constructs.Construct; import software.amazon.awscdk.Duration; import software.amazon.awscdk.Stack; import software.amazon.awscdk.StackProps; import software.amazon.awscdk.services.sns.Topic; import software.amazon.awscdk.services.sns.subscriptions.SqsSubscription; import software.amazon.awscdk.services.sqs.Queue; public class %name.PascalCased%Stack extends Stack { public %name.PascalCased%Stack(final Construct parent, final String id) { this(parent, id, null); } public %name.PascalCased%Stack(final Construct parent, final String id, final StackProps props) { super(parent, id, props); final Queue queue = Queue.Builder.create(this, "%name.PascalCased%Queue") .visibilityTimeout(Duration.seconds(300)) .build(); final Topic topic = Topic.Builder.create(this, "%name.PascalCased%Topic") .displayName("My First Topic Yeah") .build(); topic.addSubscription(new SqsSubscription(queue)); } }
4,939
0
Create_ds/aws-cdk/packages/aws-cdk/lib/init-templates/sample-app/java/src/main/java/com
Create_ds/aws-cdk/packages/aws-cdk/lib/init-templates/sample-app/java/src/main/java/com/myorg/%name.PascalCased%App.template.java
package com.myorg; import software.amazon.awscdk.App; public final class %name.PascalCased%App { public static void main(final String[] args) { App app = new App(); new %name.PascalCased%Stack(app, "%stackname%"); app.synth(); } }
4,940
0
Create_ds/aws-cdk/packages/aws-cdk/lib/init-templates/app/java/src/test/java/com
Create_ds/aws-cdk/packages/aws-cdk/lib/init-templates/app/java/src/test/java/com/myorg/%name.PascalCased%Test.template.java
// package com.myorg; // import software.amazon.awscdk.App; // import software.amazon.awscdk.assertions.Template; // import java.io.IOException; // import java.util.HashMap; // import org.junit.jupiter.api.Test; // example test. To run these tests, uncomment this file, along with the // example resource in java/src/main/java/com/myorg/%name.PascalCased%Stack.java // public class %name.PascalCased%Test { // @Test // public void testStack() throws IOException { // App app = new App(); // %name.PascalCased%Stack stack = new %name.PascalCased%Stack(app, "test"); // Template template = Template.fromStack(stack); // template.hasResourceProperties("AWS::SQS::Queue", new HashMap<String, Number>() {{ // put("VisibilityTimeout", 300); // }}); // } // }
4,941
0
Create_ds/aws-cdk/packages/aws-cdk/lib/init-templates/app/java/src/main/java/com
Create_ds/aws-cdk/packages/aws-cdk/lib/init-templates/app/java/src/main/java/com/myorg/%name.PascalCased%Stack.template.java
package com.myorg; import software.constructs.Construct; import software.amazon.awscdk.Stack; import software.amazon.awscdk.StackProps; // import software.amazon.awscdk.Duration; // import software.amazon.awscdk.services.sqs.Queue; public class %name.PascalCased%Stack extends Stack { public %name.PascalCased%Stack(final Construct scope, final String id) { this(scope, id, null); } public %name.PascalCased%Stack(final Construct scope, final String id, final StackProps props) { super(scope, id, props); // The code that defines your stack goes here // example resource // final Queue queue = Queue.Builder.create(this, "%name.PascalCased%Queue") // .visibilityTimeout(Duration.seconds(300)) // .build(); } }
4,942
0
Create_ds/aws-cdk/packages/aws-cdk/lib/init-templates/app/java/src/main/java/com
Create_ds/aws-cdk/packages/aws-cdk/lib/init-templates/app/java/src/main/java/com/myorg/%name.PascalCased%App.template.java
package com.myorg; import software.amazon.awscdk.App; import software.amazon.awscdk.Environment; import software.amazon.awscdk.StackProps; import java.util.Arrays; public class %name.PascalCased%App { public static void main(final String[] args) { App app = new App(); new %name.PascalCased%Stack(app, "%stackname%", StackProps.builder() // If you don't specify 'env', this stack will be environment-agnostic. // Account/Region-dependent features and context lookups will not work, // but a single synthesized template can be deployed anywhere. // Uncomment the next block to specialize this stack for the AWS Account // and Region that are implied by the current CLI configuration. /* .env(Environment.builder() .account(System.getenv("CDK_DEFAULT_ACCOUNT")) .region(System.getenv("CDK_DEFAULT_REGION")) .build()) */ // Uncomment the next block if you know exactly what Account and Region you // want to deploy the stack to. /* .env(Environment.builder() .account("123456789012") .region("us-east-1") .build()) */ // For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html .build()); app.synth(); } }
4,943
0
Create_ds/photon/src/test/java/com/netflix
Create_ds/photon/src/test/java/com/netflix/imflibrary/MXFUIDTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Arrays; @Test(groups = "unit") public class MXFUIDTest { @Test public void testGetUid() { byte[] bytes = new byte[16]; MXFUID MXFUID = new MXFUID(bytes); Assert.assertTrue(MXFUID.toString().length()> 0); Assert.assertEquals(MXFUID.getUID(), bytes); } @Test public void testEquals() { byte[] bytes1 = new byte[16]; MXFUID MXFUID1 = new MXFUID(bytes1); byte[] bytes2 = Arrays.copyOf(bytes1, bytes1.length); MXFUID MXFUID2 = new MXFUID(bytes2); Assert.assertTrue(MXFUID1.equals(MXFUID2)); Assert.assertFalse(MXFUID1.equals(null)); Assert.assertFalse(MXFUID1.equals(bytes1)); } @Test public void testHashCode() { byte[] bytes = new byte[16]; MXFUID MXFUID = new MXFUID(bytes); Assert.assertEquals(MXFUID.hashCode(), Arrays.hashCode(bytes)); } @Test public void testToString() { byte[] bytes = new byte[16]; MXFUID MXFUID = new MXFUID(bytes); Assert.assertEquals(MXFUID.toString().trim(),"0x00000000000000000000000000000000"); bytes = new byte[32]; MXFUID = new MXFUID(bytes); Assert.assertEquals(MXFUID.toString().trim(),"0x0000000000000000000000000000000000000000000000000000000000000000"); bytes = new byte[1]; MXFUID = new MXFUID(bytes); Assert.assertEquals(MXFUID.toString().trim(), Arrays.toString(bytes)); } }
4,944
0
Create_ds/photon/src/test/java/com/netflix
Create_ds/photon/src/test/java/com/netflix/imflibrary/KLVPacketTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.utils.ByteArrayDataProvider; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import com.netflix.imflibrary.utils.ByteProvider; import java.io.IOException; import java.io.InputStream; import static org.testng.Assert.*; @Test(groups = "unit") public class KLVPacketTest { private static final byte[] KberL1 = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x00, 0x03, 0x01, 0x02, 0x10, 0x01, 0x00, 0x00, 0x00, 0x7f}; private static final byte[] KberL2 = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x00, 0x03, 0x01, 0x02, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00}; private static final byte[] KberL3 = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x00, 0x03, 0x01, 0x02, 0x10, 0x01, 0x00, 0x00, 0x00, -1}; //0xff private static final byte[] KberL4 = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x00, 0x03, 0x01, 0x02, 0x10, 0x01, 0x00, 0x00, 0x00, -128}; //0x80 private static final byte[] KberL5 = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x00, 0x03, 0x01, 0x02, 0x10, 0x01, 0x00, 0x00, 0x00, -127, 0x01}; //0x81 (length = 1) private static final byte[] KberL6 = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x00, 0x03, 0x01, 0x02, 0x10, 0x01, 0x00, 0x00, 0x00, -125, 0x00, 0x01, 0x01}; //0x83 (length = 257) private static final byte[] KberL7 = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x00, 0x03, 0x01, 0x02, 0x10, 0x01, 0x00, 0x00, 0x00, -121, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01}; //0x87 (length = 65793) private static final byte[] KberL8 = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x00, 0x03, 0x01, 0x02, 0x10, 0x01, 0x00, 0x00, 0x00, -120}; //0x88 private static final byte[] KberL9 = {0x06, 0x0e, 0x2b, 0x34, 0x02, 0x00, 0x01, 0x00, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00}; private InputStream inputStream; @AfterMethod public void afterMethod() throws Exception { if (this.inputStream != null) { inputStream.close(); } } @Test public void testBER1() throws Exception { ByteProvider byteProvider = new ByteArrayDataProvider(KLVPacketTest.KberL1); KLVPacket.Header header = new KLVPacket.Header(byteProvider, 0L); assertEquals(header.getLSize(), 1); assertEquals(header.getKLSize(), 17); assertEquals(header.getVSize(), 127); assertTrue(header.categoryDesignatorIsDictionaries()); assertFalse(header.categoryDesignatorIsGroups()); assertFalse(header.categoryDesignatorIsWrappersAndContainers()); assertFalse(header.categoryDesignatorIsLabels()); assertTrue(KLVPacket.isKLVFillItem(header.getKey())); assertTrue(header.toString().length() > 0); } @Test public void testBER2() throws Exception { ByteProvider byteProvider = new ByteArrayDataProvider(KLVPacketTest.KberL2); KLVPacket.Header header = new KLVPacket.Header(byteProvider, 0L); assertEquals(header.getLSize(), 1); assertEquals(header.getKLSize(), 17); assertEquals(header.getVSize(), 0); } @Test(expectedExceptions = MXFException.class, expectedExceptionsMessageRegExp = "First byte of length field in KLV item equals 0xFF") public void testInvalidBER3() throws Exception { ByteProvider byteProvider = new ByteArrayDataProvider(KLVPacketTest.KberL3); new KLVPacket.Header(byteProvider, 0L); } @Test(expectedExceptions = MXFException.class, expectedExceptionsMessageRegExp = "First byte of length field in KLV item equals 0x80") public void testInvalidBER4() throws Exception { ByteProvider byteProvider = new ByteArrayDataProvider(KLVPacketTest.KberL4); new KLVPacket.Header(byteProvider, 0L); } @Test public void testBER5() throws Exception { ByteProvider byteProvider = new ByteArrayDataProvider(KLVPacketTest.KberL5); KLVPacket.Header header = new KLVPacket.Header(byteProvider, 0L); assertEquals(header.getLSize(), 2); assertEquals(header.getKLSize(), 18); assertEquals(header.getVSize(), 1); } @Test public void testBER6() throws Exception { ByteProvider byteProvider = new ByteArrayDataProvider(KLVPacketTest.KberL6); KLVPacket.Header header = new KLVPacket.Header(byteProvider, 0L); assertEquals(header.getLSize(), 4); assertEquals(header.getKLSize(), 20); assertEquals(header.getVSize(), 257); } @Test public void testBER7() throws Exception { ByteProvider byteProvider = new ByteArrayDataProvider(KLVPacketTest.KberL7); KLVPacket.Header header = new KLVPacket.Header(byteProvider, 0L); assertEquals(header.getLSize(), 8); assertEquals(header.getKLSize(), 24); assertEquals(header.getVSize(), 65793); } @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "Cannot read .*") public void testInvalidBER8() throws Exception { ByteProvider byteProvider = new ByteArrayDataProvider(KLVPacketTest.KberL8); new KLVPacket.Header(byteProvider, 0L); } @Test public void testBER9() throws Exception { ByteProvider byteProvider = new ByteArrayDataProvider(KLVPacketTest.KberL9); KLVPacket.Header header = new KLVPacket.Header(byteProvider, 0L); assertEquals(header.getLSize(), 1); assertEquals(header.getKLSize(), 17); assertEquals(header.getVSize(), 0); assertFalse(KLVPacket.isKLVFillItem(header.getKey())); } }
4,945
0
Create_ds/photon/src/test/java/com/netflix
Create_ds/photon/src/test/java/com/netflix/imflibrary/MXFDataDefinitionTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary; import org.testng.Assert; import org.testng.annotations.Test; @Test(groups = "unit") public class MXFDataDefinitionTest { @Test public void testGetDataDefinition() { Assert.assertEquals(MXFDataDefinition.getDataDefinition(new MXFUID(MXFUID.picture_essence_track)), MXFDataDefinition.PICTURE); Assert.assertEquals(MXFDataDefinition.getDataDefinition(new MXFUID(MXFUID.sound_essence_track)), MXFDataDefinition.SOUND); Assert.assertEquals(MXFDataDefinition.getDataDefinition(new MXFUID(MXFUID.data_essence_track)), MXFDataDefinition.DATA); byte[] bytes = new byte[16]; Assert.assertEquals(MXFDataDefinition.getDataDefinition(new MXFUID(bytes)), MXFDataDefinition.OTHER); } }
4,946
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/st2067_100/OutputProfileListTest.java
package com.netflix.imflibrary.st2067_100; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.st2067_100.macro.preset.PresetMacro; import com.netflix.imflibrary.st2067_2.ApplicationComposition; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory; import com.netflix.imflibrary.utils.FileByteRangeProvider; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; @Test(groups = "unit") public class OutputProfileListTest { @Test public void testSimpleOutputProfileList() throws Exception { File inputFile = TestHelper.findResourceByPath("TestIMP/OPL/OPL_8cf83c32-4949-4f00-b081-01e12b18932f_simple.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); OutputProfileList outputProfileList = OutputProfileList.getOutputProfileListType(new FileByteRangeProvider(inputFile), imfErrorLogger); Assert.assertEquals(outputProfileList.getCompositionPlaylistId().toString(), "0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85"); Assert.assertEquals(outputProfileList.getAnnotation().toString(), "OPL Example"); Assert.assertEquals(outputProfileList.getId().toString(), "8cf83c32-4949-4f00-b081-01e12b18932f"); Assert.assertEquals(((PresetMacro)outputProfileList.getMacroMap().entrySet().iterator().next().getValue()).getPreset(), "playback_cpl"); Assert.assertEquals(outputProfileList.getErrors().size(), 0); Assert.assertEquals(outputProfileList.getMacroMap().size(), 1); } @Test public void testOutputProfileList() throws Exception { File inputFile = TestHelper.findResourceByPath("TestIMP/OPL/OPL_8cf83c32-4949-4f00-b081-01e12b18932f.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); OutputProfileList outputProfileList = OutputProfileList.getOutputProfileListType(new FileByteRangeProvider(inputFile), imfErrorLogger); Assert.assertEquals(outputProfileList.getCompositionPlaylistId().toString(), "0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85"); Assert.assertEquals(outputProfileList.getAliasMap().size(), 3); Assert.assertEquals(outputProfileList.getAnnotation().toString(), "OPL Example"); Assert.assertEquals(outputProfileList.getId().toString(), "8cf83c32-4949-4f00-b081-01e12b18932f"); Assert.assertEquals(outputProfileList.getErrors().size(), 0); Assert.assertEquals(outputProfileList.getMacroMap().size(), 5); } @Test public void testOutputProfileListOnCOmposition() throws Exception { File inputFileCPL = TestHelper.findResourceByPath("TestIMP/OPL/CPL_0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85.xml"); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(inputFileCPL, new IMFErrorLoggerImpl()); File inputFileOPL = TestHelper.findResourceByPath("TestIMP/OPL/OPL_8cf83c32-4949-4f00-b081-01e12b18932f.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); OutputProfileList outputProfileList = OutputProfileList.getOutputProfileListType(new FileByteRangeProvider(inputFileOPL), imfErrorLogger); outputProfileList.applyOutputProfileOnComposition(applicationComposition); Assert.assertEquals(outputProfileList.getCompositionPlaylistId().toString(), "0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85"); Assert.assertEquals(outputProfileList.getAliasMap().size(), 3); Assert.assertEquals(outputProfileList.getAnnotation().toString(), "OPL Example"); Assert.assertEquals(outputProfileList.getId().toString(), "8cf83c32-4949-4f00-b081-01e12b18932f"); Assert.assertEquals(outputProfileList.getMacroMap().size(), 5); Assert.assertEquals(outputProfileList.getHandleMapWithApplicationComposition(applicationComposition, imfErrorLogger).size(), 28); Assert.assertEquals(outputProfileList.getErrors().size(), 0); } }
4,947
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/RESTfulInterfaces/IMPValidatorFunctionalTests.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.RESTfulInterfaces; import com.netflix.imflibrary.IMFConstraints; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.MXFOperationalPattern1A; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.header.GenericPackage; import com.netflix.imflibrary.st0377.header.Preface; import com.netflix.imflibrary.st0377.header.SourcePackage; import com.netflix.imflibrary.st2067_2.ApplicationComposition; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory; import com.netflix.imflibrary.st2067_2.Composition; import com.netflix.imflibrary.utils.ByteArrayByteRangeProvider; import com.netflix.imflibrary.utils.ByteArrayDataProvider; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.writerTools.CompositionPlaylistBuilder_2016; import com.netflix.imflibrary.writerTools.IMPBuilder; import com.netflix.imflibrary.writerTools.utils.IMFUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.xml.sax.SAXException; import testUtils.TestHelper; import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; @Test(groups = "functional") public class IMPValidatorFunctionalTests { private static final Logger logger = LoggerFactory.getLogger(IMFConstraints.class); @Test public void getPayloadTypeTest() throws IOException { //AssetMap File inputFile = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/ASSETMAP.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.Unknown, 0L, resourceByteRangeProvider.getResourceSize()); Assert.assertTrue(IMPValidator.getPayloadType(payloadRecord) == PayloadRecord.PayloadAssetType.AssetMap); //PKL inputFile = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/PKL_0429fedd-b55d-442a-aa26-2a81ec71ed05.xml"); resourceByteRangeProvider = new FileByteRangeProvider(inputFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.Unknown, 0L, resourceByteRangeProvider.getResourceSize()); Assert.assertTrue(IMPValidator.getPayloadType(payloadRecord) == PayloadRecord.PayloadAssetType.PackingList); //CPL inputFile = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/CPL_a453b63a-cf4d-454a-8c34-141f560c0100.xml"); resourceByteRangeProvider = new FileByteRangeProvider(inputFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.Unknown, 0L, resourceByteRangeProvider.getResourceSize()); Assert.assertTrue(IMPValidator.getPayloadType(payloadRecord) == PayloadRecord.PayloadAssetType.CompositionPlaylist); } @Test public void invalidPKLTest() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/PKL_befcd2d4-f35c-45d7-99bb-7f64b51b103c.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.PackingList, 0L, resourceByteRangeProvider.getResourceSize()); List<ErrorLogger.ErrorObject> errors = IMPValidator.validatePKL(payloadRecord); Assert.assertEquals(errors.size(), 1); Assert.assertTrue(errors.get(0).getErrorDescription().contains("we only support the following schema URIs")); } @Test public void validAssetMapTest() throws IOException { //File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/ASSETMAP.xml"); File inputFile = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/ASSETMAP.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.AssetMap, 0L, resourceByteRangeProvider.getResourceSize()); List<ErrorLogger.ErrorObject>errors = IMPValidator.validateAssetMap(payloadRecord); Assert.assertEquals(errors.size(), 0); } @Test public void invalidAssetMapTest() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/ASSETMAP_ERROR.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.AssetMap, 0L, resourceByteRangeProvider.getResourceSize()); List<ErrorLogger.ErrorObject>errors = IMPValidator.validateAssetMap(payloadRecord); Assert.assertEquals(errors.size(), 5); } @Test public void validPKLTest() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/PKL_0429fedd-b55d-442a-aa26-2a81ec71ed05.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.PackingList, 0L, resourceByteRangeProvider.getResourceSize()); List<ErrorLogger.ErrorObject>errors = IMPValidator.validatePKL(payloadRecord); Assert.assertEquals(errors.size(), 0); } @Test public void validPKLAndAssetMapTest() throws IOException { File pklInputFile = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/PKL_0429fedd-b55d-442a-aa26-2a81ec71ed05.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(pklInputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord pklPayloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.PackingList, 0L, resourceByteRangeProvider.getResourceSize()); List<PayloadRecord> pklPayloadRecordList = new ArrayList<>(); pklPayloadRecordList.add(pklPayloadRecord); File assetMapInputFile = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/ASSETMAP.xml"); ResourceByteRangeProvider assetMapResourceByteRangeProvider = new FileByteRangeProvider(assetMapInputFile); byte[] assetMapBytes = assetMapResourceByteRangeProvider.getByteRangeAsBytes(0, assetMapResourceByteRangeProvider.getResourceSize()-1); PayloadRecord assetMapPayloadRecord = new PayloadRecord(assetMapBytes, PayloadRecord.PayloadAssetType.AssetMap, 0L, assetMapResourceByteRangeProvider.getResourceSize()); List<ErrorLogger.ErrorObject> errors = IMPValidator.validatePKLAndAssetMap(assetMapPayloadRecord, pklPayloadRecordList); Assert.assertEquals(errors.size(), 0); } @Test public void validCPLTest_2013Schema() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, resourceByteRangeProvider.getResourceSize()); List<ErrorLogger.ErrorObject> errors = IMPValidator.validateCPL(payloadRecord); List<ErrorLogger.ErrorObject> fatalErrors = errors.stream().filter(e -> e.getErrorLevel().equals(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL)) .collect(Collectors.toList()); Assert.assertTrue(fatalErrors.size() == 0); } @Test public void invalidCPLTest_2013Schema() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_8fad47bb-ab01-4f0d-a08c" + "-d1e6c6cb62b4_error.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, resourceByteRangeProvider.getResourceSize()); List<ErrorLogger.ErrorObject> errors = IMPValidator.validateCPL(payloadRecord); List<ErrorLogger.ErrorObject> fatalErrors = errors.stream().filter(e -> e.getErrorLevel().equals(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL)) .collect(Collectors.toList()); Assert.assertEquals(fatalErrors.size(), 27); } @Test public void validCPLTest_2016Schema() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4-2016Schema.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, resourceByteRangeProvider.getResourceSize()); List<ErrorLogger.ErrorObject> errors = IMPValidator.validateCPL(payloadRecord); List<ErrorLogger.ErrorObject> fatalErrors = errors.stream().filter(e -> e.getErrorLevel().equals(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL)) .collect(Collectors.toList()); Assert.assertTrue(fatalErrors.size() == 0); } @Test public void getRandomIndexPackSizeTest() throws IOException { File inputFile = TestHelper.findResourceByPath("IMFTrackFiles/TearsOfSteel_4k_Test_Master_Audio_002.mxf"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); long archiveFileSize = resourceByteRangeProvider.getResourceSize(); long rangeEnd = archiveFileSize - 1; long rangeStart = archiveFileSize - 4; byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssenceFooter4Bytes, rangeStart, rangeEnd); Long randomIndexPackSize = IMPValidator.getRandomIndexPackSize(payloadRecord); Assert.assertTrue(randomIndexPackSize == 72); } @Test public void getAllPartitionByteOffsetsTest() throws IOException { File inputFile = TestHelper.findResourceByPath("IMFTrackFiles/TearsOfSteel_4k_Test_Master_Audio_002.mxf"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); long archiveFileSize = resourceByteRangeProvider.getResourceSize(); long rangeEnd = archiveFileSize - 1; long rangeStart = archiveFileSize - 4; byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssenceFooter4Bytes, rangeStart, rangeEnd); Long randomIndexPackSize = IMPValidator.getRandomIndexPackSize(payloadRecord); Assert.assertTrue(randomIndexPackSize == 72); rangeStart = archiveFileSize - randomIndexPackSize; rangeEnd = archiveFileSize - 1; Assert.assertTrue(rangeStart >= 0); byte[] randomIndexPackBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); PayloadRecord randomIndexPackPayload = new PayloadRecord(randomIndexPackBytes, PayloadRecord.PayloadAssetType.EssencePartition, rangeStart, rangeEnd); List<Long> partitionByteOffsets = IMPValidator.getEssencePartitionOffsets(randomIndexPackPayload, randomIndexPackSize); Assert.assertTrue(partitionByteOffsets.size() == 4); Assert.assertTrue(partitionByteOffsets.get(0) == 0); Assert.assertTrue(partitionByteOffsets.get(1) == 11868); Assert.assertTrue(partitionByteOffsets.get(2) == 12104); Assert.assertTrue(partitionByteOffsets.get(3) == 223644); } @Test public void validateEssencesHeaderPartitionTest() throws IOException { List<PayloadRecord> essencesHeaderPartition = new ArrayList<>(); File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015_ENG20.mxf.hdr"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, resourceByteRangeProvider.getResourceSize()); essencesHeaderPartition.add(payloadRecord); inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015_ENG51.mxf.hdr"); resourceByteRangeProvider = new FileByteRangeProvider(inputFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, resourceByteRangeProvider.getResourceSize()); essencesHeaderPartition.add(payloadRecord); inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015_LAS20.mxf.hdr"); resourceByteRangeProvider = new FileByteRangeProvider(inputFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, resourceByteRangeProvider.getResourceSize()); essencesHeaderPartition.add(payloadRecord); inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015_LAS51.mxf.hdr"); resourceByteRangeProvider = new FileByteRangeProvider(inputFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, resourceByteRangeProvider.getResourceSize()); essencesHeaderPartition.add(payloadRecord); inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015.mxf.hdr"); resourceByteRangeProvider = new FileByteRangeProvider(inputFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, resourceByteRangeProvider.getResourceSize()); essencesHeaderPartition.add(payloadRecord); List<ErrorLogger.ErrorObject> errors = IMPValidator.validateIMFTrackFileHeaderMetadata(essencesHeaderPartition); for(ErrorLogger.ErrorObject errorObject : errors){ logger.error(errorObject.toString()); } Assert.assertEquals(errors.size(), 8); } @Test public void cplConformanceNegativeTest() throws IOException, SAXException, JAXBException, URISyntaxException { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord cplPayloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, resourceByteRangeProvider.getResourceSize()); List<PayloadRecord> essencesHeaderPartition = new ArrayList<>(); inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015_ENG20.mxf.hdr"); resourceByteRangeProvider = new FileByteRangeProvider(inputFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, resourceByteRangeProvider.getResourceSize()); essencesHeaderPartition.add(payloadRecord); inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015_ENG51.mxf.hdr"); resourceByteRangeProvider = new FileByteRangeProvider(inputFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, resourceByteRangeProvider.getResourceSize()); essencesHeaderPartition.add(payloadRecord); inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015.mxf.hdr"); resourceByteRangeProvider = new FileByteRangeProvider(inputFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, resourceByteRangeProvider.getResourceSize()); essencesHeaderPartition.add(payloadRecord); List<ErrorLogger.ErrorObject> errors = IMPValidator.areAllVirtualTracksInCPLConformed(cplPayloadRecord, essencesHeaderPartition); Assert.assertEquals(errors.size(), 9); //The following error occurs because we do not yet support TimedText Virtual Tracks in Photon and the EssenceDescriptor in the EDL corresponds to a TimedText Virtual Track whose entry is commented out in the CPL. Assert.assertTrue(errors.get(0).toString().contains("ERROR-EssenceDescriptorID 3febc096-8727-495d-8715-bb5398d98cfe in the CPL EssenceDescriptorList is not referenced by any resource in any of the Virtual tracks in the CPL")); } @Test public void cplVirtualTrackConformanceNegativeTest() throws IOException, SAXException, JAXBException, URISyntaxException { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord cplPayloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, resourceByteRangeProvider.getResourceSize()); List<PayloadRecord> essencesHeaderPartition = new ArrayList<>(); List<ErrorLogger.ErrorObject> errors = IMPValidator.validateCPL(cplPayloadRecord);//Validates the CPL. Assert.assertEquals(errors.size(), 0); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(resourceByteRangeProvider, new IMFErrorLoggerImpl()); List<? extends Composition.VirtualTrack> virtualTracks = applicationComposition.getVirtualTracks(); inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015_ENG20.mxf.hdr"); resourceByteRangeProvider = new FileByteRangeProvider(inputFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord2 = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, resourceByteRangeProvider.getResourceSize()); List<PayloadRecord> payloadRecords = new ArrayList<PayloadRecord>() {{ add(payloadRecord2); }}; errors = IMPValidator.isVirtualTrackInCPLConformed(cplPayloadRecord, virtualTracks.get(2), payloadRecords); Assert.assertEquals(errors.size(), 4); inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015_ENG51.mxf.hdr"); resourceByteRangeProvider = new FileByteRangeProvider(inputFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord1 = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, resourceByteRangeProvider.getResourceSize()); payloadRecords = new ArrayList<PayloadRecord>() {{ add(payloadRecord1); }}; errors = IMPValidator.isVirtualTrackInCPLConformed(cplPayloadRecord, virtualTracks.get(1), payloadRecords); Assert.assertEquals(errors.size(), 4); inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015.mxf.hdr"); resourceByteRangeProvider = new FileByteRangeProvider(inputFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord0 = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, resourceByteRangeProvider.getResourceSize()); payloadRecords = new ArrayList<PayloadRecord>() {{ add(payloadRecord0); }}; errors = IMPValidator.isVirtualTrackInCPLConformed(cplPayloadRecord, virtualTracks.get(0), payloadRecords); Assert.assertEquals(errors.size(), 1); } @Test public void cplVirtualTrackConformanceNegativeTestNamespaceURIInconsitencies() throws IOException, SAXException, JAXBException, URISyntaxException { File inputFile = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/CPL-de6d2644-e84c-432d-98d5-98d89271d082.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord cplPayloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, resourceByteRangeProvider.getResourceSize()); List<PayloadRecord> essencesHeaderPartition = new ArrayList<>(); List<ErrorLogger.ErrorObject> errors = IMPValidator.validateCPL(cplPayloadRecord);//Validates the CPL. Assert.assertEquals(errors.size(), 2); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(resourceByteRangeProvider, new IMFErrorLoggerImpl()); List<? extends Composition.VirtualTrack> virtualTracks = applicationComposition.getVirtualTracks(); inputFile = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/NYCbCrLT_3840x2160x2398_full_full.mxf.hdr"); resourceByteRangeProvider = new FileByteRangeProvider(inputFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord2 = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, resourceByteRangeProvider.getResourceSize()); List<PayloadRecord> payloadRecords = new ArrayList<PayloadRecord>() {{ add(payloadRecord2); }}; errors = IMPValidator.isVirtualTrackInCPLConformed(cplPayloadRecord, virtualTracks.get(0), payloadRecords); Assert.assertEquals(errors.size(), 18); inputFile = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/NYCbCrLT_3840x2160x2chx24bitx30.03sec.mxf.hdr"); resourceByteRangeProvider = new FileByteRangeProvider(inputFile); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord1 = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, resourceByteRangeProvider.getResourceSize()); payloadRecords = new ArrayList<PayloadRecord>() {{ add(payloadRecord1); }}; errors = IMPValidator.isVirtualTrackInCPLConformed(cplPayloadRecord, virtualTracks.get(1), payloadRecords); Assert.assertEquals(errors.size(), 4); } @Test public void cplVirtualTrackConformancePositiveTest() throws IOException, ParserConfigurationException, SAXException, JAXBException, URISyntaxException, NoSuchAlgorithmException { File inputFile = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/CPL_a453b63a-cf4d-454a-8c34-141f560c0100.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); Map<UUID, IMPBuilder.IMFTrackFileMetadata> imfTrackFileMetadataMap = new HashMap<>(); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(resourceByteRangeProvider, imfErrorLogger); File headerPartition1 = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/NYCbCrLT_3840x2160x2chx24bitx30.03sec.mxf.hdr"); resourceByteRangeProvider = new FileByteRangeProvider(headerPartition1); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize() - 1); ByteProvider byteProvider = new ByteArrayDataProvider(bytes); HeaderPartition headerPartition = new HeaderPartition(byteProvider, 0L, bytes.length, imfErrorLogger); MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A = MXFOperationalPattern1A.checkOperationalPattern1ACompliance(headerPartition, imfErrorLogger); IMFConstraints.HeaderPartitionIMF headerPartitionIMF = IMFConstraints.checkIMFCompliance(headerPartitionOP1A, imfErrorLogger); Preface preface = headerPartitionIMF.getHeaderPartitionOP1A().getHeaderPartition().getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage) genericPackage; UUID packageUUID = filePackage.getPackageMaterialNumberasUUID(); imfTrackFileMetadataMap.put(packageUUID, new IMPBuilder.IMFTrackFileMetadata(bytes, IMFUtils.generateSHA1Hash(new ByteArrayByteRangeProvider(bytes)), CompositionPlaylistBuilder_2016.defaultHashAlgorithm, "NYCbCrLT_3840x2160x2chx24bitx30.03sec.mxf", bytes.length)); File headerPartition2 = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/NYCbCrLT_3840x2160x2398_full_full.mxf.hdr"); resourceByteRangeProvider = new FileByteRangeProvider(headerPartition2); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize() - 1); byteProvider = new ByteArrayDataProvider(bytes); headerPartition = new HeaderPartition(byteProvider, 0L, bytes.length, imfErrorLogger); headerPartitionOP1A = MXFOperationalPattern1A.checkOperationalPattern1ACompliance(headerPartition, imfErrorLogger); headerPartitionIMF = IMFConstraints.checkIMFCompliance(headerPartitionOP1A, imfErrorLogger); preface = headerPartitionIMF.getHeaderPartitionOP1A().getHeaderPartition().getPreface(); genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); filePackage = (SourcePackage) genericPackage; packageUUID = filePackage.getPackageMaterialNumberasUUID(); imfTrackFileMetadataMap.put(packageUUID, new IMPBuilder.IMFTrackFileMetadata(bytes, IMFUtils.generateSHA1Hash(new ByteArrayByteRangeProvider(bytes)), CompositionPlaylistBuilder_2016.defaultHashAlgorithm, "NYCbCrLT_3840x2160x2398_full_full.mxf", bytes.length)); //Create a temporary working directory under home Path tempPath = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "IMFDocuments"); File tempDir = tempPath.toFile(); IMPBuilder.buildIMP_2016("IMP", "Netflix", applicationComposition.getEssenceVirtualTracks(), applicationComposition.getEditRate(), "http://www.smpte-ra.org/schemas/2067-21/2016", imfTrackFileMetadataMap, tempDir); boolean cplFound = false; File cplFile = null; for (File file : tempDir.listFiles()) { if (file.getName().contains("CPL-")) { cplFound = true; cplFile = file; } } Assert.assertTrue(cplFound == true); ResourceByteRangeProvider fileByteRangeProvider = new FileByteRangeProvider(cplFile); byte[] documentBytes = fileByteRangeProvider.getByteRangeAsBytes(0, fileByteRangeProvider.getResourceSize()-1); PayloadRecord cplPayloadRecord = new PayloadRecord(documentBytes, PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, 0L); List<ErrorLogger.ErrorObject> errors = IMPValidator.validateCPL(cplPayloadRecord); Assert.assertEquals(errors.size(), 2); applicationComposition = ApplicationCompositionFactory.getApplicationComposition(fileByteRangeProvider, imfErrorLogger); fileByteRangeProvider = new FileByteRangeProvider(headerPartition1); byte[] headerPartition1_bytes = fileByteRangeProvider.getByteRangeAsBytes(0, fileByteRangeProvider.getResourceSize()-1); PayloadRecord headerPartition1PayloadRecord = new PayloadRecord(headerPartition1_bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, 0L); fileByteRangeProvider = new FileByteRangeProvider(headerPartition2); byte[] headerPartition2_bytes = fileByteRangeProvider.getByteRangeAsBytes(0, fileByteRangeProvider.getResourceSize()-1); PayloadRecord headerPartition2PayloadRecord = new PayloadRecord(headerPartition2_bytes, PayloadRecord.PayloadAssetType.EssencePartition, 0L, 0L); List<PayloadRecord> essencesHeaderPartitionPayloads = new ArrayList<>(); essencesHeaderPartitionPayloads.add(headerPartition2PayloadRecord); List<ErrorLogger.ErrorObject> conformanceErrors = IMPValidator.isVirtualTrackInCPLConformed(cplPayloadRecord, applicationComposition.getVideoVirtualTrack(), essencesHeaderPartitionPayloads); Assert.assertEquals(conformanceErrors.size(), 3); } private byte[] getHeaderPartition(File inputFile) throws IOException { ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); long archiveFileSize = resourceByteRangeProvider.getResourceSize(); long rangeEnd = archiveFileSize - 1; long rangeStart = archiveFileSize - 4; byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssenceFooter4Bytes, rangeStart, rangeEnd); Long randomIndexPackSize = IMPValidator.getRandomIndexPackSize(payloadRecord); rangeStart = archiveFileSize - randomIndexPackSize; rangeEnd = archiveFileSize - 1; byte[] randomIndexPackBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); PayloadRecord randomIndexPackPayload = new PayloadRecord(randomIndexPackBytes, PayloadRecord.PayloadAssetType.EssencePartition, rangeStart, rangeEnd); List<Long> partitionByteOffsets = IMPValidator.getEssencePartitionOffsets(randomIndexPackPayload, randomIndexPackSize); return resourceByteRangeProvider.getByteRangeAsBytes(partitionByteOffsets.get(0), partitionByteOffsets.get(1)-1); } @Test public void cplMergeabilityNegativeTest() throws IOException { File cpl1 = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4.xml"); File cpl2 = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4_corrected.xml"); List<ErrorLogger.ErrorObject> errors = new ArrayList<>(); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(cpl1); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord cplPayloadRecord1 = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, resourceByteRangeProvider.getResourceSize()); errors.addAll(IMPValidator.validateCPL(cplPayloadRecord1)); resourceByteRangeProvider = new FileByteRangeProvider(cpl2); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord cplPayloadRecord2 = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, resourceByteRangeProvider.getResourceSize()); errors.addAll(IMPValidator.validateCPL(cplPayloadRecord2)); if(errors.size() == 0) { errors.addAll(IMPValidator.isCPLMergeable(cplPayloadRecord1, new ArrayList<PayloadRecord>() {{ add(cplPayloadRecord2); }})); } Assert.assertEquals(errors.size(), 2); } @Test public void cplMergeabilityPositiveTest() throws IOException { File cpl1 = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4.xml"); File cpl2 = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_supplemental.xml"); List<ErrorLogger.ErrorObject> errors = new ArrayList<>(); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(cpl1); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord cplPayloadRecord1 = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, resourceByteRangeProvider.getResourceSize()); errors.addAll(IMPValidator.validateCPL(cplPayloadRecord1)); resourceByteRangeProvider = new FileByteRangeProvider(cpl2); bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize()-1); PayloadRecord cplPayloadRecord2 = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, resourceByteRangeProvider.getResourceSize()); errors.addAll(IMPValidator.validateCPL(cplPayloadRecord2)); if(errors.size() == 0) { errors.addAll(IMPValidator.isCPLMergeable(cplPayloadRecord1, new ArrayList<PayloadRecord>() {{ add(cplPayloadRecord2); }})); } Assert.assertEquals(errors.size(), 0); } }
4,948
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/app/IMPAnalyzerTestMultiAppIMP.java
/* * * Copyright 2019 RheinMain University of Applied Sciences, Wiesbaden, Germany. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.app; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory.ApplicationCompositionType; import com.netflix.imflibrary.utils.ErrorLogger; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import static com.netflix.imflibrary.app.IMPAnalyzer.analyzePackage; @Test(groups = "unit") public class IMPAnalyzerTestMultiAppIMP { @Test public void IMPAnalyzerTestMultiAppIMP() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/Application5/MultiAppIMP/"); Map<String, List<ErrorLogger.ErrorObject>> errorMap = analyzePackage(inputFile); Assert.assertEquals(errorMap.size(), 8); errorMap.entrySet().stream().forEach( e -> { if (e.getKey().matches("CPL_be8dd1cf-f6e0-4455-ac6f-b22d28557755.xml Virtual Track Conformance")) { Assert.assertEquals(e.getValue().size(), 2); } else if (e.getKey().matches("CPL_eaf76289-fd79-477f-9526-e34d69a8f57a.xml")) { Assert.assertEquals(e.getValue().size(), 1); } else if (e.getKey().matches("CPL_a74cc26b-a87d-4fde-9a28-1865a5ef33db.xml")) { Assert.assertEquals(e.getValue().size(), 0); } else if (e.getKey().matches("CPL_a74cc26b-a87d-4fde-9a28-1865a5ef33db.xml Virtual Track Conformance")) { Assert.assertEquals(e.getValue().size(), 3); } else if (e.getKey().matches("CPL_be8dd1cf-f6e0-4455-ac6f-b22d28557755.xml")) { Assert.assertEquals(e.getValue().size(), 1); } else if (e.getKey().matches("CPL_eaf76289-fd79-477f-9526-e34d69a8f57a.xml Virtual Track Conformance")) { Assert.assertEquals(e.getValue().size(), 2); } else { Assert.assertEquals(e.getValue().size(), 0); } } ); } }
4,949
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/app/IMPAnalyzerTestApp5NoContainerConstraintsSubDescriptor.java
/* * * Copyright 2020 RheinMain University of Applied Sciences, Wiesbaden, Germany. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.app; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory.ApplicationCompositionType; import com.netflix.imflibrary.utils.ErrorLogger; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import static com.netflix.imflibrary.app.IMPAnalyzer.analyzePackage; @Test(groups = "unit") public class IMPAnalyzerTestApp5NoContainerConstraintsSubDescriptor { @Test public void IMPAnalyzerTestApp5NoContainerConstraintsSubDescriptor() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/Application5/PhotonApp5TestNoContainerConstraintsSubDescriptor/"); Map<String, List<ErrorLogger.ErrorObject>> errorMap = analyzePackage(inputFile); Assert.assertEquals(errorMap.size(), 7); errorMap.entrySet().stream().forEach( e -> { if (e.getKey().matches("CPL.*")) { Assert.assertEquals(e.getValue().size(), 5); } else { Assert.assertEquals(e.getValue().size(), 0); } } ); } }
4,950
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/app/IMPAnalyzerTestApp5.java
/* * * Copyright 2019 RheinMain University of Applied Sciences, Wiesbaden, Germany. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.app; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory.ApplicationCompositionType; import com.netflix.imflibrary.utils.ErrorLogger; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import static com.netflix.imflibrary.app.IMPAnalyzer.analyzePackage; @Test(groups = "unit") public class IMPAnalyzerTestApp5 { @Test public void IMPAnalyzerTestApp5() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/Application5/PhotonApp5Test/"); Map<String, List<ErrorLogger.ErrorObject>> errorMap = analyzePackage(inputFile); Assert.assertEquals(errorMap.size(), 7); errorMap.entrySet().stream().forEach( e -> { if (e.getKey().matches("CPL.*")) { Assert.assertEquals(e.getValue().size(), 3); } else { Assert.assertEquals(e.getValue().size(), 0); } } ); } }
4,951
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/app/IMFTrackFileCPLBuilderTests.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary.app; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; import java.nio.file.Files; @Test(groups = "unit") public class IMFTrackFileCPLBuilderTests { @Test public void IMFTrackFileCPLBuilderTest() throws IOException { File inputFile = TestHelper.findResourceByPath("TearsOfSteel_4k_Test_Master_Audio_002.mxf"); File workingDirectory = Files.createTempDirectory(null).toFile(); IMFTrackFileCPLBuilder imfTrackFileCPLBuilder = new IMFTrackFileCPLBuilder(workingDirectory, inputFile); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); Assert.assertTrue(imfTrackFileCPLBuilder.getCompositionPlaylist(imfErrorLogger).length() > 0); } }
4,952
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/app/IMPAnalyzerTestApp5Errors.java
/* * * Copyright 2019 RheinMain University of Applied Sciences, Wiesbaden, Germany. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.app; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory.ApplicationCompositionType; import com.netflix.imflibrary.utils.ErrorLogger; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import static com.netflix.imflibrary.app.IMPAnalyzer.analyzePackage; @Test(groups = "unit") public class IMPAnalyzerTestApp5Errors { @Test public void IMPAnalyzerTestApp5Errors() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/Application5/PhotonApp5TestDiscontinuityAndVideoLineMapError/"); Map<String, List<ErrorLogger.ErrorObject>> errorMap = analyzePackage(inputFile); Assert.assertEquals(errorMap.size(), 7); errorMap.entrySet().stream().forEach( e -> { if (e.getKey().matches("CPL.*")) { Assert.assertEquals(e.getValue().size(), 5); } else { Assert.assertEquals(e.getValue().size(), 0); } } ); } }
4,953
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/app/IMFUtilsTests.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary.app; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.writerTools.utils.IMFUtils; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.security.NoSuchAlgorithmException; @Test(groups = "unit") public class IMFUtilsTests { @Test public void generateHashTest() throws IOException { File inputFile = TestHelper.findResourceByPath("TearsOfSteel_4k_Test_Master_Audio_002.mxf"); String hash = new String(IMFUtils.generateSHA1HashAndBase64Encode(inputFile)); Assert.assertEquals(hash, "fKE0Ukl/nR4ZSQiG43SziGDLDZ4="); } @Test(expectedExceptions = IMFException.class) public void generateHashNegativeTest() throws IOException { File inputFile = TestHelper.findResourceByPath("TearsOfSteel_4k_Test_Master_Audio_002.mxf"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); IMFUtils.generateHash(resourceByteRangeProvider, "SHA-12"); } }
4,954
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/app/IMFTrackFileCPLBuilderFunctionalTests.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary.app; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.KLVPacket; import org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.header.InterchangeObject; import com.netflix.imflibrary.utils.ByteArrayDataProvider; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.writerTools.IMFCPLObjectFieldsFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.w3c.dom.Document; import testUtils.TestHelper; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; @Test(groups = "functional") public class IMFTrackFileCPLBuilderFunctionalTests { @Test public void IMFCPLFactoryTest(){ org.smpte_ra.schemas._2067_3._2013.CompositionPlaylistType compositionPlaylistType = IMFCPLObjectFieldsFactory.constructCompositionPlaylistType_2013(); Assert.assertTrue(compositionPlaylistType.getContentTitle() != null); Assert.assertTrue(compositionPlaylistType.getContentVersionList() != null); Assert.assertTrue(compositionPlaylistType.getContentVersionList().getContentVersion() != null); Assert.assertTrue(compositionPlaylistType.getEssenceDescriptorList() != null); Assert.assertTrue(compositionPlaylistType.getEssenceDescriptorList().getEssenceDescriptor() != null); Assert.assertTrue(compositionPlaylistType.getLocaleList() != null); Assert.assertTrue(compositionPlaylistType.getLocaleList().getLocale() != null); Assert.assertTrue(compositionPlaylistType.getSegmentList() != null); Assert.assertTrue(compositionPlaylistType.getSegmentList().getSegment() != null); } @Test public void RegXMLLibTest() throws IOException, ParserConfigurationException, TransformerException { /*AudioEssence*/ File inputFile = TestHelper.findResourceByPath("TearsOfSteel_4k_Test_Master_Audio_002.mxf"); File workingDirectory = Files.createTempDirectory(null).toFile(); IMFTrackFileCPLBuilder imfTrackFileCPLBuilder = new IMFTrackFileCPLBuilder(workingDirectory, inputFile); IMFTrackFileReader imfTrackFileReader = new IMFTrackFileReader(workingDirectory, new FileByteRangeProvider(inputFile)); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); List<InterchangeObject.InterchangeObjectBO> essenceDescriptors = imfTrackFileReader.getEssenceDescriptors(imfErrorLogger); Assert.assertTrue(essenceDescriptors.size() == 1); List<KLVPacket.Header> subDescriptorHeaders = imfTrackFileReader.getSubDescriptorKLVHeader(essenceDescriptors.get(0), imfErrorLogger); /* create dom */ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = null; docBuilder = docFactory.newDocumentBuilder(); Document document = docBuilder.newDocument(); Assert.assertTrue(imfTrackFileCPLBuilder.getEssenceDescriptorAsXMLFile(document, imfTrackFileReader.getEssenceDescriptorKLVHeader(essenceDescriptors.get(0)), subDescriptorHeaders, imfErrorLogger) != null); } @Test public void EssenceDescriptorTest() throws IOException, ParserConfigurationException, TransformerException { /*Audio Essence*/ File inputFile = TestHelper.findResourceByPath("TearsOfSteel_4k_Test_Master_Audio_002.mxf.hdr"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); byte[] headerPartitionBytes = Files.readAllBytes(Paths.get(inputFile.toURI())); ByteProvider byteProvider = new ByteArrayDataProvider(headerPartitionBytes); HeaderPartition headerPartition = new HeaderPartition(byteProvider, 0L, headerPartitionBytes.length, imfErrorLogger); List<InterchangeObject.InterchangeObjectBO> list = headerPartition.getEssenceDescriptors(); List<KLVPacket.Header> essenceDescriptorHeaders = new ArrayList<>(); for(InterchangeObject.InterchangeObjectBO descriptorBO : list){ essenceDescriptorHeaders.add(descriptorBO.getHeader()); } Assert.assertTrue(essenceDescriptorHeaders.size() == 1); /*Image Essence*/ inputFile = TestHelper.findResourceByPath("CHIMERA_NETFLIX_2398.mxf.hdr"); headerPartitionBytes = Files.readAllBytes(Paths.get(inputFile.toURI())); byteProvider = new ByteArrayDataProvider(headerPartitionBytes); headerPartition = new HeaderPartition(byteProvider, 0L, headerPartitionBytes.length, imfErrorLogger); list = headerPartition.getEssenceDescriptors(); essenceDescriptorHeaders = new ArrayList<>(); for(InterchangeObject.InterchangeObjectBO descriptorBO : list){ essenceDescriptorHeaders.add(descriptorBO.getHeader()); } Assert.assertTrue(essenceDescriptorHeaders.size() == 1); } }
4,955
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/app/IMPAnalyzerTest.java
package com.netflix.imflibrary.app; import com.netflix.imflibrary.utils.ErrorLogger; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import static com.netflix.imflibrary.app.IMPAnalyzer.analyzePackage; @Test(groups = "unit") public class IMPAnalyzerTest { @Test public void IMPAnalyzerTest() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/MERIDIAN_Netflix_Photon_161006/"); Map<String, List<ErrorLogger.ErrorObject>> errorMap = analyzePackage(inputFile); Assert.assertEquals(errorMap.size(), 7); errorMap.entrySet().stream().forEach( e -> { if (e.getKey().matches("CPL.*")) { Assert.assertEquals(e.getValue().size(), 1); } else { Assert.assertEquals(e.getValue().size(), 0); } } ); } @Test public void IMPAnalyzerTestIDMismatches() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/MERIDIAN_Netflix_Photon_161006_ID_MISMATCH/"); Map<String, List<ErrorLogger.ErrorObject>> errorMap = analyzePackage(inputFile); Assert.assertEquals(errorMap.size(), 7); errorMap.entrySet().stream().forEach( e -> { if (e.getKey().matches("CPL.*Virtual Track Conformance")) { Assert.assertEquals(e.getValue().size(), 1); } else if (e.getKey().matches("CPL.*")) { Assert.assertEquals(e.getValue().size(), 2); e.getValue().get(0).getErrorDescription().contains("ERROR-UUID 0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca84 in the CPL is not same as UUID 0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85 of the CPL in the AssetMap"); } else if (e.getKey().matches("OPL.*")) { Assert.assertEquals(e.getValue().size(), 2); e.getValue().get(0).getErrorDescription().contains("ERROR-UUID 8cf83c32-4949-4f00-b081-01e12b18932e in the OPL is not same as UUID 8cf83c32-4949-4f00-b081-01e12b18932f of the OPL in the AssetMap"); e.getValue().get(1).getErrorDescription().contains("Failed to get application composition with ID = 0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85"); } else if (e.getKey().matches("MERIDIAN_Netflix_Photon_161006_00.mxf.*")) { Assert.assertEquals(e.getValue().size(), 1); e.getValue().get(0).getErrorDescription().contains("ERROR-UUID 61d91654-2650-4abf-abbc-ad2c7f640bf8 in the MXF file is not same as UUID 61d91654-2650-4abf-abbc-ad2c7f640bf9 of the MXF file in the AssetMap"); } } ); } }
4,956
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/app/IMPAnalyzerTestApp2E2021.java
package com.netflix.imflibrary.app; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; @Test(groups = "unit") public class IMPAnalyzerTestApp2E2021 { @Test public void ValidCPL() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/Application2E2021/CPL_b2e1ace2-9c7d-4c12-b2f7-24bde303869e.xml"); IMFErrorLogger logger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, logger); logger.getErrors().forEach(e -> {System.out.println(e.getErrorDescription());}); Assert.assertEquals(logger.getErrors().size(), 0); } @Test public void InvalidCPLBadFrameStructure() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/Application2E2021/CPL_b2e1ace2-9c7d-4c12-b2f7-24bde303869e-bad-frame-structure.xml"); IMFErrorLogger logger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, logger); Assert.assertNotEquals(logger.getErrors().size(), 0); } @Test public void InvalidCPLBadCodec() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/Application2E2021/CPL_b2e1ace2-9c7d-4c12-b2f7-24bde303869e-bad-codec.xml"); IMFErrorLogger logger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, logger); Assert.assertNotEquals(logger.getErrors().size(), 0); } @Test public void InvalidCPLBadColor() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/Application2E2021/CPL_b2e1ace2-9c7d-4c12-b2f7-24bde303869e-bad-color.xml"); IMFErrorLogger logger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, logger); Assert.assertNotEquals(logger.getErrors().size(), 0); } }
4,957
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/app/IMFTrackFileReaderTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary.app; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.MXFException; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import java.io.File; import java.io.IOException; import java.nio.file.Files; import static org.mockito.Mockito.*; @Test(groups = "unit") public class IMFTrackFileReaderTest { @Test public void IMFTrackFileReaderTest() throws IOException { File inputFile = TestHelper.findResourceByPath("TearsOfSteel_4k_Test_Master_Audio_002.mxf"); File workingDirectory = Files.createTempDirectory(null).toFile(); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); IMFTrackFileReader imfTrackFileReader = new IMFTrackFileReader(workingDirectory, resourceByteRangeProvider); Assert.assertTrue(imfTrackFileReader.toString().length() > 0); } @Test(expectedExceptions = MXFException.class, expectedExceptionsMessageRegExp = "RandomIndexPackSize = .*") public void badRandomIndexPackLength() throws IOException { File inputFile = TestHelper.findResourceByPath("TearsOfSteel_4k_Test_Master_Audio_002.mxf"); File workingDirectory = Files.createTempDirectory(null).toFile(); ResourceByteRangeProvider resourceByteRangeProvider = mock(ResourceByteRangeProvider.class); when(resourceByteRangeProvider.getResourceSize()).thenReturn(16L); when(resourceByteRangeProvider.getByteRange(anyLong(), anyLong(), any(File.class))).thenReturn(inputFile); IMFTrackFileReader imfTrackFileReader = new IMFTrackFileReader(workingDirectory, resourceByteRangeProvider); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); imfTrackFileReader.getRandomIndexPack(imfErrorLogger); } }
4,958
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/app/MXFEssenceReaderTest.java
package com.netflix.imflibrary.app; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; import java.nio.file.Files; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @Test(groups = "unit") public class MXFEssenceReaderTest { @Test public void MXFAudioEssenceReaderTest() throws IOException { File inputFile = TestHelper.findResourceByPath("TearsOfSteel_4k_Test_Master_Audio_002.mxf"); File workingDirectory = Files.createTempDirectory(null).toFile(); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); MXFEssenceReader mxfEssenceReader = new MXFEssenceReader(workingDirectory, resourceByteRangeProvider); Assert.assertTrue(mxfEssenceReader.toString().length() > 0); Assert.assertEquals(mxfEssenceReader.getPartitionPacks().size(), 4); Assert.assertEquals(mxfEssenceReader.getEssenceTypes().size(), 1); Assert.assertEquals(mxfEssenceReader.getEssenceTypes().get(0), HeaderPartition.EssenceTypeEnum.MainAudioEssence); Assert.assertEquals(mxfEssenceReader.getEssenceDescriptors().size(), 1); Assert.assertEquals(mxfEssenceReader.getEssenceDescriptorsDOMNodes().size(), 1); } @Test(expectedExceptions = MXFException.class, expectedExceptionsMessageRegExp = "randomIndexPackSize = .*") public void badRandomIndexPackLength() throws IOException { File inputFile = TestHelper.findResourceByPath("TearsOfSteel_4k_Test_Master_Audio_002.mxf"); File workingDirectory = Files.createTempDirectory(null).toFile(); ResourceByteRangeProvider resourceByteRangeProvider = mock(ResourceByteRangeProvider.class); when(resourceByteRangeProvider.getResourceSize()).thenReturn(16L); when(resourceByteRangeProvider.getByteRange(anyLong(), anyLong(), any(File.class))).thenReturn(inputFile); MXFEssenceReader mxfEssenceReader = new MXFEssenceReader(workingDirectory, resourceByteRangeProvider); mxfEssenceReader.getRandomIndexPack(); } }
4,959
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/st2067_2/Application2ExtendedCompositionTest.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.utils.ErrorLogger; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import static java.lang.Boolean.TRUE; @Test(groups = "unit") public class Application2ExtendedCompositionTest { @Test public void app2ExtendedCompositionCDCIPositiveTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 0); } @Test public void app2ExtendedCompositionRGBPositiveTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } @Test public void app2ExtendedCompositionInterlacePositiveTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_Interlace.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 0); } @Test public void app2ExtendedCompositionInterlaceErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_InterlaceError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 2); } @Test public void app2ExtendedCompositionRGBErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85_Error.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 7); } @Test public void app2ExtendedCompositionColorSpaceErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_ColorSpaceError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } @Test public void app2ExtendedCompositionColorErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_ColorError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 4); } @Test public void app2ExtendedCompositionQuantizationErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_QuantizationError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 2); } @Test public void app2ExtendedCompositionSamplingErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_SamplingError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 4); } @Test public void app2ExtendedCompositionSubDescriptorsErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_SubDescriptorError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 4); } @Test public void app2ExtendedCompositionJPEG2000SubDescriptorErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_JPEG2000SubDescriptorError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 4); } @Test public void app2ExtendedCompositionJ2CLayoutErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_J2CLayoutError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 4); } @Test public void app2ExtendedCompositionRGBAComponentError1Test() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_RGBAComponentError1.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 4); } @Test public void app2ExtendedCompositionRGBAComponentError2Test() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_RGBAComponentError2.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 14); } @Test public void app2ExtendedCompositionYUV4KTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_4k.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); /* Make sure its APP2#E Composition */ Assert.assertEquals(applicationComposition.getApplicationCompositionType(), ApplicationCompositionFactory.ApplicationCompositionType.APPLICATION_2E_COMPOSITION_TYPE); /* Filter 4k YUV error */ String regex = "^.+invalid StoredWidth\\(.+\\) for ColorModel\\(YUV\\).+$"; List filteredErrors = imfErrorLogger.getErrors().stream() .filter(e -> !( e.getErrorDescription().matches(regex) && e.getErrorCode().equals(IMFErrorLogger.IMFErrors.ErrorCodes.APPLICATION_COMPOSITION_ERROR) && e.getErrorDescription().contains(ApplicationCompositionFactory.ApplicationCompositionType.APPLICATION_2E_COMPOSITION_TYPE.toString()))).collect(Collectors.toList()); /* No other erros after filtering */ Assert.assertEquals(filteredErrors.size(), 0); /* Verify StoredWidth is within max RGB width */ Assert.assertTrue(applicationComposition.getCompositionImageEssenceDescriptorModel().getStoredWidth() <= Application2ExtendedComposition.MAX_RGB_IMAGE_FRAME_WIDTH); } @Test public void app2ExtendedCompositionPictureEssenceCodingErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2Extended/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_EssenceCodingError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } }
4,960
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/st2067_2/IMFEssenceComponentVirtualTrackTest.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.utils.FileByteRangeProvider; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.util.HashSet; import java.util.UUID; @Test(groups = "unit") public class IMFEssenceComponentVirtualTrackTest { @Test public void testEssenceComponentVirtualTrack_2013() throws Exception { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4_corrected.xml"); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(new FileByteRangeProvider(inputFile), new IMFErrorLoggerImpl(), new HashSet<String>() {{ add("MCALinkID"); add("MCALabelDictionaryID"); add("RFC5646SpokenLanguage"); add("AudioChannelLabelSubDescriptor"); add("SoundfieldGroupLabelSubDescriptor");}}); Assert.assertTrue(ApplicationComposition.isCompositionPlaylist(new FileByteRangeProvider(inputFile))); Assert.assertTrue(applicationComposition.toString().length() > 0); Assert.assertEquals(applicationComposition.getEditRate().getNumerator().longValue(), 24000); Assert.assertEquals(applicationComposition.getEditRate().getDenominator().longValue(), 1001); Assert.assertEquals(applicationComposition.getUUID(), UUID.fromString("8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4")); Assert.assertEquals(applicationComposition.getVirtualTracks().size(), 4); IMFEssenceComponentVirtualTrack virtualTrack = applicationComposition.getVideoVirtualTrack(); Assert.assertEquals(virtualTrack.getTrackFileResourceList().size(), 7); } @Test public void testEssenceComponentVirtualTrackEquivalent_2013() throws Exception { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4_corrected.xml"); ApplicationComposition applicationComposition1 = ApplicationCompositionFactory.getApplicationComposition(inputFile, new IMFErrorLoggerImpl()); ApplicationComposition applicationComposition2 = ApplicationCompositionFactory.getApplicationComposition(inputFile, new IMFErrorLoggerImpl()); IMFEssenceComponentVirtualTrack virtualTrack1 = applicationComposition1.getVideoVirtualTrack(); IMFEssenceComponentVirtualTrack virtualTrack2 = applicationComposition2.getVideoVirtualTrack(); Assert.assertTrue(virtualTrack1.equivalent(virtualTrack2)); } @Test public void testEssenceComponentVirtualTrack_2016() throws Exception { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_2016_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4_corrected.xml"); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(inputFile, new IMFErrorLoggerImpl()); Assert.assertTrue(ApplicationComposition.isCompositionPlaylist(new FileByteRangeProvider(inputFile))); Assert.assertTrue(applicationComposition.toString().length() > 0); Assert.assertEquals(applicationComposition.getEditRate().getNumerator().longValue(), 24000); Assert.assertEquals(applicationComposition.getEditRate().getDenominator().longValue(), 1001); Assert.assertEquals(applicationComposition.getUUID(), UUID.fromString("8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4")); Assert.assertEquals(applicationComposition.getVirtualTracks().size(), 4); IMFEssenceComponentVirtualTrack virtualTrack = applicationComposition.getVideoVirtualTrack(); Assert.assertEquals(virtualTrack.getTrackFileResourceList().size(), 7); for( Composition.VirtualTrack track : applicationComposition.getVirtualTracks()) { if(track instanceof IMFEssenceComponentVirtualTrack) { IMFEssenceComponentVirtualTrack essenseTrack = (IMFEssenceComponentVirtualTrack) track; for (IMFTrackFileResourceType resource : essenseTrack.getTrackFileResourceList()) { Assert.assertEquals(resource.getHashAlgorithm(), "http://www.w3.org/2000/09/xmldsig#sha1"); } } } } @Test public void testEssenceComponentVirtualTrackEquivalent_2016() throws Exception { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_2016_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4_corrected.xml"); ApplicationComposition applicationComposition1 = ApplicationCompositionFactory.getApplicationComposition(inputFile, new IMFErrorLoggerImpl()); ApplicationComposition applicationComposition2 = ApplicationCompositionFactory.getApplicationComposition(inputFile, new IMFErrorLoggerImpl()); IMFEssenceComponentVirtualTrack virtualTrack1 = applicationComposition1.getVideoVirtualTrack(); IMFEssenceComponentVirtualTrack virtualTrack2 = applicationComposition2.getVideoVirtualTrack(); Assert.assertTrue(virtualTrack1.equivalent(virtualTrack2)); } @Test public void testZeroResourceDuration() throws Exception { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_zero_resource_duration_track_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4.xml"); IMFErrorLoggerImpl errorLogger = new IMFErrorLoggerImpl(); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(inputFile, new IMFErrorLoggerImpl()); Assert.assertTrue(ApplicationComposition.isCompositionPlaylist(new FileByteRangeProvider(inputFile))); Assert.assertTrue(applicationComposition.toString().length() > 0); Assert.assertEquals(applicationComposition.getEditRate().getNumerator().longValue(), 24000); Assert.assertEquals(applicationComposition.getEditRate().getDenominator().longValue(), 1001); Assert.assertEquals(applicationComposition.getUUID(), UUID.fromString("8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4")); Assert.assertEquals(applicationComposition.getVirtualTracks().size(), 4); IMFEssenceComponentVirtualTrack virtualTrack = applicationComposition.getVideoVirtualTrack(); for(IMFBaseResourceType resource: virtualTrack.getTrackFileResourceList()) { Assert.assertTrue(resource.getSourceDuration().longValue() > 0); } } @Test public void testEssenceComponentVirtualTrackAudioHomogeneityFail_2013() throws Exception { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4_audio_homogeneity_fail.xml"); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(new FileByteRangeProvider(inputFile), new IMFErrorLoggerImpl(), new HashSet<String>() {{ add("MCAChannelID"); add("MCALabelDictionaryID"); add("RFC5646SpokenLanguage"); add("AudioChannelLabelSubDescriptor"); add("SoundfieldGroupLabelSubDescriptor"); add("MCAAudioContentKind");}}); Assert.assertTrue(ApplicationComposition.isCompositionPlaylist(new FileByteRangeProvider(inputFile))); Assert.assertTrue(applicationComposition.toString().length() > 0); Assert.assertEquals(applicationComposition.getEditRate().getNumerator().longValue(), 24000); Assert.assertEquals(applicationComposition.getEditRate().getDenominator().longValue(), 1001); Assert.assertEquals(applicationComposition.getUUID(), UUID.fromString("8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4")); Assert.assertEquals(applicationComposition.getErrors().size(), 1); Assert.assertEquals(applicationComposition.getVirtualTracks().size(), 4); IMFEssenceComponentVirtualTrack virtualTrack = applicationComposition.getVideoVirtualTrack(); Assert.assertEquals(virtualTrack.getTrackFileResourceList().size(), 7); } @Test public void testEssenceComponentVirtualTrackCodingEquationHomogeneityFail_2013() throws Exception { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4_coding_equation_homogeneity_fail.xml"); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(new FileByteRangeProvider(inputFile), new IMFErrorLoggerImpl(), new HashSet<String>() {{ add("MCAChannelID"); add("MCALabelDictionaryID"); add("RFC5646SpokenLanguage"); add("AudioChannelLabelSubDescriptor"); add("SoundfieldGroupLabelSubDescriptor"); add("MCAAudioContentKind");}}); Assert.assertTrue(ApplicationComposition.isCompositionPlaylist(new FileByteRangeProvider(inputFile))); Assert.assertTrue(applicationComposition.toString().length() > 0); Assert.assertEquals(applicationComposition.getEditRate().getNumerator().longValue(), 24000); Assert.assertEquals(applicationComposition.getEditRate().getDenominator().longValue(), 1001); Assert.assertEquals(applicationComposition.getUUID(), UUID.fromString("8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4")); Assert.assertEquals(applicationComposition.getErrors().size(), 1); Assert.assertEquals(applicationComposition.getVirtualTracks().size(), 4); IMFEssenceComponentVirtualTrack virtualTrack = applicationComposition.getVideoVirtualTrack(); Assert.assertEquals(virtualTrack.getTrackFileResourceList().size(), 7); } @Test public void testEssenceComponentVirtualTrackRGBACodingEquationHomogeneityIgnore_2013() throws Exception { File inputFile = TestHelper.findResourceByPath("TestIMP/Application2/CPL_0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85_rgba_coding_equation.xml"); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(new FileByteRangeProvider(inputFile), new IMFErrorLoggerImpl(), new HashSet<String>() {{ add("MCAChannelID"); add("MCALabelDictionaryID"); add("RFC5646SpokenLanguage"); add("AudioChannelLabelSubDescriptor"); add("SoundfieldGroupLabelSubDescriptor"); add("MCAAudioContentKind");}}); Assert.assertTrue(ApplicationComposition.isCompositionPlaylist(new FileByteRangeProvider(inputFile))); Assert.assertTrue(applicationComposition.toString().length() > 0); Assert.assertEquals(applicationComposition.getEditRate().getNumerator().longValue(), 60000); Assert.assertEquals(applicationComposition.getEditRate().getDenominator().longValue(), 1001); Assert.assertEquals(applicationComposition.getUUID(), UUID.fromString("0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85")); Assert.assertEquals(applicationComposition.getErrors().size(), 1); Assert.assertEquals(applicationComposition.getVirtualTracks().size(), 3); IMFEssenceComponentVirtualTrack virtualTrack = applicationComposition.getVideoVirtualTrack(); Assert.assertEquals(virtualTrack.getTrackFileResourceList().size(), 2); } }
4,961
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/st2067_2/IMFMarkerVirtualTrackTest.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.utils.FileByteRangeProvider; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.util.UUID; @Test(groups = "unit") public class IMFMarkerVirtualTrackTest { @Test public void testMarkerVirtualTrack_2013() throws Exception { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4_corrected.xml"); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(inputFile, new IMFErrorLoggerImpl()); Assert.assertTrue(ApplicationComposition.isCompositionPlaylist(new FileByteRangeProvider(inputFile))); Assert.assertTrue(applicationComposition.toString().length() > 0); Assert.assertEquals(applicationComposition.getEditRate().getNumerator().longValue(), 24000); Assert.assertEquals(applicationComposition.getEditRate().getDenominator().longValue(), 1001); Assert.assertEquals(applicationComposition.getUUID(), UUID.fromString("8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4")); Assert.assertEquals(applicationComposition.getVirtualTracks().size(), 4); IMFMarkerVirtualTrack virtualTrack = applicationComposition.getMarkerVirtualTrack(); Assert.assertEquals(virtualTrack.getMarkerResourceList().size(), 1); Assert.assertEquals(virtualTrack.getMarkerResourceList().get(0).getMarkerList().size(), 19); } @Test public void testMarkerVirtualTrackEquivalent_2013() throws Exception { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4_corrected.xml"); ApplicationComposition applicationComposition1 = ApplicationCompositionFactory.getApplicationComposition(inputFile, new IMFErrorLoggerImpl()); ApplicationComposition applicationComposition2 = ApplicationCompositionFactory.getApplicationComposition(inputFile, new IMFErrorLoggerImpl()); IMFMarkerVirtualTrack virtualTrack1 = applicationComposition1.getMarkerVirtualTrack(); IMFMarkerVirtualTrack virtualTrack2 = applicationComposition2.getMarkerVirtualTrack(); Assert.assertTrue(virtualTrack1.equivalent(virtualTrack2)); } @Test public void testMarkerVirtualTrack_2016() throws Exception { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_2016_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4_corrected.xml"); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(inputFile, new IMFErrorLoggerImpl()); Assert.assertTrue(ApplicationComposition.isCompositionPlaylist(new FileByteRangeProvider(inputFile))); Assert.assertTrue(applicationComposition.toString().length() > 0); Assert.assertEquals(applicationComposition.getEditRate().getNumerator().longValue(), 24000); Assert.assertEquals(applicationComposition.getEditRate().getDenominator().longValue(), 1001); Assert.assertEquals(applicationComposition.getUUID(), UUID.fromString("8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4")); Assert.assertEquals(applicationComposition.getVirtualTracks().size(), 4); IMFMarkerVirtualTrack virtualTrack = applicationComposition.getMarkerVirtualTrack(); Assert.assertEquals(virtualTrack.getMarkerResourceList().size(), 1); Assert.assertEquals(virtualTrack.getMarkerResourceList().get(0).getMarkerList().size(), 19); } @Test public void testMarkerVirtualTrackEquivalent_2016() throws Exception { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_2016_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4_corrected.xml"); ApplicationComposition applicationComposition1 = ApplicationCompositionFactory.getApplicationComposition(inputFile, new IMFErrorLoggerImpl()); ApplicationComposition applicationComposition2 = ApplicationCompositionFactory.getApplicationComposition(inputFile, new IMFErrorLoggerImpl()); IMFMarkerVirtualTrack virtualTrack1 = applicationComposition1.getMarkerVirtualTrack(); IMFMarkerVirtualTrack virtualTrack2 = applicationComposition2.getMarkerVirtualTrack(); Assert.assertTrue(virtualTrack1.equivalent(virtualTrack2)); } }
4,962
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/st2067_2/Application2CompositionTest.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import org.testng.Assert; import org.testng.annotations.Ignore; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; @Test(groups = "unit") public class Application2CompositionTest { @Test public void app2CompositionCDCIPositiveTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 0); } @Test @Ignore public void app2CompositionRGBPositiveTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } @Test public void app2CompositionInterlacePositiveTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_Interlace.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 0); } @Test public void app2CompositionInterlaceErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_InterlaceError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } @Test @Ignore public void app2CompositionRGBErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85_Error.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 7); } @Test public void app2CompositionColorSpaceErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_ColorSpaceError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } @Test public void app2CompositionColorErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_ColorError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 4); } @Test public void app2CompositionQuantizationErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_QuantizationError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 2); } @Test public void app2CompositionSamplingErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_SamplingError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 3); } @Test public void app2CompositionSubDescriptorsErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_SubDescriptorError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 5); } @Test public void app2CompositionJPEG2000SubDescriptorMissingComponentDepthErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_SubDescriptorError_componentDepth_missing.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 6); } @Test public void app2CompositionJPEG2000SubDescriptorComponentDepthPixelDepthMismatchErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_SubDescriptorError_componentDepth_mismatch.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 5); } @Test public void app2CompositionJPEG2000SubDescriptorErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_JPEG2000SubDescriptorError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 5); } @Test public void app2CompositionJ2CLayoutErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_J2CLayoutError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 5); } @Test public void app2CompositionRGBAComponentError1Test() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_RGBAComponentError.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 5); } @Test public void app2CompositionRGBAComponentError2Test() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_RGBAError1.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 10); } @Test public void app2CompositionPictureEssenceCodingErrorTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Application2/CPL_BLACKL_202_1080p_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_BadEssenceCoding.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } }
4,963
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/st2067_2/CompositionTest.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.writerTools.CompositionPlaylistBuilder_2013; import com.netflix.imflibrary.writerTools.utils.IMFUUIDGenerator; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Test(groups = "unit") public class CompositionTest { @Test public void testCompositionPlaylist() throws Exception { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); File inputFile = TestHelper.findResourceByPath("test_mapped_file_set/CPL_682feecb-7516-4d93-b533-f40d4ce60539.xml"); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertTrue(ApplicationComposition.isCompositionPlaylist(new FileByteRangeProvider(inputFile))); Assert.assertTrue(applicationComposition.toString().length() > 0); Assert.assertEquals(applicationComposition.getEditRate().getNumerator().longValue(), 24); Assert.assertEquals(applicationComposition.getEditRate().getDenominator().longValue(), 1); Assert.assertEquals(applicationComposition.getUUID(), UUID.fromString("682feecb-7516-4d93-b533-f40d4ce60539")); UUID uuid = UUID.fromString("586286d2-c45f-4b2f-ad76-58eecd0202b4"); Assert.assertEquals(applicationComposition.getVirtualTracks().size(), 2); Composition.VirtualTrack virtualTrack = applicationComposition.getVideoVirtualTrack(); Assert.assertEquals(virtualTrack.getSequenceTypeEnum(), Composition.SequenceTypeEnum.MainImageSequence); Assert.assertTrue(applicationComposition.getAnnotation().length() > 0); Assert.assertTrue(applicationComposition.getIssuer().length() > 0); Assert.assertTrue(applicationComposition.getCreator().length() > 0); Assert.assertTrue(applicationComposition.getContentOriginator().length() > 0); Assert.assertTrue(applicationComposition.getContentTitle().length() > 0); } @Test public void compositionPositiveTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/MERIDIAN_Netflix_Photon_161006/CPL_0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertTrue(imfErrorLogger.getErrors().size() == 1); } @Test public void compositionWithMultipleImageResourcesPositiveTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertTrue(imfErrorLogger.getErrors().size() == 0); } @Test public void compositionNegativeTestInconsistentURI() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_LAS_8fad47bb-ab01-4f0d-a08c-d1e6c6cb62b4_InconsistentNamespaceURI.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertTrue(imfErrorLogger.getErrors().size() == 11); } @Test public void virtualTracksEquivalenceTest(){ String trackFileId1 = IMFUUIDGenerator.getInstance().getUrnUUID(); String trackFileId2 = IMFUUIDGenerator.getInstance().getUrnUUID(); String sourceEncoding = IMFUUIDGenerator.getInstance().generateUUID().toString(); byte[] hash = new byte[16]; String hashAlgorithm = CompositionPlaylistBuilder_2013.defaultHashAlgorithm; List<Long> editRate = new ArrayList<>(); editRate.add(24000L); editRate.add(1001L); BigInteger intrinsicDuration = new BigInteger("100"); IMFTrackFileResourceType imfTrackFileResourceType1 = new IMFTrackFileResourceType(IMFUUIDGenerator.getInstance().generateUUID().toString(), trackFileId1, editRate, intrinsicDuration, new BigInteger("0"), new BigInteger("50"), new BigInteger("2"), sourceEncoding, hash, hashAlgorithm); IMFTrackFileResourceType imfTrackFileResourceType2 = new IMFTrackFileResourceType(IMFUUIDGenerator.getInstance().generateUUID().toString(), trackFileId1, editRate, intrinsicDuration, new BigInteger("50"), new BigInteger("50"), new BigInteger("2"), sourceEncoding, hash, hashAlgorithm); IMFTrackFileResourceType imfTrackFileResourceType3 = new IMFTrackFileResourceType(IMFUUIDGenerator.getInstance().generateUUID().toString(), trackFileId2, editRate, intrinsicDuration, new BigInteger("0"), new BigInteger("50"), new BigInteger("2"), sourceEncoding, hash, hashAlgorithm); IMFTrackFileResourceType imfTrackFileResourceType4 = new IMFTrackFileResourceType(IMFUUIDGenerator.getInstance().generateUUID().toString(), trackFileId1, editRate, intrinsicDuration, new BigInteger("0"), new BigInteger("100"), new BigInteger("2"), sourceEncoding, hash, hashAlgorithm); IMFTrackFileResourceType imfTrackFileResourceType5 = new IMFTrackFileResourceType(IMFUUIDGenerator.getInstance().generateUUID().toString(), trackFileId1, editRate, intrinsicDuration, new BigInteger("0"), new BigInteger("50"), new BigInteger("1"), sourceEncoding, hash, hashAlgorithm); IMFTrackFileResourceType imfTrackFileResourceType6 = new IMFTrackFileResourceType(IMFUUIDGenerator.getInstance().generateUUID().toString(), trackFileId1, editRate, intrinsicDuration, new BigInteger("0"), new BigInteger("100"), new BigInteger("1"), sourceEncoding, hash, hashAlgorithm); IMFTrackFileResourceType imfTrackFileResourceType7 = new IMFTrackFileResourceType(IMFUUIDGenerator.getInstance().generateUUID().toString(), trackFileId1, editRate, intrinsicDuration, new BigInteger("50"), new BigInteger("50"), new BigInteger("1"), sourceEncoding, hash, hashAlgorithm); IMFTrackFileResourceType imfTrackFileResourceType8 = new IMFTrackFileResourceType(IMFUUIDGenerator.getInstance().generateUUID().toString(), trackFileId2, editRate, intrinsicDuration, new BigInteger("0"), new BigInteger("50"), new BigInteger("1"), sourceEncoding, hash, hashAlgorithm); IMFTrackFileResourceType imfTrackFileResourceType9 = new IMFTrackFileResourceType(IMFUUIDGenerator.getInstance().generateUUID().toString(), trackFileId2, editRate, intrinsicDuration, new BigInteger("50"), new BigInteger("50"), new BigInteger("1"), sourceEncoding, hash, hashAlgorithm); IMFTrackFileResourceType imfTrackFileResourceType10 = new IMFTrackFileResourceType(IMFUUIDGenerator.getInstance().generateUUID().toString(), trackFileId2, editRate, intrinsicDuration, new BigInteger("0"), new BigInteger("100"), new BigInteger("1"), sourceEncoding, hash, hashAlgorithm); IMFTrackFileResourceType imfTrackFileResourceType11 = new IMFTrackFileResourceType(IMFUUIDGenerator.getInstance().generateUUID().toString(), trackFileId1, editRate, intrinsicDuration, new BigInteger("0"), new BigInteger("25"), new BigInteger("1"), sourceEncoding, hash, hashAlgorithm); IMFTrackFileResourceType imfTrackFileResourceType12 = new IMFTrackFileResourceType(IMFUUIDGenerator.getInstance().generateUUID().toString(), trackFileId1, editRate, intrinsicDuration, new BigInteger("25"), new BigInteger("25"), new BigInteger("1"), sourceEncoding, hash, hashAlgorithm); IMFTrackFileResourceType imfTrackFileResourceType13 = new IMFTrackFileResourceType(IMFUUIDGenerator.getInstance().generateUUID().toString(), trackFileId1, editRate, intrinsicDuration, new BigInteger("50"), new BigInteger("50"), new BigInteger("1"), sourceEncoding, hash, hashAlgorithm); List<IMFTrackFileResourceType> resourceList1 = new ArrayList<>(); resourceList1.add(imfTrackFileResourceType1); resourceList1.add(imfTrackFileResourceType2); resourceList1.add(imfTrackFileResourceType3); List<IMFTrackFileResourceType> resourceList2 = new ArrayList<>(); resourceList2.add(imfTrackFileResourceType4); resourceList2.add(imfTrackFileResourceType3); List<IMFTrackFileResourceType> resourceList3 = new ArrayList<>(); resourceList3.add(imfTrackFileResourceType5); resourceList3.add(imfTrackFileResourceType6); resourceList3.add(imfTrackFileResourceType7); resourceList3.add(imfTrackFileResourceType3); List<IMFTrackFileResourceType> resourceList4 = new ArrayList<>(); resourceList4.add(imfTrackFileResourceType8); resourceList4.add(imfTrackFileResourceType9); resourceList4.add(imfTrackFileResourceType3); List<IMFTrackFileResourceType> resourceList5 = new ArrayList<>(); resourceList5.add(imfTrackFileResourceType10); resourceList5.add(imfTrackFileResourceType3); List<IMFTrackFileResourceType> resourceList6 = new ArrayList<>(); resourceList6.add(imfTrackFileResourceType3); resourceList6.add(imfTrackFileResourceType1); resourceList6.add(imfTrackFileResourceType2); List<IMFTrackFileResourceType> resourceList7 = new ArrayList<>(); resourceList7.add(imfTrackFileResourceType11); resourceList7.add(imfTrackFileResourceType12); resourceList7.add(imfTrackFileResourceType13); List<IMFTrackFileResourceType> resourceList8 = new ArrayList<>(); resourceList8.add(imfTrackFileResourceType6); List<IMFTrackFileResourceType> resourceList9 = new ArrayList<>(); resourceList9.add(imfTrackFileResourceType11); resourceList9.add(imfTrackFileResourceType12); resourceList9.add(imfTrackFileResourceType13); resourceList9.add(imfTrackFileResourceType3); List<IMFTrackFileResourceType> resourceList10 = new ArrayList<>(); resourceList10.add(imfTrackFileResourceType6); resourceList10.add(imfTrackFileResourceType3); Composition.EditRate compositionEditRate = new Composition.EditRate(editRate); Composition.VirtualTrack virtualTrack1 = new IMFEssenceComponentVirtualTrack(IMFUUIDGenerator.getInstance().generateUUID(), Composition.SequenceTypeEnum.MainImageSequence, resourceList1, compositionEditRate); Composition.VirtualTrack virtualTrack2 = new IMFEssenceComponentVirtualTrack(IMFUUIDGenerator.getInstance().generateUUID(), Composition.SequenceTypeEnum.MainImageSequence, resourceList2, compositionEditRate); Composition.VirtualTrack virtualTrack3 = new IMFEssenceComponentVirtualTrack(IMFUUIDGenerator.getInstance().generateUUID(), Composition.SequenceTypeEnum.MainImageSequence, resourceList3, compositionEditRate); Composition.VirtualTrack virtualTrack4 = new IMFEssenceComponentVirtualTrack(IMFUUIDGenerator.getInstance().generateUUID(), Composition.SequenceTypeEnum.MainImageSequence, resourceList4, compositionEditRate); Composition.VirtualTrack virtualTrack5 = new IMFEssenceComponentVirtualTrack(IMFUUIDGenerator.getInstance().generateUUID(), Composition.SequenceTypeEnum.MainImageSequence, resourceList5, compositionEditRate); Composition.VirtualTrack virtualTrack6 = new IMFEssenceComponentVirtualTrack(IMFUUIDGenerator.getInstance().generateUUID(), Composition.SequenceTypeEnum.MainImageSequence, resourceList6, compositionEditRate); Composition.VirtualTrack virtualTrack7 = new IMFEssenceComponentVirtualTrack(IMFUUIDGenerator.getInstance().generateUUID(), Composition.SequenceTypeEnum.MainImageSequence, resourceList7, compositionEditRate); Composition.VirtualTrack virtualTrack8 = new IMFEssenceComponentVirtualTrack(IMFUUIDGenerator.getInstance().generateUUID(), Composition.SequenceTypeEnum.MainImageSequence, resourceList8, compositionEditRate); Composition.VirtualTrack virtualTrack9 = new IMFEssenceComponentVirtualTrack(IMFUUIDGenerator.getInstance().generateUUID(), Composition.SequenceTypeEnum.MainImageSequence, resourceList9, compositionEditRate); Composition.VirtualTrack virtualTrack10 = new IMFEssenceComponentVirtualTrack(IMFUUIDGenerator.getInstance().generateUUID(), Composition.SequenceTypeEnum.MainImageSequence, resourceList10, compositionEditRate); Assert.assertTrue(virtualTrack1.equivalent(virtualTrack2) == false); Assert.assertTrue(virtualTrack1.equivalent(virtualTrack3) == true); Assert.assertTrue(virtualTrack4.equivalent(virtualTrack5) == true); Assert.assertTrue(virtualTrack1.equivalent(virtualTrack6) == false); Assert.assertTrue(virtualTrack7.equivalent(virtualTrack8) == true); Assert.assertTrue(virtualTrack9.equivalent(virtualTrack10) == true); } @Test public void compositionWithMultipleApplicationIdentificationPositiveTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/ApplicationIdentification/CPL-multiple-values-supported.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 0); } @Test public void compositionWithMultipleApplicationIdentificationDuplicatePositiveTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/ApplicationIdentification/CPL-multiple-values-supported-duplicated.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 0); } @Test public void compositionWithMultipleApplicationIdentificationPartialNegativeTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/ApplicationIdentification/CPL-multiple-values-partially-supported.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } @Test public void compositionWithMultipleApplicationIdentificationFullyNegativeTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/ApplicationIdentification/CPL-multiple-values-non-supported.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 2); } @Test public void composition2020Test() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IMF-2020/CPL-2020_updated-core-constraints.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 0); Assert.assertEquals(applicationComposition.getCoreConstraintsSchema(), CoreConstraints.NAMESPACE_IMF_2020); } @Test public void composition2020WithoutAudioTrackTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IMF-2020/CPL-2020_no-audio-track.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 0); Assert.assertEquals(applicationComposition.getCoreConstraintsSchema(), CoreConstraints.NAMESPACE_IMF_2020); } @Test public void composition2016WithoutAudioTrackNegativeTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IMF-2020/CPL-2016_no-audio-track.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertTrue(imfErrorLogger.getErrors().stream().anyMatch(e -> e.getErrorCode() == IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR)); Assert.assertNull(applicationComposition); } }
4,964
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/st2067_2/IMPDeliveryTest.java
package com.netflix.imflibrary.st2067_2; import com.netflix.imflibrary.IMPDelivery; import com.netflix.imflibrary.InteroperableMasterPackage; import com.netflix.imflibrary.st0429_9.BasicMapProfileV2FileSet; import com.netflix.imflibrary.st0429_9.BasicMapProfileV2MappedFileSet; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; @Test(groups = "unit") public class IMPDeliveryTest { @Test public void testIMPDelivery() throws Exception { File inputFile = TestHelper.findResourceByPath("test_mapped_file_set"); BasicMapProfileV2MappedFileSet basicMapProfileV2MappedFileSet = new BasicMapProfileV2MappedFileSet(inputFile); BasicMapProfileV2FileSet basicMapProfileV2FileSet = new BasicMapProfileV2FileSet(basicMapProfileV2MappedFileSet); IMPDelivery impDelivery = new IMPDelivery(basicMapProfileV2FileSet); Assert.assertTrue(impDelivery.toString().length() > 0); Assert.assertTrue(impDelivery.isValid()); Assert.assertEquals(impDelivery.getInteroperableMasterPackages().size(), 1); InteroperableMasterPackage interoperableMasterPackage = impDelivery.getInteroperableMasterPackages().get(0); Assert.assertEquals(interoperableMasterPackage.getPackingListURI(), TestHelper.findResourceByPath("test_mapped_file_set/PKL_51edd4be-4506-494d-a58e-516553055c33.xml").toURI()); Assert.assertEquals(interoperableMasterPackage.getReferencedAssets().size(), 3); Assert.assertEquals(interoperableMasterPackage.getPackingList().getAssets().size(), 3); } }
4,965
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/st0429_8/PackingListTest.java
package com.netflix.imflibrary.st0429_8; import com.netflix.imflibrary.IMFErrorLoggerImpl; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.util.UUID; @Test(groups="unit") public class PackingListTest { @Test public void testPackingList() throws Exception { File inputFile = TestHelper.findResourceByPath("test_mapped_file_set/PKL_51edd4be-4506-494d-a58e-516553055c33.xml"); PackingList packingList = new PackingList(inputFile); Assert.assertEquals(packingList.getUUID(), UUID.fromString("51edd4be-4506-494d-a58e-516553055c33")); Assert.assertEquals(packingList.getAssets().size(), 3); Assert.assertTrue(packingList.toString().length() > 0); PackingList.Asset asset = packingList.getAssets().get(2); Assert.assertEquals(asset.getUUID(), UUID.fromString("682feecb-7516-4d93-b533-f40d4ce60539")); Assert.assertEquals(asset.getSize(), 2544L); Assert.assertEquals(asset.getType(),"text/xml"); Assert.assertEquals(asset.getOriginalFilename(),"CPL_682feecb-7516-4d93-b533-f40d4ce60539.xml"); Assert.assertTrue(asset.toString().length() > 0); } @Test public void testPackingList2016() throws Exception { File inputFile = TestHelper.findResourceByPath("PKL_2067_2_2016.xml"); PackingList packingList = new PackingList(inputFile); Assert.assertEquals(packingList.getUUID(), UUID.fromString("7281a71b-0dcb-4ed7-93a4-97b7929e2a7c")); Assert.assertEquals(packingList.getAssets().size(), 2); Assert.assertTrue(packingList.toString().length() > 0); PackingList.Asset asset = packingList.getAssets().get(0); Assert.assertEquals(asset.getUUID(), UUID.fromString("88b5b453-a342-46eb-bc0a-4c9645f4d627")); Assert.assertEquals(asset.getSize(), 19139240035L); Assert.assertEquals(asset.getType(),"application/mxf"); Assert.assertEquals(asset.getOriginalFilename(),"1.mxf"); Assert.assertTrue(asset.toString().length() > 0); } }
4,966
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/st0429_9/AssetMapTest.java
package com.netflix.imflibrary.st0429_9; import com.netflix.imflibrary.exceptions.IMFException; import org.smpte_ra.schemas._429_9._2007.am.AssetMapType; import org.smpte_ra.schemas._429_9._2007.am.AssetType; import org.smpte_ra.schemas._429_9._2007.am.ChunkType; import org.testng.Assert; import org.testng.annotations.Test; import java.math.BigInteger; import java.util.List; @Test(groups = "unit") public class AssetMapTest { @Test public void testAssetMapTypeConformanceBad1() { AssetMapType assetMapType = new AssetMapType(); //volume count is not 1 assetMapType.setVolumeCount(new BigInteger("2")); List errors = AssetMap.checkConformance(assetMapType); Assert.assertEquals(errors.size(), 2); } @Test public void testAssetMapTypeConformanceBad2() { ChunkType chunkType = new ChunkType(); AssetType.ChunkList chunkList = new AssetType.ChunkList(); //chunklist has two chunks chunkList.getChunk().add(chunkType); chunkList.getChunk().add(chunkType); AssetType assetType = new AssetType(); assetType.setChunkList(chunkList); AssetMapType.AssetList assetList = new AssetMapType.AssetList(); assetList.getAsset().add(assetType); AssetMapType assetMapType = new AssetMapType(); assetMapType.setAssetList(assetList); assetMapType.setVolumeCount(new BigInteger("1")); List errors = AssetMap.checkConformance(assetMapType); Assert.assertEquals(errors.size(), 1); } @Test public void testAssetMapTypeConformanceBad3() { ChunkType chunkType = new ChunkType(); //VolumeIndex in <Chunk> is not 1 chunkType.setVolumeIndex(new BigInteger("2")); AssetType.ChunkList chunkList = new AssetType.ChunkList(); chunkList.getChunk().add(chunkType); AssetType assetType = new AssetType(); assetType.setChunkList(chunkList); AssetMapType.AssetList assetList = new AssetMapType.AssetList(); assetList.getAsset().add(assetType); AssetMapType assetMapType = new AssetMapType(); assetMapType.setAssetList(assetList); assetMapType.setVolumeCount(new BigInteger("1")); List errors = AssetMap.checkConformance(assetMapType); Assert.assertEquals(errors.size(), 1); } @Test public void testAssetMapTypeConformanceBad4() { ChunkType chunkType = new ChunkType(); chunkType.setVolumeIndex(new BigInteger("1")); //Offset in <Chunk> is not 0 chunkType.setOffset(new BigInteger("1")); AssetType.ChunkList chunkList = new AssetType.ChunkList(); chunkList.getChunk().add(chunkType); AssetType assetType = new AssetType(); assetType.setChunkList(chunkList); AssetMapType.AssetList assetList = new AssetMapType.AssetList(); assetList.getAsset().add(assetType); AssetMapType assetMapType = new AssetMapType(); assetMapType.setAssetList(assetList); assetMapType.setVolumeCount(new BigInteger("1")); List errors = AssetMap.checkConformance(assetMapType); Assert.assertEquals(errors.size(), 1); } }
4,967
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/st2067_201/IMPAnalyzerTest.java
package com.netflix.imflibrary.st2067_201; import com.netflix.imflibrary.utils.ErrorLogger; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import static com.netflix.imflibrary.app.IMPAnalyzer.analyzePackage; @Test(groups = "unit") public class IMPAnalyzerTest { @Test public void IMPAnalyzerTest() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/CompleteIMP"); Map<String, List<ErrorLogger.ErrorObject>> errorMap = analyzePackage(inputFile); Assert.assertEquals(errorMap.size(), 7); errorMap.entrySet().stream().forEach( e -> { if (e.getKey().matches("CPL.*Conformance")) { Assert.assertEquals(e.getValue().size(), 6); } else if (e.getKey().matches("meridian.*")) { Assert.assertEquals(e.getValue().size(), 6); } else { Assert.assertEquals(e.getValue().size(), 0); } } ); } }
4,968
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/st2067_201/IABCompositionTest.java
package com.netflix.imflibrary.st2067_201; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.st2067_2.ApplicationComposition; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory; import com.netflix.imflibrary.st2067_2.Composition; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; @Test(groups = "unit") public class IABCompositionTest { @Test public void compositionPositiveTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_valid_iabsequence.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 0); } @Test public void compositionPositiveTestNonZeroChannelCount() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_valid_non_zero_essence_channelcount.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 0); } @Test public void compositionNegativeTestMissingAudio() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_invalid_missing_audio.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(),1); } @Test public void compositionNegativeTestEditRateMismatchMainVideo() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_invalid_iabsequence_wrong_editrate_main.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 2); } @Test public void compositionNegativeTestWrongTrackFile() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_invalid_iabsequence_wrong_trackfile.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); // Changing expected error count as the channel count is now being ignored as of // SMPTE ST 2067-201:2021, 5.9 IAB Essence Descriptor Constraints Assert.assertEquals(imfErrorLogger.getErrors().size(), 5); } @Test public void compositionNegativeTestHomogeneous() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_invalid_homogeneous.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(),2); } @Test public void compositionNegativeTestNoResource() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_invalid_no_resource.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } @Test public void compositionNegativeTestWrongBitDepth() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_invalid_wrong_bitdepth.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } @Test public void compositionNegativeTestWrongEssenceContainer() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_invalid_wrong_essence_container_ul.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } @Test public void compositionNegativeTestCodecPresent() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_invalid_codec_present.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } @Test public void compositionNegativeTestWrongSoundCompression() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_invalid_wrong_soundcompression.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } @Test public void compositionNegativeTestMissingAudioSamplingRate() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_valid_missing_audiosamplingrate.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } @Test public void compositionNegativeTestWrongElectroSpatialFormulation() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_invalid_wrong_electro_spatial_formulation.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } @Test public void compositionNegativeTestNoSubDescriptor() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_invalid_missing_subdescriptor.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 1); } @Test public void compositionNegativeTestWrongSubDescriptor() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_invalid_wrong_subdescriptor.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 2); } @Test public void compositionNegativeTestWrongSubDescriptorValues() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_invalid_wrong_subdescriptor_values.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Assert.assertEquals(imfErrorLogger.getErrors().size(), 4); } @Test public void correctDurationTest() throws IOException { File inputFile = TestHelper.findResourceByPath ("TestIMP/IAB/CPL/IAB_CPL_valid_iabsequence.xml"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationComposition composition = ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger); Composition.VirtualTrack iabTrack = composition.getVirtualTracks().stream().filter(vt -> vt.getSequenceTypeEnum() == Composition.SequenceTypeEnum.IABSequence).findFirst().orElse(null); Assert.assertNotNull(iabTrack); Assert.assertNotEquals(iabTrack.getDuration(), 0L); Assert.assertNotEquals(iabTrack.getDurationInTrackEditRateUnits(), 0L); } }
4,969
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/st2067_201/IABMXFValidationTest.java
package com.netflix.imflibrary.st2067_201; import com.netflix.imflibrary.utils.ErrorLogger; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; import java.util.List; import com.netflix.imflibrary.app.IMPAnalyzer; public class IABMXFValidationTest { @Test public void testValid() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f.mxf"); List<ErrorLogger.ErrorObject> errors = IMPAnalyzer.analyzeFile(inputFile); Assert.assertEquals(errors.size(), 6); } @Test public void testValidNonZeroChannelCount() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f_non_zero_channelcount.mxf"); List<ErrorLogger.ErrorObject> errors = IMPAnalyzer.analyzeFile(inputFile); Assert.assertEquals(errors.size(), 6); } @Test public void testInvalidEditRateMismatch() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f_editrate_mismatch.mxf"); List<ErrorLogger.ErrorObject> errors = IMPAnalyzer.analyzeFile(inputFile); Assert.assertEquals(errors.size(), 8); } @Test public void testInvalidNoConformsToSpecifications() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f_no_conformstospecifications.mxf"); List<ErrorLogger.ErrorObject> errors = IMPAnalyzer.analyzeFile(inputFile); Assert.assertEquals(errors.size(), 7); } @Test public void testInvalidNoSubDescriptor() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f_no_subdesc.mxf"); List<ErrorLogger.ErrorObject> errors = IMPAnalyzer.analyzeFile(inputFile); Assert.assertEquals(errors.size(), 3); } @Test public void testInvalidWrongCoding() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f_wrong_coding.mxf"); List<ErrorLogger.ErrorObject> errors = IMPAnalyzer.analyzeFile(inputFile); Assert.assertEquals(errors.size(), 7); } @Test public void testInvalidWrongConformsToSpecifications() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f_wrong_conformstospecifications_value.mxf"); List<ErrorLogger.ErrorObject> errors = IMPAnalyzer.analyzeFile(inputFile); Assert.assertEquals(errors.size(), 7); } @Test public void testInvalidWrongEssence() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f_wrong_essence_ul.mxf"); List<ErrorLogger.ErrorObject> errors = IMPAnalyzer.analyzeFile(inputFile); Assert.assertEquals(errors.size(), 7); } @Test public void testInvalidWrongMCAValues() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f_wrong_mca_values.mxf"); List<ErrorLogger.ErrorObject> errors = IMPAnalyzer.analyzeFile(inputFile); Assert.assertEquals(errors.size(), 9); } @Test public void testInvalidWrongQuantizationBits() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f_wrong_qb.mxf"); List<ErrorLogger.ErrorObject> errors = IMPAnalyzer.analyzeFile(inputFile); Assert.assertEquals(errors.size(), 7); } @Test public void testInvalidWrongSubDescriptorAudioChannel() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f_wrong_subdesc_ac.mxf"); List<ErrorLogger.ErrorObject> errors = IMPAnalyzer.analyzeFile(inputFile); Assert.assertEquals(errors.size(), 4); } @Test public void testInvalidWrongSubDescriptorSoundFieldGroup() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f_wrong_subdesc_sg.mxf"); List<ErrorLogger.ErrorObject> errors = IMPAnalyzer.analyzeFile(inputFile); Assert.assertEquals(errors.size(), 4); } @Test public void testInvalidWrongSubDescriptorGroupOfSoundfieldGroup() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f_wrong_subdesc_gosg.mxf"); List<ErrorLogger.ErrorObject> errors = IMPAnalyzer.analyzeFile(inputFile); Assert.assertEquals(errors.size(), 4); } @Test public void testInvalidWrongIndexEditRate() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f_wrong_index_edit_rate.mxf"); List<ErrorLogger.ErrorObject> errors = IMPAnalyzer.analyzeFile(inputFile); Assert.assertEquals(errors.size(), 7); } }
4,970
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/writerTools/AssetMapBuilderFunctionalTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.RESTfulInterfaces.IMPValidator; import com.netflix.imflibrary.RESTfulInterfaces.PayloadRecord; import com.netflix.imflibrary.exceptions.IMFAuthoringException; import com.netflix.imflibrary.st0429_9.AssetMap; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.utils.Utilities; import com.netflix.imflibrary.writerTools.utils.IMFUtils; import org.testng.Assert; import org.testng.annotations.Test; import org.xml.sax.SAXException; import testUtils.TestHelper; import javax.xml.bind.JAXBException; import javax.xml.datatype.XMLGregorianCalendar; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * A test for the AssetMapBuilder */ @Test(groups = "functional") public class AssetMapBuilderFunctionalTest { @Test public void assetMapBuilderTest() throws IOException, SAXException, JAXBException, URISyntaxException { File inputFile = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/ASSETMAP.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); AssetMap assetMap = new AssetMap(resourceByteRangeProvider); /** * Build the AssetMapBuilder's AssetList */ List<AssetMap.Asset> assets = assetMap.getAssetList(); List<AssetMapBuilder.Asset> assetMapBuilderAssets = new ArrayList<>(); for(AssetMap.Asset asset : assets){ String annotationText = (asset.isPackingList() ? "PKL" : "Netflix Asset"); String language = "en"; AssetMapBuilder.Chunk chunk = new AssetMapBuilder.Chunk(asset.getPath().toString(), 10L); //All assets will have a length of 10 bytes perhaps okay for a functional test. List<AssetMapBuilder.Chunk> chunks = new ArrayList<AssetMapBuilder.Chunk>() {{ add(chunk);}}; AssetMapBuilder.Asset assetMapBuilderAsset = new AssetMapBuilder.Asset(asset.getUUID(), AssetMapBuilder.buildAssetMapUserTextType_2007(annotationText, language), asset.isPackingList(), chunks); assetMapBuilderAssets.add(assetMapBuilderAsset); } org.smpte_ra.schemas._429_9._2007.am.UserText annotationText = AssetMapBuilder.buildAssetMapUserTextType_2007("Photon AssetMapBuilder", "en"); org.smpte_ra.schemas._429_9._2007.am.UserText creator = AssetMapBuilder.buildAssetMapUserTextType_2007("Netflix", "en"); XMLGregorianCalendar issueDate = IMFUtils.createXMLGregorianCalendar(); org.smpte_ra.schemas._429_9._2007.am.UserText issuer = AssetMapBuilder.buildAssetMapUserTextType_2007("Netflix", "en"); /** * Create a temporary working directory under home */ Path tempPath = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "IMFDocuments"); File tempDir = tempPath.toFile(); IMFErrorLogger assetMapBuilderErrorLogger = new IMFErrorLoggerImpl(); List<ErrorLogger.ErrorObject> errors = new AssetMapBuilder(assetMap.getUUID(), annotationText, creator, issueDate, issuer, assetMapBuilderAssets, tempDir, assetMapBuilderErrorLogger).build(); List<ErrorLogger.ErrorObject> fatalErrors = errors.stream().filter(e -> e.getErrorLevel().equals(IMFErrorLogger .IMFErrors.ErrorLevels.FATAL)).collect(Collectors.toList()); if(fatalErrors.size() > 0) { throw new IMFAuthoringException(String.format("Fatal errors occurred while generating the AssetMap. " + "Please see following error messages %s", Utilities.serializeObjectCollectionToString(fatalErrors))); } File assetMapFile = null; for(File file : tempDir.listFiles()){ if(file.getName().contains("ASSETMAP.xml")){ assetMapFile = file; } } if(assetMapFile == null){ throw new IMFAuthoringException(String.format("AssetMap file does not exist in the working directory %s, IMP is incomplete", tempDir.getAbsolutePath())); } Assert.assertTrue(assetMapFile.length() > 0); List<ErrorLogger.ErrorObject> assetMapValidationErrors = IMPValidator.validateAssetMap(new PayloadRecord(new FileByteRangeProvider(assetMapFile).getByteRangeAsBytes(0, assetMapFile.length()-1), PayloadRecord.PayloadAssetType.AssetMap, 0L, 0L)); Assert.assertTrue(assetMapValidationErrors.size() == 0); //Destroy the temporary working directory tempDir.delete(); } }
4,971
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/writerTools/PackingListBuilderFunctionalTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools; /** * Functional test for the PackingListBuilder */ import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.RESTfulInterfaces.IMPValidator; import com.netflix.imflibrary.RESTfulInterfaces.PayloadRecord; import com.netflix.imflibrary.exceptions.IMFAuthoringException; import com.netflix.imflibrary.st0429_8.PackingList; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.utils.Utilities; import com.netflix.imflibrary.writerTools.utils.IMFUtils; import org.testng.Assert; import org.testng.annotations.Test; import org.xml.sax.SAXException; import testUtils.TestHelper; import javax.xml.bind.JAXBException; import javax.xml.datatype.XMLGregorianCalendar; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; @Test(groups = "functional") public class PackingListBuilderFunctionalTest { @Test public void packingListBuilder_2007_Test() throws IOException, SAXException, JAXBException { File inputFile = TestHelper.findResourceByPath("TestIMP/NYCbCrLT_3840x2160x23.98x10min/PKL_0429fedd-b55d-442a-aa26-2a81ec71ed05.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); PackingList packingList = new PackingList(resourceByteRangeProvider); List<PackingList.Asset> assets = packingList.getAssets(); List<PackingListBuilder.PackingListBuilderAsset_2007> packingListBuilderAssets = new ArrayList<>(); for(PackingList.Asset asset : assets){ org.smpte_ra.schemas._429_8._2007.pkl.UserText annotationText = PackingListBuilder.buildPKLUserTextType_2007("Netflix", "en"); org.smpte_ra.schemas._429_8._2007.pkl.UserText originalFileName = PackingListBuilder.buildPKLUserTextType_2007(asset.getOriginalFilename(), "en"); PackingListBuilder.PackingListBuilderAsset_2007 asset_2007 = new PackingListBuilder.PackingListBuilderAsset_2007(asset.getUUID(), annotationText, asset.getHash(), asset.getSize(), PackingListBuilder.PKLAssetTypeEnum.getAssetTypeEnum(asset.getType()), originalFileName); packingListBuilderAssets.add(asset_2007); } /** * Create a temporary working directory under home */ Path tempPath = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "IMFDocuments"); File tempDir = tempPath.toFile(); IMFErrorLogger packingListBuilderErrorLogger = new IMFErrorLoggerImpl(); org.smpte_ra.schemas._429_8._2007.pkl.UserText annotationText = PackingListBuilder.buildPKLUserTextType_2007("Photon PackingListBuilder", "en"); org.smpte_ra.schemas._429_8._2007.pkl.UserText creator = PackingListBuilder.buildPKLUserTextType_2007("Netflix", "en"); XMLGregorianCalendar issueDate = IMFUtils.createXMLGregorianCalendar(); org.smpte_ra.schemas._429_8._2007.pkl.UserText issuer = PackingListBuilder.buildPKLUserTextType_2007("Netflix", "en"); new PackingListBuilder(packingList.getUUID(), issueDate, tempDir, packingListBuilderErrorLogger).buildPackingList_2007(annotationText, issuer, creator, packingListBuilderAssets); imfErrorLogger.addAllErrors(packingList.getErrors()); if(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, 0, imfErrorLogger.getNumberOfErrors()).size() > 0){ throw new IMFAuthoringException(String.format("Fatal errors occurred while generating the PackingList. Please see following error messages %s", Utilities.serializeObjectCollectionToString(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, 0, imfErrorLogger.getNumberOfErrors())))); } File pklOutputFile = null; for(File file : tempDir.listFiles()){ if(file.getName().contains("PKL-")){ pklOutputFile = file; } } if(pklOutputFile == null){ throw new IMFAuthoringException(String.format("PackingList file does not exist in the working directory %s, cannot generate the rest of the documents", tempDir.getAbsolutePath())); } Assert.assertTrue(pklOutputFile.length() > 0); resourceByteRangeProvider = new FileByteRangeProvider(pklOutputFile); List<ErrorLogger.ErrorObject> errors = IMPValidator.validatePKL(new PayloadRecord(resourceByteRangeProvider.getByteRangeAsBytes(0, pklOutputFile.length()-1), PayloadRecord.PayloadAssetType.PackingList, 0L, 0L)); Assert.assertEquals(errors.size(), 0); //Destroy the temporary working directory tempDir.delete(); } @Test public void packingListBuilder_2016_Test() throws IOException, SAXException, JAXBException { File inputFile = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/PKL_befcd2d4-f35c-45d7-99bb-7f64b51b103c_corrected.xml"); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); PackingList packingList = new PackingList(resourceByteRangeProvider); imfErrorLogger.addAllErrors(packingList.getErrors()); List<PackingList.Asset> assets = packingList.getAssets(); List<PackingListBuilder.PackingListBuilderAsset_2016> packingListBuilderAssets = new ArrayList<>(); for(PackingList.Asset asset : assets){ org.smpte_ra.schemas._2067_2._2016.pkl.UserText annotationText = PackingListBuilder.buildPKLUserTextType_2016("Netflix", "en"); org.smpte_ra.schemas._2067_2._2016.pkl.UserText originalFileName = PackingListBuilder.buildPKLUserTextType_2016(asset.getOriginalFilename(), "en"); org.w3._2000._09.xmldsig_.DigestMethodType hashAlgorithm = new org.w3._2000._09.xmldsig_.DigestMethodType(); hashAlgorithm.setAlgorithm(asset.getHashAlgorithm()); PackingListBuilder.PackingListBuilderAsset_2016 asset_2016 = new PackingListBuilder.PackingListBuilderAsset_2016(asset.getUUID(), annotationText, asset.getHash(), hashAlgorithm, asset.getSize(), PackingListBuilder.PKLAssetTypeEnum.getAssetTypeEnum(asset.getType()), originalFileName); packingListBuilderAssets.add(asset_2016); } /** * Create a temporary working directory under home */ Path tempPath = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "IMFDocuments"); File tempDir = tempPath.toFile(); IMFErrorLogger packingListBuilderErrorLogger = new IMFErrorLoggerImpl(); org.smpte_ra.schemas._2067_2._2016.pkl.UserText annotationText = PackingListBuilder.buildPKLUserTextType_2016("Photon PackingListBuilder", "en"); org.smpte_ra.schemas._2067_2._2016.pkl.UserText creator = PackingListBuilder.buildPKLUserTextType_2016("Netflix", "en"); XMLGregorianCalendar issueDate = IMFUtils.createXMLGregorianCalendar(); org.smpte_ra.schemas._2067_2._2016.pkl.UserText issuer = PackingListBuilder.buildPKLUserTextType_2016("Netflix", "en"); new PackingListBuilder(packingList.getUUID(), issueDate, tempDir, packingListBuilderErrorLogger).buildPackingList_2016(annotationText, issuer, creator, packingListBuilderAssets); if(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, 0, imfErrorLogger.getNumberOfErrors()).size() > 0){ throw new IMFAuthoringException(String.format("Fatal errors occurred while generating the PackingList. Please see following error messages %s", Utilities.serializeObjectCollectionToString(imfErrorLogger.getErrors(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, 0, imfErrorLogger.getNumberOfErrors())))); } File pklOutputFile = null; for(File file : tempDir.listFiles()){ if(file.getName().contains("PKL-")){ pklOutputFile = file; } } if(pklOutputFile == null){ throw new IMFAuthoringException(String.format("PackingList file does not exist in the working directory %s, cannot generate the rest of the documents", tempDir.getAbsolutePath())); } Assert.assertTrue(pklOutputFile.length() > 0); resourceByteRangeProvider = new FileByteRangeProvider(pklOutputFile); List<ErrorLogger.ErrorObject> pklValidationErrors = IMPValidator.validatePKL(new PayloadRecord(resourceByteRangeProvider.getByteRangeAsBytes(0, pklOutputFile.length()-1), PayloadRecord.PayloadAssetType.PackingList, 0L, 0L)); Assert.assertTrue(pklValidationErrors.size() == 0); //Destroy the temporary working directory tempDir.delete(); } }
4,972
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/writerTools/IMPBuilderFunctionalTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools; import com.netflix.imflibrary.IMFConstraints; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.MXFOperationalPattern1A; import com.netflix.imflibrary.RESTfulInterfaces.IMPValidator; import com.netflix.imflibrary.RESTfulInterfaces.PayloadRecord; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.header.GenericPackage; import com.netflix.imflibrary.st0377.header.Preface; import com.netflix.imflibrary.st0377.header.SourcePackage; import com.netflix.imflibrary.st2067_2.Application2ExtendedComposition; import com.netflix.imflibrary.st2067_2.ApplicationComposition; import com.netflix.imflibrary.st2067_2.ApplicationCompositionFactory; import com.netflix.imflibrary.utils.ByteArrayByteRangeProvider; import com.netflix.imflibrary.utils.ByteArrayDataProvider; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import com.netflix.imflibrary.utils.UUIDHelper; import com.netflix.imflibrary.writerTools.utils.IMFUtils; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.xml.sax.SAXException; import testUtils.TestHelper; import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; /** * A test for the IMF Master Package Builder */ @Test(groups = "functional") public class IMPBuilderFunctionalTest { @DataProvider(name = "cplList") private Object[][] getCplList() { return new Object[][] { {"TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4.xml", "2013", true, 1}, {"TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_duplicate_source_encoding_element.xml", "2013", true, 1}, {"TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4.xml", "2013", false, 0}, {"TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_duplicate_source_encoding_element.xml", "2013", false, 0}, {"TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4.xml", "2016", true, 1}, {"TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_duplicate_source_encoding_element.xml", "2016", true, 1}, {"TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4.xml", "2016", false, 0}, {"TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4_duplicate_source_encoding_element.xml", "2016", false, 0}, {"TestIMP/IAB/CompleteIMP/CPL_e0265fda-cb35-4e35-a4e4-4f44d82d2a52.xml", "2016", false, 0}, {"TestIMP/IMF-2020/CPL-2020_no-audio-track.xml", "2020", false, 0}, {"TestIMP/IMF-2020/CPL-2020_no-audio-track.xml", "2016", false, 1}, {"TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4.xml", "2020", true, 1}, {"TestIMP/Netflix_Sony_Plugfest_2015/CPL_BLACKL_202_HD_REC709_178_ENG_fe8cf2f4-1bcd-4145-8f72-6775af4038c4.xml", "2020", false, 0}, }; } @Test(dataProvider = "cplList") public void impBuilderTest(String cplFilePath, String schemaVersion, boolean useHeaderPartition, int expectedCPLErrors) throws IOException, ParserConfigurationException, SAXException, JAXBException, URISyntaxException, NoSuchAlgorithmException { File inputFile = TestHelper.findResourceByPath(cplFilePath); ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(inputFile); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(resourceByteRangeProvider, imfErrorLogger); buildIMPAndValidate(applicationComposition, schemaVersion, expectedCPLErrors, useHeaderPartition, imfErrorLogger); } private void buildIMPAndValidate(ApplicationComposition applicationComposition, String schemaVersion, int cplErrorsExpected, boolean useHeaderPartition, IMFErrorLogger imfErrorLogger) throws IOException, ParserConfigurationException, SAXException, JAXBException, URISyntaxException, NoSuchAlgorithmException { /** * Create a temporary working directory under home */ Path tempPath = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "IMFDocuments"); File tempDir = tempPath.toFile(); if(useHeaderPartition) { if (schemaVersion.equals("2016")) { IMPBuilder.buildIMP_2016("IMP", "Netflix", applicationComposition.getVirtualTracks(), applicationComposition.getEditRate(), Application2ExtendedComposition.SCHEMA_URI_APP2E_2016, buildTrackFileMetadataMap(imfErrorLogger), tempDir); } else if (schemaVersion.equals("2020")) { IMPBuilder.buildIMP_2016("IMP", "Netflix", applicationComposition.getVirtualTracks(), applicationComposition.getEditRate(), Application2ExtendedComposition.SCHEMA_URI_APP2E_2020, buildTrackFileMetadataMap(imfErrorLogger), tempDir); } else if (schemaVersion.equals("2013")) { IMPBuilder.buildIMP_2013("IMP", "Netflix", applicationComposition.getVirtualTracks(), applicationComposition.getEditRate(), Application2ExtendedComposition.SCHEMA_URI_APP2E_2014, buildTrackFileMetadataMap(imfErrorLogger), tempDir); } } else { if (schemaVersion.equals("2016")) { IMPBuilder.buildIMP_2016("IMP", "Netflix", applicationComposition.getVirtualTracks(), applicationComposition.getEditRate(), Application2ExtendedComposition.SCHEMA_URI_APP2E_2016, buildTrackFileInfoMap(imfErrorLogger), tempDir, applicationComposition.getEssenceDescriptorDomNodeMap()); } else if (schemaVersion.equals("2020")) { IMPBuilder.buildIMP_2016("IMP", "Netflix", applicationComposition.getVirtualTracks(), applicationComposition.getEditRate(), Application2ExtendedComposition.SCHEMA_URI_APP2E_2020, buildTrackFileInfoMap(imfErrorLogger), tempDir, applicationComposition.getEssenceDescriptorDomNodeMap()); } else if (schemaVersion.equals("2013")) { IMPBuilder.buildIMP_2013("IMP", "Netflix", applicationComposition.getVirtualTracks(), applicationComposition.getEditRate(), Application2ExtendedComposition.SCHEMA_URI_APP2E_2014, buildTrackFileInfoMap(imfErrorLogger), tempDir, applicationComposition.getEssenceDescriptorDomNodeMap()); } } boolean assetMapFound = false; boolean pklFound = false; boolean cplFound = false; File assetMapFile = null; File pklFile = null; File cplFile = null; for(File file : tempDir.listFiles()){ if(file.getName().contains("ASSETMAP.xml")){ assetMapFound = true; assetMapFile = file; } else if(file.getName().contains("PKL-")){ pklFound = true; pklFile = file; } else if(file.getName().contains("CPL-")){ cplFound = true; cplFile = file; } } Assert.assertTrue(assetMapFound == true); Assert.assertTrue(pklFound == true); Assert.assertTrue(cplFound == true); ResourceByteRangeProvider fileByteRangeProvider = new FileByteRangeProvider(assetMapFile); byte[] documentBytes = fileByteRangeProvider.getByteRangeAsBytes(0, fileByteRangeProvider.getResourceSize()-1); PayloadRecord payloadRecord = new PayloadRecord(documentBytes, PayloadRecord.PayloadAssetType.AssetMap, 0L, 0L); List<ErrorLogger.ErrorObject> errors = IMPValidator.validateAssetMap(payloadRecord); Assert.assertEquals(errors.size(), 0); fileByteRangeProvider = new FileByteRangeProvider(pklFile); documentBytes = fileByteRangeProvider.getByteRangeAsBytes(0, fileByteRangeProvider.getResourceSize()-1); payloadRecord = new PayloadRecord(documentBytes, PayloadRecord.PayloadAssetType.PackingList, 0L, 0L); errors = IMPValidator.validatePKL(payloadRecord); Assert.assertEquals(errors.size(), 0); fileByteRangeProvider = new FileByteRangeProvider(cplFile); documentBytes = fileByteRangeProvider.getByteRangeAsBytes(0, fileByteRangeProvider.getResourceSize()-1); payloadRecord = new PayloadRecord(documentBytes, PayloadRecord.PayloadAssetType.CompositionPlaylist, 0L, 0L); errors = IMPValidator.validateCPL(payloadRecord); Assert.assertEquals(errors.size(), cplErrorsExpected); } private Map<UUID, IMPBuilder.IMFTrackFileMetadata> buildTrackFileMetadataMap(IMFErrorLogger imfErrorLogger) throws IOException, NoSuchAlgorithmException { Map<UUID, IMPBuilder.IMFTrackFileMetadata> imfTrackFileMetadataMap = new HashMap<>(); ResourceByteRangeProvider resourceByteRangeProvider; List<String> fileNames = Arrays.asList("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015.mxf.hdr", "TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015_ENG20.mxf.hdr", "TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015_ENG51.mxf.hdr"); for(String fileName: fileNames) { File headerPartition1 = TestHelper.findResourceByPath(fileName); resourceByteRangeProvider = new FileByteRangeProvider(headerPartition1); byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(0, resourceByteRangeProvider.getResourceSize() - 1); ByteProvider byteProvider = new ByteArrayDataProvider(bytes); HeaderPartition headerPartition = new HeaderPartition(byteProvider, 0L, bytes.length, imfErrorLogger); MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A = MXFOperationalPattern1A.checkOperationalPattern1ACompliance(headerPartition, imfErrorLogger); IMFConstraints.HeaderPartitionIMF headerPartitionIMF = IMFConstraints.checkIMFCompliance(headerPartitionOP1A, imfErrorLogger); Preface preface = headerPartitionIMF.getHeaderPartitionOP1A().getHeaderPartition().getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage) genericPackage; UUID packageUUID = filePackage.getPackageMaterialNumberasUUID(); imfTrackFileMetadataMap.put(packageUUID, new IMPBuilder.IMFTrackFileMetadata(bytes, IMFUtils.generateSHA1Hash(new ByteArrayByteRangeProvider(bytes)), CompositionPlaylistBuilder_2016.defaultHashAlgorithm, fileName, bytes.length)); } return imfTrackFileMetadataMap; } private Map<UUID, IMPBuilder.IMFTrackFileInfo> buildTrackFileInfoMap(IMFErrorLogger imfErrorLogger) throws IOException, NoSuchAlgorithmException { Map<UUID, IMPBuilder.IMFTrackFileInfo> uuidimfTrackFileInfoMap = new HashMap<>(); String hash1 = "yCsxE1M6xmEGkVoXAWWjvfq2VHM="; uuidimfTrackFileInfoMap.put(UUIDHelper.fromUUIDAsURNStringToUUID("urn:uuid:ec9f8003-655e-438a-b30a-d7700ec4cb6f"), new IMPBuilder.IMFTrackFileInfo(hash1.getBytes(), CompositionPlaylistBuilder_2016.defaultHashAlgorithm, "Netflix_Plugfest_Oct2015.mxf", 10517511198L, false)); String hash2 = "9zit4G2zsmwpLqwXwFEJTu7UG50="; uuidimfTrackFileInfoMap.put(UUIDHelper.fromUUIDAsURNStringToUUID("urn:uuid:7be07495-1aaa-4a69-8b92-3ec162122b34"), new IMPBuilder.IMFTrackFileInfo(hash2.getBytes(), CompositionPlaylistBuilder_2016.defaultHashAlgorithm, "Netflix_Plugfest_Oct2015_ENG20.mxf", 94532279L, false)); String hash3 = "9zit4G2zsmwpLqwXwFEJTu7UG50="; uuidimfTrackFileInfoMap.put(UUIDHelper.fromUUIDAsURNStringToUUID("urn:uuid:c808001c-da54-4295-a721-dcaa00659699"), new IMPBuilder.IMFTrackFileInfo(hash3.getBytes(), CompositionPlaylistBuilder_2016.defaultHashAlgorithm, "Netflix_Plugfest_Oct2015_ENG51.mxf", 94532279L, false)); return uuidimfTrackFileInfoMap; } }
4,973
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/utils/UUIDHelperTest.java
package com.netflix.imflibrary.utils; import com.netflix.imflibrary.exceptions.IMFException; import org.testng.annotations.Test; @Test(groups = "unit") public class UUIDHelperTest { @Test(expectedExceptions = IMFException.class) public void testUUIDHelperBadInput() { UUIDHelper.fromUUIDAsURNStringToUUID("682feecb-7516-4d93-b533-f40d4ce60539"); } }
4,974
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/utils/DOMNodeObjectModelTest.java
package com.netflix.imflibrary.utils; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.PrimerPack; import com.netflix.imflibrary.st0377.header.InterchangeObject; import com.sandflow.smpte.klv.Triplet; import org.testng.Assert; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Node; import testUtils.TestHelper; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * A set of tests for DOMNodeObjectModel */ @Test(groups = "unit") public class DOMNodeObjectModelTest { private ByteProvider getByteProvider(ResourceByteRangeProvider resourceByteRangeProvider, KLVPacket.Header header) throws IOException { byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(header.getByteOffset(), header.getByteOffset() + header.getKLSize() + header.getVSize()); ByteProvider byteProvider = new ByteArrayDataProvider(bytes); return byteProvider; } public List<DOMNodeObjectModel> setUp(File inputFile) throws IOException, ParserConfigurationException { IMFErrorLogger imfErrorLogger1 = new IMFErrorLoggerImpl(); List<Node> essenceDescriptorNodes1 = new ArrayList<>(); List<DOMNodeObjectModel> essenceDescriptorDOMNodeObjectModels1 = new ArrayList<>(); ResourceByteRangeProvider resourceByteRangeProvider1 = new FileByteRangeProvider(inputFile); byte[] bytes1 = resourceByteRangeProvider1.getByteRangeAsBytes(0, resourceByteRangeProvider1.getResourceSize() - 1); ByteProvider byteProvider1 = new ByteArrayDataProvider(bytes1); HeaderPartition headerPartition1 = new HeaderPartition(byteProvider1, 0L, bytes1.length, imfErrorLogger1); List<InterchangeObject.InterchangeObjectBO> essenceDescriptors1 = headerPartition1.getEssenceDescriptors(); for (InterchangeObject.InterchangeObjectBO essenceDescriptor : essenceDescriptors1) { List<KLVPacket.Header> subDescriptorHeaders = new ArrayList<>(); List<InterchangeObject.InterchangeObjectBO> subDescriptors = headerPartition1.getSubDescriptors(essenceDescriptor); for (InterchangeObject.InterchangeObjectBO subDescriptorBO : subDescriptors) { if (subDescriptorBO != null) { subDescriptorHeaders.add(subDescriptorBO.getHeader()); } } /*Create a dom*/ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document document = docBuilder.newDocument(); //DocumentFragment documentFragment = this.getEssenceDescriptorAsDocumentFragment(document, headerPartitionTuple, essenceDescriptorHeader, subDescriptorHeaders); PrimerPack primerPack = headerPartition1.getPrimerPack(); RegXMLLibHelper regXMLLibHelper = new RegXMLLibHelper(primerPack.getHeader(), getByteProvider(resourceByteRangeProvider1, primerPack.getHeader())); Triplet essenceDescriptorTriplet = regXMLLibHelper.getTripletFromKLVHeader(essenceDescriptor.getHeader(), getByteProvider(resourceByteRangeProvider1, essenceDescriptor.getHeader())); //DocumentFragment documentFragment = this.regXMLLibHelper.getDocumentFragment(essenceDescriptorTriplet, document); /*Get the Triplets corresponding to the SubDescriptors*/ List<Triplet> subDescriptorTriplets = new ArrayList<>(); for (KLVPacket.Header subDescriptorHeader : subDescriptorHeaders) { subDescriptorTriplets.add(regXMLLibHelper.getTripletFromKLVHeader(subDescriptorHeader, this.getByteProvider(resourceByteRangeProvider1, subDescriptorHeader))); } DocumentFragment documentFragment = regXMLLibHelper.getEssenceDescriptorDocumentFragment(essenceDescriptorTriplet, subDescriptorTriplets, document, imfErrorLogger1); Node node = documentFragment.getFirstChild(); essenceDescriptorNodes1.add(node); essenceDescriptorDOMNodeObjectModels1.add(new DOMNodeObjectModel(node)); } return essenceDescriptorDOMNodeObjectModels1; } @Test public void domNodeObjectModelEquivalenceNegativeTest() throws IOException, ParserConfigurationException { File inputFile1 = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015_ENG20.mxf.hdr"); File inputFile2 = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015_ENG51.mxf.hdr"); List<DOMNodeObjectModel> domNodeObjectModels = new ArrayList<>(); domNodeObjectModels.addAll(setUp(inputFile1)); domNodeObjectModels.addAll(setUp(inputFile2)); Set<String> ignoreSet = new HashSet<>(); ignoreSet.add("InstanceUID"); DOMNodeObjectModel curr = domNodeObjectModels.get(0).createDOMNodeObjectModelIgnoreSet(domNodeObjectModels.get(0), ignoreSet); boolean result = true; for(int i=1; i<domNodeObjectModels.size(); i++){ result &= curr.equals(domNodeObjectModels.get(i).createDOMNodeObjectModelIgnoreSet(domNodeObjectModels.get(i), ignoreSet)); } Assert.assertTrue(result == false); } @Test public void domNodeObjectModelEquivalencePositiveTest() throws IOException, ParserConfigurationException { File inputFile1 = TestHelper.findResourceByPath("TestIMP/Netflix_Sony_Plugfest_2015/Netflix_Plugfest_Oct2015_ENG20.mxf.hdr"); List<DOMNodeObjectModel> domNodeObjectModels = new ArrayList<>(); domNodeObjectModels.addAll(setUp(inputFile1)); domNodeObjectModels.addAll(setUp(inputFile1)); Set<String> ignoreSet = new HashSet<>(); ignoreSet.add("InstanceUID"); DOMNodeObjectModel curr = domNodeObjectModels.get(0).createDOMNodeObjectModelIgnoreSet(domNodeObjectModels.get(0), ignoreSet); boolean result = true; for(int i=1; i<domNodeObjectModels.size(); i++){ result &= curr.equals(domNodeObjectModels.get(i).createDOMNodeObjectModelIgnoreSet(domNodeObjectModels.get(i), ignoreSet)); } Assert.assertTrue(result == true); } }
4,975
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/utils/FileDataProviderTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary.utils; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.*; import java.util.Arrays; @Test(groups = "unit") public class FileDataProviderTest { File inputFile; InputStream inputStream; @BeforeClass public void beforeClass() { inputFile = TestHelper.findResourceByPath("PKL_e788efe2-1782-4b09-b56d-1336da2413d5.xml"); } @BeforeMethod public void beforeMethod() throws FileNotFoundException { inputStream = new FileInputStream(inputFile); } @AfterMethod public void AfterMethod() throws IOException { if (inputStream != null) { inputStream.close(); } } @Test public void testGetBytes() throws IOException { byte[] refBytes = Arrays.copyOf(TestHelper.toByteArray(inputStream), 100); ByteProvider byteProvider = new FileDataProvider(this.inputFile); byte[] bytes = byteProvider.getBytes(100); Assert.assertEquals(refBytes, bytes); } @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "Could not read .*") public void testGetBytesLarge() throws IOException { long length = inputFile.length(); Assert.assertTrue(length < Integer.MAX_VALUE); ByteProvider byteProvider = new FileDataProvider(this.inputFile); byteProvider.getBytes((int)length + 1); } @Test public void testSkipBytes() throws IOException { ByteProvider byteProvider = new FileDataProvider(this.inputFile); byteProvider.skipBytes(100L); byte[] bytes = byteProvider.getBytes(1); Assert.assertEquals(bytes.length, 1); Assert.assertEquals(bytes[0], 99); } @Test public void testSkipBytesLarge() throws IOException { long length = inputFile.length(); Assert.assertTrue(length < Integer.MAX_VALUE); ByteProvider byteProvider = new FileDataProvider(this.inputFile); byteProvider.skipBytes(length + 1); } }
4,976
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/utils/FileByteRangeProviderTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary.utils; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.*; import java.nio.file.Files; @Test(groups = "unit") public class FileByteRangeProviderTest { private File file; private FileByteRangeProvider fileByteRangeProvider; @BeforeClass public void setUp() throws Exception { String keyboard = "qwertyuiopasdfghjklzxcvbnm"; this.file = File.createTempFile("test_file",".tmp"); FileWriter fileWriter = new FileWriter(this.file); try { fileWriter.write(keyboard); } finally { if (fileWriter != null) { fileWriter.close(); } } this.fileByteRangeProvider = new FileByteRangeProvider(this.file); } @AfterClass public void tearDown() throws Exception { Assert.assertTrue(this.file.delete()); } @Test public void testGetResourceSize() { Assert.assertEquals(26L, this.fileByteRangeProvider.getResourceSize()); } @Test public void testGetByteRangeWithRangeStart() throws IOException { File workingDirectory = Files.createTempDirectory(null).toFile(); File file = this.fileByteRangeProvider.getByteRange(24, workingDirectory); Assert.assertEquals(2L, file.length()); BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); Assert.assertEquals("nm", bufferedReader.readLine()); } @Test public void testGetByteRange() throws IOException { File workingDirectory = Files.createTempDirectory(null).toFile(); File file = this.fileByteRangeProvider.getByteRange(3, 9, workingDirectory); Assert.assertEquals(7L, file.length()); BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); Assert.assertEquals("rtyuiop", bufferedReader.readLine()); } }
4,977
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/utils/ByteArrayDataProviderTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary.utils; import testUtils.TestHelper; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; @Test(groups = "unit") public class ByteArrayDataProviderTest { File inputFile; InputStream inputStream; @BeforeClass public void beforeClass() { inputFile = TestHelper.findResourceByPath("PKL_e788efe2-1782-4b09-b56d-1336da2413d5.xml"); } @BeforeMethod public void beforeMethod() throws FileNotFoundException { inputStream = new FileInputStream(inputFile); } @AfterMethod public void AfterMethod() throws IOException { if (inputStream != null) { inputStream.close(); } } @Test public void testGetBytes() throws IOException { byte[] refBytes = Arrays.copyOf(TestHelper.toByteArray(inputStream), 100); ByteProvider byteProvider = new ByteArrayDataProvider(Files.readAllBytes(Paths.get(this.inputFile.toURI()))); byte[] bytes = byteProvider.getBytes(100); Assert.assertEquals(refBytes, bytes); } @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "Cannot read .*") public void testGetBytesLarge() throws IOException { long length = inputFile.length(); Assert.assertTrue(length < Integer.MAX_VALUE); ByteProvider byteProvider = new ByteArrayDataProvider(Files.readAllBytes(Paths.get(this.inputFile.toURI()))); byteProvider.getBytes((int)length + 1); } @Test public void testSkipBytes() throws IOException { ByteProvider byteProvider = new ByteArrayDataProvider(Files.readAllBytes(Paths.get(this.inputFile.toURI()))); byteProvider.skipBytes(100L); byte[] bytes = byteProvider.getBytes(1); Assert.assertEquals(bytes.length, 1); Assert.assertEquals(bytes[0], 99); } @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "Cannot skip .*") public void testSkipBytesLarge() throws IOException { long length = inputFile.length(); Assert.assertTrue(length < Integer.MAX_VALUE); ByteProvider byteProvider = new ByteArrayDataProvider(Files.readAllBytes(Paths.get(this.inputFile.toURI()))); byteProvider.skipBytes(length + 1); } }
4,978
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/utils/ResourceByteRangeProviderTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary.utils; import org.testng.annotations.Test; public class ResourceByteRangeProviderTest { @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "rangeStart = .*") public void negativeRangeStartTest() { ResourceByteRangeProvider.Utilities.validateRangeRequest(1L, -1L, 1L); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "rangeStart = .*") public void rangeStartGreaterThanRangeEndTest() { ResourceByteRangeProvider.Utilities.validateRangeRequest(1L, 2L, 1L); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "rangeEnd = .*") public void invalidRangeEndTest() { ResourceByteRangeProvider.Utilities.validateRangeRequest(1L, 1L, 2L); } }
4,979
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/exceptions/IMFExceptionTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary.exceptions; import testUtils.ExceptionTester; import org.testng.annotations.Test; @Test(groups = "unit") public class IMFExceptionTest { @Test public void test() { new ExceptionTester<>(IMFException.class); } }
4,980
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/exceptions/TestException.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary.exceptions; public class TestException extends RuntimeException { public TestException() { super(); } public TestException(Throwable cause, String format, Object ... args) { super(args.length == 0? format : String.format(format, args), cause); } public TestException(String format, Object ... args) { super(args.length == 0? format : String.format(format, args)); } public TestException(Throwable cause) { super(cause); } }
4,981
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/exceptions/MXFExceptionTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary.exceptions; import testUtils.ExceptionTester; import org.testng.annotations.Test; @Test(groups = "unit") public class MXFExceptionTest { @Test public void test() { new ExceptionTester<>(MXFException.class); } }
4,982
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/st0377/IndexTableSegmentTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary.st0377; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.utils.ByteArrayDataProvider; import com.netflix.imflibrary.utils.ByteProvider; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class IndexTableSegmentTest { @Test public void indexTableSegmentTest() throws IOException { File inputFile = TestHelper.findResourceByPath("Netflix_Ident_23976_3840x2160_177AR.mxf.idx"); byte[] bytes = Files.readAllBytes(Paths.get(inputFile.toURI())); ByteProvider byteProvider = new ByteArrayDataProvider(bytes); KLVPacket.Header header = new KLVPacket.Header(byteProvider, 0L); IndexTableSegment indexTableSegment = new IndexTableSegment(byteProvider, header); Assert.assertTrue(indexTableSegment.toString().length() > 0); Assert.assertEquals(indexTableSegment.getIndexEntries().size(), 96); Assert.assertEquals(indexTableSegment.getIndexEntries().get(1).getStreamOffset(), 28127L); } }
4,983
0
Create_ds/photon/src/test/java/com/netflix/imflibrary
Create_ds/photon/src/test/java/com/netflix/imflibrary/st0377/HeaderPartitionTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.imflibrary.st0377; import com.netflix.imflibrary.Colorimetry; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.RESTfulInterfaces.IMPValidator; import com.netflix.imflibrary.RESTfulInterfaces.PayloadRecord; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.st0377.header.AudioChannelLabelSubDescriptor; import com.netflix.imflibrary.st0377.header.ContentStorage; import com.netflix.imflibrary.st0377.header.EssenceContainerData; import com.netflix.imflibrary.st0377.header.GenericTrack; import com.netflix.imflibrary.st0377.header.InterchangeObject; import com.netflix.imflibrary.st0377.header.MaterialPackage; import com.netflix.imflibrary.st0377.header.Preface; import com.netflix.imflibrary.st0377.header.Sequence; import com.netflix.imflibrary.st0377.header.SoundFieldGroupLabelSubDescriptor; import com.netflix.imflibrary.st0377.header.SourceClip; import com.netflix.imflibrary.st0377.header.SourcePackage; import com.netflix.imflibrary.st0377.header.TimelineTrack; import com.netflix.imflibrary.st0377.header.WaveAudioEssenceDescriptor; import com.netflix.imflibrary.st2067_2.AudioContentKind; import com.netflix.imflibrary.utils.ByteArrayDataProvider; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.utils.FileByteRangeProvider; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import org.testng.Assert; import org.testng.annotations.Test; import testUtils.TestHelper; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class HeaderPartitionTest { @Test public void audioHeaderPartitionTest() throws IOException { File inputFile = TestHelper.findResourceByPath("TearsOfSteel_4k_Test_Master_Audio_002.mxf.hdr"); byte[] bytes = Files.readAllBytes(Paths.get(inputFile.toURI())); ByteProvider byteProvider = new ByteArrayDataProvider(bytes); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); HeaderPartition headerPartition = new HeaderPartition(byteProvider, 0L, inputFile.length(), imfErrorLogger); Assert.assertTrue(headerPartition.toString().length() > 0); Preface preface = headerPartition.getPreface(); Assert.assertTrue(preface.toString().length() > 0); ContentStorage contentStorage = preface.getContentStorage(); Assert.assertEquals(contentStorage.getGenericPackageList().size(), 2); Assert.assertEquals(contentStorage.getPackageInstanceUIDs().size(), 2); List<InterchangeObject> materialPackages = headerPartition.getMaterialPackages(); Assert.assertEquals(materialPackages.size(), 1); MaterialPackage materialPackage = (MaterialPackage)materialPackages.get(0); Assert.assertTrue(materialPackage.toString().length() > 0); MXFUID materialPackageInstanceUID = new MXFUID(new byte[]{ 0x6a, (byte)0x92, (byte)0xc9, 0x01, 0x13, 0x59, 0x48, 0x42, (byte)0x86, 0x38, (byte)0xdf, (byte)0xa9, 0x3a, 0x08, (byte)0x80, 0x20}); Assert.assertEquals(materialPackage.getInstanceUID(), materialPackageInstanceUID); Assert.assertSame(materialPackage, headerPartition.getMaterialPackage(materialPackageInstanceUID)); List<GenericTrack> genericTracks = materialPackage.getGenericTracks(); Assert.assertEquals(genericTracks.size(), 2); List<MXFUID> trackInstanceUIDs = materialPackage.getTrackInstanceUIDs(); Assert.assertEquals(trackInstanceUIDs.size(), 2); MXFUID timeCodeTrackInstanceUID = new MXFUID(new byte[]{ 0x33, (byte)0xb6, (byte)0xc7, 0x6c, 0x1f, 0x7a, 0x45, (byte)0xf0, (byte)0x88, 0x46, 0x65, 0x7d, (byte)0xd4, (byte)0x96, 0x08, 0x01}); Assert.assertEquals(trackInstanceUIDs.get(0), timeCodeTrackInstanceUID); MXFUID soundTrackInstanceUID = new MXFUID(new byte[]{ 0x5c, (byte)0xab, 0x51, (byte)0x93, (byte)0x96, (byte)0x8b, 0x4e, 0x13, (byte)0x8f, (byte)0xdb, 0x0b, (byte)0x83, (byte)0x81, 0x0a, (byte)0xc7, (byte)0x97}); Assert.assertEquals(trackInstanceUIDs.get(1), soundTrackInstanceUID); List<TimelineTrack> timelineTracks = materialPackage.getTimelineTracks(); Assert.assertEquals(timelineTracks.size(), 2); TimelineTrack timeCodeTrack = timelineTracks.get(0); Assert.assertEquals(timeCodeTrack.getInstanceUID(), timeCodeTrackInstanceUID); Assert.assertEquals(timeCodeTrack.getEditRateNumerator(), 24000L); Assert.assertEquals(timeCodeTrack.getEditRateDenominator(), 1001L); Sequence sequence = timelineTracks.get(1).getSequence(); Assert.assertEquals(sequence.getInstanceUID(), timelineTracks.get(1).getSequenceUID()); Assert.assertEquals(sequence.getNumberOfStructuralComponents(), 1); Assert.assertEquals(sequence.getSourceClips().size(), 1); SourceClip sourceClip = sequence.getSourceClips().get(0); Assert.assertEquals(sourceClip.getInstanceUID(), sequence.getSourceClipUID(0)); Assert.assertEquals((long)sourceClip.getDuration(), 35232L); List<InterchangeObject> sourcePackages = headerPartition.getSourcePackages(); Assert.assertEquals(sourcePackages.size(), 1); SourcePackage sourcePackage = (SourcePackage)sourcePackages.get(0); Assert.assertTrue(sourcePackage.toString().length() > 0); MXFUID sourcePackageInstanceUid = new MXFUID(new byte[]{ 0x54, 0x0b, 0x00, (byte)0xf2, (byte)0xb9, (byte)0x8e, 0x43, 0x7a, (byte)0x8f, (byte)0xa0, 0x3c, (byte)0xe1, (byte)0xa6, 0x1f, 0x25, (byte)0xf9 }); Assert.assertEquals(sourcePackage.getInstanceUID(), sourcePackageInstanceUid); Assert.assertSame(sourcePackage, headerPartition.getSourcePackage(sourcePackageInstanceUid)); Assert.assertEquals(sourcePackage.getPackageUID(), new MXFUID(new byte[]{ 0x06, 0x0a, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x01, 0x01, 0x0f, 0x20, 0x13, 0x00, 0x00, 0x00, (byte)0xcf, (byte)0xbc, (byte)0xf3, (byte)0xb9, 0x62, 0x50, 0x46, 0x7c, (byte)0xbd, 0x18, (byte)0x9f, 0x5d, (byte)0xe0, (byte)0xdf, (byte)0x9f, (byte)0xfb })); trackInstanceUIDs = sourcePackage.getTrackInstanceUIDs(); Assert.assertEquals(trackInstanceUIDs.size(), 2); Assert.assertEquals(trackInstanceUIDs.get(0), new MXFUID(new byte[]{ 0x51, 0x0f, (byte)0x96, (byte)0xd1, (byte)0xa4, (byte)0xa4, 0x4a, (byte)0xd9, (byte)0xa9, 0x36, (byte)0xdd, 0x60, (byte)0xd3, 0x1a, (byte)0xc9, 0x2f })); Assert.assertEquals(trackInstanceUIDs.get(1), new MXFUID(new byte[]{ 0x2b, 0x71, 0x39, (byte)0xcc, 0x16, 0x3c, 0x43, (byte)0xa5, (byte)0x9d, (byte)0xc4, (byte)0xb3, 0x64, (byte)0xb6, (byte)0xa1, (byte)0xeb, (byte)0x93 })); Assert.assertTrue(headerPartition.hasWaveAudioEssenceDescriptor()); Assert.assertEquals(headerPartition.getWaveAudioEssenceDescriptors().size(), 1); Assert.assertTrue(headerPartition.getEssenceTypes().size() == 1); Assert.assertTrue(headerPartition.getEssenceTypes().get(0) == HeaderPartition.EssenceTypeEnum.MainAudioEssence); WaveAudioEssenceDescriptor waveAudioEssenceDescriptor = (WaveAudioEssenceDescriptor)headerPartition.getWaveAudioEssenceDescriptors().get(0); Assert.assertTrue(waveAudioEssenceDescriptor.toString().length() > 0); Assert.assertTrue(waveAudioEssenceDescriptor.equals(waveAudioEssenceDescriptor)); Assert.assertEquals(waveAudioEssenceDescriptor.getAudioSamplingRateNumerator(), 48000); Assert.assertEquals(waveAudioEssenceDescriptor.getAudioSamplingRateDenominator(), 1); Assert.assertEquals(waveAudioEssenceDescriptor.getChannelCount(), 2); Assert.assertEquals(waveAudioEssenceDescriptor.getQuantizationBits(), 24); Assert.assertEquals(waveAudioEssenceDescriptor.getBlockAlign(), 6); Assert.assertFalse(headerPartition.hasAudioChannelLabelSubDescriptors()); Assert.assertFalse(headerPartition.hasSoundFieldGroupLabelSubDescriptor()); Assert.assertFalse(headerPartition.hasCDCIPictureEssenceDescriptor()); Assert.assertFalse(headerPartition.hasRGBAPictureEssenceDescriptor()); Assert.assertEquals(headerPartition.getAudioContentKind(), AudioContentKind.Unknown); MXFUID essenceContainerDataInstanceUID = new MXFUID(new byte[]{ 0x46, 0x31, (byte)0x9f, 0x11, (byte)0xc9, (byte)0xb1, 0x40, (byte)0xa5, (byte)0xb9, (byte)0xb1, (byte)0x9e, 0x69, (byte)0xda, (byte)0x89, (byte)0xbe, 0x52 }); Assert.assertEquals(headerPartition.getPreface().getContentStorage().getEssenceContainerDataList().size(), 1); EssenceContainerData essenceContainerData = headerPartition.getPreface().getContentStorage().getEssenceContainerDataList().get(0); Assert.assertSame(essenceContainerData, headerPartition.getEssenceContainerData(essenceContainerDataInstanceUID)); PartitionPack partitionPack = headerPartition.getPartitionPack(); Assert.assertFalse(partitionPack.isBodyPartition()); Assert.assertFalse(partitionPack.isFooterPartition()); Assert.assertFalse(partitionPack.isValidFooterPartition()); Assert.assertEquals(partitionPack.getHeaderByteCount(), 11744L); Assert.assertEquals(partitionPack.getIndexByteCount(), 0L); Assert.assertEquals(partitionPack.getPartitionDataByteOffset(), 124L); } @Test(expectedExceptions = MXFException.class, expectedExceptionsMessageRegExp = "This partition does not contain essence data") public void partitionPackWithNoEssenceDataTest() throws IOException { File inputFile = TestHelper.findResourceByPath("TearsOfSteel_4k_Test_Master_Audio_002.mxf.hdr"); byte[] bytes = Files.readAllBytes(Paths.get(inputFile.toURI())); ByteProvider byteProvider = new ByteArrayDataProvider(bytes); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); HeaderPartition headerPartition = new HeaderPartition(byteProvider, 0L, inputFile.length(), imfErrorLogger); PartitionPack partitionPack = headerPartition.getPartitionPack(); partitionPack.getEssenceStreamSegmentStartStreamPosition(); } @Test public void videoHeaderPartitionTest() throws IOException { File inputFile = TestHelper.findResourceByPath("CHIMERA_NETFLIX_2398.mxf.hdr"); byte[] bytes = Files.readAllBytes(Paths.get(inputFile.toURI())); ByteProvider byteProvider = new ByteArrayDataProvider(bytes); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); HeaderPartition headerPartition = new HeaderPartition(byteProvider, 0L, inputFile.length(), imfErrorLogger); Assert.assertTrue(headerPartition.toString().length() > 0); Assert.assertFalse(headerPartition.hasRGBAPictureEssenceDescriptor()); Assert.assertTrue(headerPartition.hasCDCIPictureEssenceDescriptor()); Assert.assertEquals(headerPartition.getImageColorModel(), Colorimetry.ColorModel.YUV); Assert.assertEquals(headerPartition.getImageCodingEquation(), Colorimetry.CodingEquation.ITU709); Assert.assertEquals(headerPartition.getImageColorPrimaries(), Colorimetry.ColorPrimaries.Unknown); Assert.assertEquals(headerPartition.getImageTransferCharacteristic(), Colorimetry.TransferCharacteristic.ITU709); Assert.assertEquals(headerPartition.getImageQuantization(), Colorimetry.Quantization.QE2); Assert.assertEquals(headerPartition.getImageSampling(), Colorimetry.Sampling.Sampling422); Assert.assertEquals(headerPartition.getImagePixelBitDepth().intValue(), 10); Assert.assertTrue(headerPartition.getEssenceTypes().size() == 1); Assert.assertTrue(headerPartition.getEssenceTypes().get(0) == HeaderPartition.EssenceTypeEnum.MainImageEssence); } @Test public void videoHeaderPartitionTest2() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/MERIDIAN_Netflix_Photon_161006/MERIDIAN_Netflix_Photon_161006_00.mxf"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); HeaderPartition headerPartition = HeaderPartition.fromFile(inputFile, imfErrorLogger); Assert.assertTrue(headerPartition.toString().length() > 0); Assert.assertTrue(headerPartition.hasRGBAPictureEssenceDescriptor()); Assert.assertFalse(headerPartition.hasCDCIPictureEssenceDescriptor()); Assert.assertEquals(headerPartition.getImageColorModel(), Colorimetry.ColorModel.RGB); Assert.assertEquals(headerPartition.getImageCodingEquation(), Colorimetry.CodingEquation.Unknown); Assert.assertEquals(headerPartition.getImageColorPrimaries(), Colorimetry.ColorPrimaries.ITU2020); Assert.assertEquals(headerPartition.getImageTransferCharacteristic(), Colorimetry.TransferCharacteristic.SMPTEST2084); Assert.assertEquals(headerPartition.getImageQuantization(), Colorimetry.Quantization.QE2); Assert.assertEquals(headerPartition.getImageSampling(), Colorimetry.Sampling.Sampling444); Assert.assertEquals(headerPartition.getImagePixelBitDepth().intValue(), 12); Assert.assertTrue(headerPartition.getEssenceTypes().size() == 1); Assert.assertTrue(headerPartition.getEssenceTypes().get(0) == HeaderPartition.EssenceTypeEnum.MainImageEssence); } @Test public void audioHeaderPartitionTest2() throws IOException { File inputFile = TestHelper.findResourceByPath("NMPC_6000ms_6Ch_ch_id.mxf.hdr"); byte[] bytes = Files.readAllBytes(Paths.get(inputFile.toURI())); ByteProvider byteProvider = new ByteArrayDataProvider(bytes); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); HeaderPartition headerPartition = new HeaderPartition(byteProvider, 0L, inputFile.length(), imfErrorLogger); Assert.assertTrue(headerPartition.toString().length() > 0); Assert.assertTrue(headerPartition.hasSoundFieldGroupLabelSubDescriptor()); Assert.assertEquals(headerPartition.getSoundFieldGroupLabelSubDescriptors().size(), 1); SoundFieldGroupLabelSubDescriptor soundFieldGroupLabelSubDescriptor = (SoundFieldGroupLabelSubDescriptor)headerPartition.getSoundFieldGroupLabelSubDescriptors().get(0); Assert.assertEquals(soundFieldGroupLabelSubDescriptor.getMCALabelDictionaryId(), new MXFUID(new byte[]{ 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x0d, 0x03, 0x02, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00 })); MXFUID soundFieldGroupMCALinkId = new MXFUID(new byte[]{ (byte)0xe5, (byte)0x84, 0x07, 0x22, 0x47, (byte)0xb8, 0x45, 0x13, (byte)0xa0, (byte)0xb0, 0x2e, (byte)0xee, (byte)0xde, 0x20, (byte)0x92, (byte)0xfe }); Assert.assertEquals(soundFieldGroupLabelSubDescriptor.getMCALinkId(), soundFieldGroupMCALinkId); Assert.assertTrue(headerPartition.hasAudioChannelLabelSubDescriptors()); Assert.assertEquals(headerPartition.getAudioChannelLabelSubDescriptors().size(), 6); if(headerPartition.getAudioChannelLabelSubDescriptors().size() == 0){ throw new MXFException(String.format("Asset seems to be invalid since it does not contain any AudioChannelLabelSubDescriptors")); } Assert.assertEquals(headerPartition.getAudioContentKind(), AudioContentKind.Unknown); AudioChannelLabelSubDescriptor audioChannelLabelSubDescriptor = (AudioChannelLabelSubDescriptor)headerPartition.getAudioChannelLabelSubDescriptors().get(0); Assert.assertEquals(audioChannelLabelSubDescriptor.getSoundfieldGroupLinkId(), soundFieldGroupMCALinkId); Assert.assertEquals(audioChannelLabelSubDescriptor.getMCALabelDictionaryId(), new MXFUID(new byte[]{ 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x0d, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 })); Assert.assertEquals(audioChannelLabelSubDescriptor.getMCALinkId(), new MXFUID(new byte[]{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 })); } @Test public void descriptiveMetadataHeaderPartitionTest() throws IOException { File inputFile = TestHelper.findResourceByPath("TestIMP/IAB/MXF/meridian_2398_IAB_5f.mxf"); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); HeaderPartition headerPartition = HeaderPartition.fromFile(inputFile, imfErrorLogger); Assert.assertEquals(headerPartition.getGenericStreamIdFromGenericStreamTextBaseSetDescription("http://www.dolby.com/schemas/2018/DbmdWrapper"), 3); } }
4,984
0
Create_ds/photon/src/test/java
Create_ds/photon/src/test/java/testUtils/TestHelper.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package testUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import static org.testng.Assert.assertNotNull; public final class TestHelper { private static final int DEFAULT_BUFFER_SIZE = 1024; private static final int EOF = -1; private TestHelper() { //to prevent instantiation } public static File findResourceByPath(String resourcePath) { URL resource = TestHelper.class.getClassLoader().getResource(resourcePath); if (resource == null) { resource = Thread.currentThread().getContextClassLoader().getResource(resourcePath); } assertNotNull(resource, String.format("Resource %s does not exist", resourcePath)); return new File(resource.getPath()); } public static byte[] toByteArray(InputStream inputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int numBytesRead = 0; while((numBytesRead = inputStream.read(buffer)) != EOF) { baos.write(buffer, 0, numBytesRead); } return baos.toByteArray(); } }
4,985
0
Create_ds/photon/src/test/java
Create_ds/photon/src/test/java/testUtils/ExceptionTester.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package testUtils; import com.netflix.imflibrary.exceptions.TestException; import java.lang.reflect.Constructor; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertSame; import static org.testng.Assert.fail; public class ExceptionTester<T extends Throwable> { public ExceptionTester(Class<T> clazz) { assertNotNull(clazz, "Class must not be null"); assertTrue(Throwable.class.isAssignableFrom(clazz)); TestException nestedException = new TestException("nested"); String message = new String("ExceptionTester"); try { Constructor<T> ctor = clazz.getConstructor(); try { T ex = ctor.newInstance(); assertNull(ex.getMessage()); assertNull(ex.getCause()); } catch (Exception e) { fail("We expect this operation to succeed, but it threw an exception - signature: no parameters", e); } } catch (NoSuchMethodException e) { // NOPMD // We don't have one of these constructors, that's ok } try { Constructor<T> ctor = clazz.getConstructor(Throwable.class); try { T ex = ctor.newInstance(nestedException); assertSame(ex.getCause(), nestedException); assertEquals(ex.getMessage(), nestedException.toString()); } catch (Exception e) { fail("We expect this operation to succeed, but it threw an exception - signature(nested_exception)", e); } } catch (NoSuchMethodException e) { // NOPMD // We don't have one of these constructors, that's ok } try { Constructor<T> ctor = clazz.getConstructor(String.class); try { T ex = ctor.newInstance(message); assertEquals(ex.getMessage(), message); assertNull(ex.getCause()); } catch (Exception e) { fail("We expect this operation to succeed, but it threw an exception - signature(message)", e); } } catch (NoSuchMethodException e) { // NOPMD // We don't have one of these constructors, that's ok } try { Constructor<T> ctor = clazz.getConstructor(String.class, Throwable.class); try { T ex = ctor.newInstance(message, nestedException); assertEquals(ex.getMessage(), message); assertSame(ex.getCause(), nestedException); } catch (Exception e) { fail("We expect this operation to succeed, but it threw an exception - signature(nested_exception, message", e); } } catch (NoSuchMethodException e) { // NOPMD // We don't have one of these constructors, that's ok } } }
4,986
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/MXFOperationalPattern1A.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.PartitionPack; import com.netflix.imflibrary.st0377.header.ContentStorage; import com.netflix.imflibrary.st0377.header.GenericPackage; import com.netflix.imflibrary.st0377.header.MaterialPackage; import com.netflix.imflibrary.st0377.header.Preface; import com.netflix.imflibrary.st0377.header.Sequence; import com.netflix.imflibrary.st0377.header.SourcePackage; import com.netflix.imflibrary.st0377.header.TimelineTrack; import javax.annotation.Nonnull; import java.util.List; import java.util.UUID; /** * This class consists exclusively of static methods that help verify the compliance of an * MXF header partition as well as MXF partition packs (see st377-1:2011) with st378:2004 */ public final class MXFOperationalPattern1A { private static final byte[] OPERATIONAL_PATTERN1A_KEY = {0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00}; private static final byte[] OPERATIONAL_PATTERN1A_KEY_MASK = { 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1}; private static final double EPSILON = 0.000001; private static final double TOLERANCE = 1.0; private static final String OP1A_EXCEPTION_PREFIX = "MXF Operational Pattern 1A check: "; //to prevent instantiation private MXFOperationalPattern1A() { } /** * Checks the compliance of an MXF header partition with st378:2004. A runtime * exception is thrown in case of non-compliance * * @param headerPartition the MXF header partition * @param imfErrorLogger - an object for logging errors * @return the same header partition wrapped in a HeaderPartitionOP1A object */ @SuppressWarnings({"PMD.NcssMethodCount","PMD.CollapsibleIfStatements"}) public static HeaderPartitionOP1A checkOperationalPattern1ACompliance(@Nonnull HeaderPartition headerPartition, @Nonnull IMFErrorLogger imfErrorLogger) { int previousNumberOfErrors = imfErrorLogger.getErrors().size(); Preface preface = headerPartition.getPreface(); String trackFileID_Prefix = ""; if(preface != null) { GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage; filePackage = (SourcePackage) genericPackage; UUID packageID = filePackage.getPackageMaterialNumberasUUID(); trackFileID_Prefix = String.format("TrackFile ID : %s - ", packageID.toString()); } //Section 9.5.1 st377-1:2011 if(preface == null){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("Preface does not exist in the header partition, which is invalid.")); } //Preface else { //check 'Operational Pattern' field in Preface byte[] bytes = preface.getOperationalPattern().getULAsBytes(); for (int i=0; i< bytes.length; i++) { //An IMF track file shall conform to the OP1A requirements as mandated by Section 5.1.1 #10 st2067-5:2013 if( (MXFOperationalPattern1A.OPERATIONAL_PATTERN1A_KEY_MASK[i] != 0) && (MXFOperationalPattern1A.OPERATIONAL_PATTERN1A_KEY[i] != bytes[i]) ) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("Operational Pattern field in preface = 0x%x at position (zero-indexed) = %d, is different from expected value = 0x%x", bytes[i], i, MXFOperationalPattern1A.OPERATIONAL_PATTERN1A_KEY[i])); } } //check number of essence containers ULs Section 9.4.3 st377-1:2011 if (preface.getNumberOfEssenceContainerULs() < 1) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("Number of EssenceContainer ULs in preface = %d, at least 1 is expected", preface.getNumberOfEssenceContainerULs())); } } //Content Storage { //check number of Content Storage sets Section 9.5.2 st377-1:2011 if (headerPartition.getContentStorageList().size() != 1) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("Number of Content Storage sets in header partition = %d, is different from 1", headerPartition.getContentStorageList().size())); } if(preface != null) { ContentStorage contentStorage = preface.getContentStorage(); //Section 9.5.2 st377-1:2011 if (contentStorage == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("No Content Storage set was found in header partition")); } //check number of Essence Container Data sets referred by Content Storage Section 9.4.3 st377-1:2011 else if (contentStorage.getNumberOfEssenceContainerDataSets() != 1) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("Number of EssenceContainerData sets referred by Content Storage = %d, is different from 1", contentStorage.getNumberOfEssenceContainerDataSets())); } } } //check number of Essence Container Data sets { //Section 9.4.3 st377-1:2011 if (headerPartition.getEssenceContainerDataList().size() != 1) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("Number of EssenceContainerData sets = %d, is different from 1", headerPartition.getEssenceContainerDataList().size())); } } //check number of Material Packages Section 5.1, Table-1 st378:2004 if (headerPartition.getMaterialPackages().size() != 1) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("Number of Material Packages in header partition = %d, is different from 1", headerPartition.getMaterialPackages().size())); } //Material Package { MaterialPackage materialPackage = (MaterialPackage)headerPartition.getMaterialPackages().get(0); //check number of source clips per track of Material Package Section 5.1, Table-1 st378:2004 for (TimelineTrack timelineTrack : materialPackage.getTimelineTracks()) { Sequence sequence = timelineTrack.getSequence(); //Section 9.5.3 st377-1:2011 if (sequence == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("TimelineTrack with instanceUID = %s has no sequence", timelineTrack.getInstanceUID())); } else if (!sequence.getMxfDataDefinition().equals(MXFDataDefinition.OTHER)) { //Section 5.1, Table-1 st378:2004 if (sequence.getSourceClips().size() != 1) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("Material Package Sequence with UID = %s has %d source clips, exactly one is allowed", sequence.getInstanceUID(), sequence.getSourceClips().size())); } } } //check if Material Package accesses a single source package Section 5.1, Table-1 st378:2004 MXFUID referencedSourcePackageUMID = null; for (TimelineTrack timelineTrack : materialPackage.getTimelineTracks()) { Sequence sequence = timelineTrack.getSequence(); if (sequence != null && !sequence.getMxfDataDefinition().equals(MXFDataDefinition.OTHER)) { MXFUID thisSourcePackageUMID = sequence.getSourceClips().get(0).getSourcePackageID(); if (referencedSourcePackageUMID == null) { referencedSourcePackageUMID = thisSourcePackageUMID; } else if (!referencedSourcePackageUMID.equals(thisSourcePackageUMID)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("SourceClipUID = %s refers to source package UID = %s different from other source clips that refer to source package UID = %s", sequence.getInstanceUID(), thisSourcePackageUMID, referencedSourcePackageUMID)); } } } if(referencedSourcePackageUMID == null){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("Invalid source package UID, perhaps because one or more timelineTrack has no sequence")); } if(preface != null) { //check if SourcePackageID referenced from Material Package is present in ContentStorage ContentStorage contentStorage = preface.getContentStorage(); if (contentStorage == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("No Content Storage set was found in header partition")); } else { boolean foundReferenceForReferencedSourcePackageUMIDInContentStorage = false; for (SourcePackage sourcePackage : contentStorage.getSourcePackageList()) { if (sourcePackage.getPackageUID().equals(referencedSourcePackageUMID)) { foundReferenceForReferencedSourcePackageUMIDInContentStorage = true; break; } } if (!foundReferenceForReferencedSourcePackageUMIDInContentStorage) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("Content Storage does not refer to Source Package with packageUID = %s", referencedSourcePackageUMID)); } //check if SourcePackageID referenced from Material Package is the same as that referred by EssenceContainer Data set MXFUID linkedPackageUID = contentStorage.getEssenceContainerDataList().get(0).getLinkedPackageUID(); if (referencedSourcePackageUMID != null && !linkedPackageUID.equals(referencedSourcePackageUMID)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("Package UID = %s referred by EssenceContainerData set is different from %s which is referred by Material Package", linkedPackageUID, referencedSourcePackageUMID)); } } } } //check if all tracks across the Material Package and the top-level File Package have the same duration st377-1:2011 double sequenceDuration = 0.0; { MaterialPackage materialPackage = (MaterialPackage)headerPartition.getMaterialPackages().get(0); for (TimelineTrack timelineTrack : materialPackage.getTimelineTracks()) { long thisEditRateNumerator = timelineTrack.getEditRateNumerator(); long thisEditRateDenominator = timelineTrack.getEditRateDenominator(); if (thisEditRateNumerator == 0) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("Timeline Track %s has invalid edit rate : numerator = %d, denominator = %d", timelineTrack.getInstanceUID(), thisEditRateNumerator, thisEditRateDenominator)); } Sequence sequence = timelineTrack.getSequence(); if (sequence != null && !sequence.getMxfDataDefinition().equals(MXFDataDefinition.OTHER)) { double thisSequenceDuration = ((double)sequence.getDuration()*(double)thisEditRateDenominator)/(double)thisEditRateNumerator; if (Math.abs(sequenceDuration) < MXFOperationalPattern1A.EPSILON) { sequenceDuration = thisSequenceDuration; } else if (Math.abs(sequenceDuration - thisSequenceDuration) > MXFOperationalPattern1A.TOLERANCE) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("Material Package SequenceUID = %s is associated with duration = %f, which is different from expected value %f", sequence.getInstanceUID(), thisSequenceDuration, sequenceDuration)); } } } if(preface != null && preface.getContentStorage() != null) { SourcePackage filePackage = (SourcePackage) preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); for (TimelineTrack timelineTrack : filePackage.getTimelineTracks()) { long thisEditRateNumerator = timelineTrack.getEditRateNumerator(); long thisEditRateDenominator = timelineTrack.getEditRateDenominator(); if (thisEditRateNumerator == 0) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("Timeline Track %s has invalid edit rate : numerator = %d, denominator = %d", timelineTrack.getInstanceUID(), thisEditRateNumerator, thisEditRateDenominator)); } Sequence sequence = timelineTrack.getSequence(); if (sequence != null && !sequence.getMxfDataDefinition().equals(MXFDataDefinition.OTHER)) { double thisSequenceDuration = ((double) sequence.getDuration() * (double) thisEditRateDenominator) / (double) thisEditRateNumerator; if (Math.abs(sequenceDuration) < MXFOperationalPattern1A.EPSILON) { sequenceDuration = thisSequenceDuration; } else if (Math.abs(sequenceDuration - thisSequenceDuration) > MXFOperationalPattern1A.TOLERANCE) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + trackFileID_Prefix + String.format("File Package SequenceUID = %s is associated with duration = %f, which is different from expected value %f", sequence.getInstanceUID(), thisSequenceDuration, sequenceDuration)); } } } } } if(imfErrorLogger.hasFatalErrors(previousNumberOfErrors, imfErrorLogger.getNumberOfErrors())){ throw new MXFException(String.format("Found fatal errors in the IMFTrackFile that violate IMF OP1A compliance"), imfErrorLogger); } return new HeaderPartitionOP1A(headerPartition); } /** * Checks the compliance of partition packs found in an MXF file with st378:2004. A runtime * exception is thrown in case of non-compliance * * @param partitionPacks the list of partition packs for which the compliance check is performed */ public static void checkOperationalPattern1ACompliance(List<PartitionPack> partitionPacks) { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); for(PartitionPack partitionPack : partitionPacks) { //check 'Operational Pattern' field in PartitionPack byte[] bytes = partitionPack.getOperationalPattern(); for (int i=0; i< bytes.length; i++) { if( (MXFOperationalPattern1A.OPERATIONAL_PATTERN1A_KEY_MASK[i] != 0) && (MXFOperationalPattern1A.OPERATIONAL_PATTERN1A_KEY[i] != bytes[i]) ) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + String.format("Operational Pattern field in preface = 0x%x at position (zero-indexed) = %d, is different from expected value = 0x%x", bytes[i], i, MXFOperationalPattern1A.OPERATIONAL_PATTERN1A_KEY[i])); } } //check number of essence containers if (partitionPack.getNumberOfEssenceContainerULs() < 1) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, MXFOperationalPattern1A.OP1A_EXCEPTION_PREFIX + String.format("Number of EssenceContainer ULs in partition pack = %d, at least 1 is expected", partitionPack.getNumberOfEssenceContainerULs())); } } if(imfErrorLogger.hasFatalErrors()){ throw new MXFException(String.format("Found fatal errors in the IMFTrackFile that violate IMF OP1A compliance"), imfErrorLogger); } } /** * This class wraps an MXF header partition object - wrapping can be done * only if the header partition object is compliant with st378:2004 */ public static class HeaderPartitionOP1A { private final HeaderPartition headerPartition; private HeaderPartitionOP1A(HeaderPartition headerPartition) { this.headerPartition = headerPartition; } /** * Gets the wrapped MXF header partition object * @return the wrapped MXF header partition object */ public HeaderPartition getHeaderPartition() { return this.headerPartition; } /** * A method that returns a string representation of a HeaderPartitionOP1A object * * @return string representing the object */ public String toString() { return this.headerPartition.toString(); } } }
4,987
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/KLVPacket.java
/* * * * Copyright 2015 Netflix, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.netflix.imflibrary; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.utils.ByteProvider; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.nio.ByteOrder; import java.util.Arrays; /** * An object model representing a KLV packet defined in st336:2007 and utility methods to check for KLV packet definitions */ public final class KLVPacket { /** * The constant BYTE_ORDER. */ //smpte st 377-1:2011, section 6.4.2 public static final ByteOrder BYTE_ORDER = ByteOrder.BIG_ENDIAN; /** * The constant KEY_FIELD_SIZE. */ //smpte st 377-1:2011, section 6.3.8 public static final int KEY_FIELD_SIZE = 16; /** * The constant LENGTH_FIELD_SUFFIX_MAX_SIZE. */ //we are currently using long for storing value of length, below allows a value of the order of 2^63 (i.e., 8 * 10^18) public static final int LENGTH_FIELD_SUFFIX_MAX_SIZE = 8; private static final byte[] KLV_FILL_ITEM_KEY = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x00, 0x03, 0x01, 0x02, 0x10, 0x01, 0x00, 0x00, 0x00}; private static final byte[] KLV_FILL_ITEM_KEY_MASK = { 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1}; private static final byte[] PHDR_IMAGE_METADATA_ITEM_KEY = {0x06, 0x0E, 0x2B, 0x34, 0x01, 0x02, 0x01, 0x05, 0x0E, 0x09, 0x06, 0x07, 0x01, 0x01, 0x01, 0x03}; //the following mask can be used to ignore byte values in 8th and 16th positions private static final byte[] PHDR_IMAGE_METADATA_ITEM_KEY_MASK = {1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0}; private static final byte[] GENERIC_STREAM_PARTITION_DATA_ELEMENT_KEY = {0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x0C, 0x0D, 0x01, 0x05, 0x09, 0x01, 0x00, 0x00, 0x00}; /** * Checks if the key corresponding to the KLV packet is a KLV fill item key * * @param key the key * @return the boolean */ public static boolean isKLVFillItem(byte[] key) { for (int i=0; i< KLVPacket.KEY_FIELD_SIZE; i++) { if((KLVPacket.KLV_FILL_ITEM_KEY_MASK[i] != 0) && (KLVPacket.KLV_FILL_ITEM_KEY[i] != key[i])) { return false; } } return true; } /** * Checks if the key corresponding to the KLV packet is a PHDR image metadata item key * * @param key the key * @return the boolean */ public static boolean isPHDRImageMetadataItemKey(byte[] key) { for (int i=0; i<KLVPacket.KEY_FIELD_SIZE; i++) { if ((KLVPacket.PHDR_IMAGE_METADATA_ITEM_KEY_MASK[i] != 0) && (key[i] != KLVPacket.PHDR_IMAGE_METADATA_ITEM_KEY[i])) { return false; } } return true; } /** * Checks if the key corresponding to the KLV packet is a Generic Stream Partition Data Element key. * * @param key the key * @return the boolean */ public static boolean isGenericStreamPartitionDataElementKey(byte[] key) { return Arrays.equals(key, KLVPacket.GENERIC_STREAM_PARTITION_DATA_ELEMENT_KEY); } //prevent instantiation private KLVPacket() { } /** * Gets the length field of the KLV packet * * @param byteProvider the mxf byte provider * @return the length * @throws IOException - any I/O related error is exposed through an IOException */ public static LengthField getLength(ByteProvider byteProvider) throws IOException { //read one byte int value = byteProvider.getBytes(1)[0]; if ((value >> 7) == 0) {//MSB equals 0 return new LengthField(value, 1); } else {//MSB equals 1 //smpte st 336:2007, annex K if ((value & 0xFF) == 0xFF) {//forbidden value throw new MXFException("First byte of length field in KLV item equals 0xFF"); } if ((value & 0xFF) == 0x80) {//non-deterministic length throw new MXFException("First byte of length field in KLV item equals 0x80"); } int numBytesToRead = value & 0x7F; if (numBytesToRead > KLVPacket.LENGTH_FIELD_SUFFIX_MAX_SIZE) { throw new MXFException(String.format("Size of length field = %d is greater than max size = %d", numBytesToRead, KLVPacket.LENGTH_FIELD_SUFFIX_MAX_SIZE)); } byte[] byteArray = byteProvider.getBytes(numBytesToRead); long length = 0; for (long b : byteArray) { length <<= 8; length += (b & 0xFF); } if (length < 0) { throw new MXFException(String.format("Size of length field = 0x%x is greater than max supported size = 0x%x", length, Long.MAX_VALUE)); } return new LengthField(length, 1 + numBytesToRead); } } /** * A class that represents the length field of a KLV packet */ public static final class LengthField { /** * The Value. */ public final long value; /** * The Size of length field. */ public final long sizeOfLengthField; /** * Instantiates a new Length field. * * @param value the value * @param sizeOfLengthField the size of length field */ public LengthField(long value, long sizeOfLengthField) { this.value = value; this.sizeOfLengthField = sizeOfLengthField; } } /** * A class that represents a KLV packet header */ @Immutable public static final class Header { private final byte[] key; private final long length; private final long sizeOfLengthField; private final long byteOffset; /** * Instantiates a new Header. * * @param byteProvider the mxf byte provider * @param byteOffset corresponding to the MXF KLV header * @throws IOException - any I/O related error will be exposed through an IOException */ public Header(ByteProvider byteProvider, long byteOffset) throws IOException { this.key = byteProvider.getBytes(KLVPacket.KEY_FIELD_SIZE); LengthField lengthField = KLVPacket.getLength(byteProvider); this.length = lengthField.value; this.sizeOfLengthField = lengthField.sizeOfLengthField; this.byteOffset = byteOffset; } /** * Getter for the key of the KLV packet * * @return a copy of the key array */ public byte[] getKey() { return Arrays.copyOf(this.key, this.key.length); } /** * Getter for the value field of the KLV packet * * @return the size of the value field */ public long getVSize() { return this.length; } /** * Getter for the size of the length field of the KLV packet * * @return the size of the length field */ public long getLSize() { return this.sizeOfLengthField; } /** * Gets the byteOffset in the underlying resource. * * @return the byteOffset */ public long getByteOffset() { return this.byteOffset; } /** * Getter for the size of the Key and Length fields of the KLV packet * * @return the kL size */ public long getKLSize() { return KLVPacket.KEY_FIELD_SIZE + this.sizeOfLengthField; } /** * Checks if the category designator in the key of this KLV packet is set to the value corresponding to * dictionaries as defined in st336:2007 * * @return the boolean */ public boolean categoryDesignatorIsDictionaries() { return (this.key[4] == 0x01); } /** * Checks if the category designator in the key of this KLV packet is set to the value corresponding to * groups as defined in st336:2007 * * @return the boolean */ public boolean categoryDesignatorIsGroups() { return (this.key[4] == 0x02); } /** * Checks if the category designator in the key of this KLV packet is set to the value corresponding to * wrappers and containers as defined in st336:2007 * * @return the boolean */ public boolean categoryDesignatorIsWrappersAndContainers() { return (this.key[4] == 0x03); } /** * Gets the Set/Pack kind * * @return the pack kind interpreted as an Integer */ public Integer getSetOrPackKindKey(){ Byte setOrPackKind = this.key[13]; return setOrPackKind.intValue(); } /** * Gets the RegistryDesignator value in the key * * @return the pack kind interpreted as an Integer */ public Integer getRegistryDesignator(){ Byte registryDesignator = this.key[5]; //byte-6 of the 16 byte UL identifies the registry designator return registryDesignator.intValue(); } /** * Checks if the category designator in the key corresponds to labels * * @return the boolean */ public boolean categoryDesignatorIsLabels() { return (this.key[4] == 0x04); } /** * A method that returns a string representation of a KLV packet header object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== KLVPacket Header ======================"); sb.append("\n"); sb.append(String.format("key = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.key[0], this.key[1], this.key[2], this.key[3], this.key[4], this.key[5], this.key[6], this.key[7], this.key[8], this.key[9], this.key[10], this.key[11], this.key[12], this.key[13], this.key[14], this.key[15])); sb.append(String.format("length = %d%n", this.length)); return sb.toString(); } } }
4,988
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/MXFPropertyPopulator.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.st0377.CompoundDataTypes; import com.netflix.imflibrary.st0377.header.InterchangeObject; import com.netflix.imflibrary.st0377.header.JPEG2000PictureComponent; import com.netflix.imflibrary.st0377.header.UL; import com.netflix.imflibrary.utils.ByteProvider; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; /** * A utility class that provides methods for populating fields with MXF metadata sets */ public final class MXFPropertyPopulator { //to prevent instantiation private MXFPropertyPopulator() { } /** * An overloaded method that populates fields within a MXF metadata set * * @param byteProvider the mxf byte provider * @param object the object * @param fieldName the field name * @throws IOException the iO exception */ public static void populateField(ByteProvider byteProvider, Object object, String fieldName) throws IOException { int byteArraySize = getFieldSizeInBytes(object, fieldName); doPopulateField(byteArraySize, byteProvider, object, fieldName); } /** * An overloaded method that populates fields within a MXF metadata set * * @param fieldSize the field size * @param byteProvider the mxf byte provider * @param object the object * @param fieldName the field name * @throws IOException the iO exception */ public static void populateField(int fieldSize, ByteProvider byteProvider, Object object, String fieldName) throws IOException { doPopulateField(fieldSize, byteProvider, object, fieldName); } @SuppressWarnings("PMD.NcssMethodCount") private static void doPopulateField(int byteArraySize, ByteProvider byteProvider, Object object, String fieldName) throws IOException { try { Field field = getField(object.getClass(), fieldName); field.setAccessible(true); if (field.getType() == byte[].class) { byte[] byteArray = byteProvider.getBytes(byteArraySize); field.set(object, byteArray); } else if (field.getType() == InterchangeObject.InterchangeObjectBO.StrongRef.class) { byte[] byteArray = byteProvider.getBytes(byteArraySize); field.set(object, new InterchangeObject.InterchangeObjectBO.StrongRef(byteArray)); } else if(field.getType() == UL.class){ byte[] byteArray = byteProvider.getBytes(byteArraySize); field.set(object, new UL(byteArray)); } else if (field.getType() == String.class) { byte[] byteArray = byteProvider.getBytes(byteArraySize); Charset charset = getFieldCharset(object, fieldName); field.set(object, getString(byteArray, charset)); } else if (field.getType() == CompoundDataTypes.Rational.class) { CompoundDataTypes.Rational rational = new CompoundDataTypes.Rational(byteProvider); field.set(object, rational); } else if (field.getType() == CompoundDataTypes.Timestamp.class) { CompoundDataTypes.Timestamp timestamp = new CompoundDataTypes.Timestamp(byteProvider); field.set(object, timestamp); } else if (field.getType() == CompoundDataTypes.MXFCollections.MXFCollection.class) { CompoundDataTypes.MXFCollections.Header cHeader = new CompoundDataTypes.MXFCollections.Header(byteProvider); ParameterizedType parameterizedType = (ParameterizedType)field.getGenericType(); if(parameterizedType.getActualTypeArguments().length > 1) { throw new MXFException(String.format("Found %d type arguments, however only 1 is supported at this time", parameterizedType.getActualTypeArguments().length)); } if ((parameterizedType.getActualTypeArguments()[0] == byte[].class) || (parameterizedType.getActualTypeArguments()[0].toString().equals("byte[]"))) { List<byte[]> cList = new ArrayList<>(); for (long i=0; i<cHeader.getNumberOfElements(); i++) { cList.add(byteProvider.getBytes((int)cHeader.getSizeOfElement())); } field.set(object, new CompoundDataTypes.MXFCollections.MXFCollection<>(cHeader, cList, fieldName)); } else if (parameterizedType.getActualTypeArguments()[0] == Integer.class) { List<Integer> cList = new ArrayList<>(); for (long i=0; i<cHeader.getNumberOfElements(); i++) { cList.add(getInt(byteProvider.getBytes(4), KLVPacket.BYTE_ORDER)); } field.set(object, new CompoundDataTypes.MXFCollections.MXFCollection<>(cHeader, cList, fieldName)); } else if (parameterizedType.getActualTypeArguments()[0] == InterchangeObject.InterchangeObjectBO.StrongRef.class){ List<InterchangeObject.InterchangeObjectBO.StrongRef> cList = new ArrayList<>(); for (long i=0; i<cHeader.getNumberOfElements(); i++) { cList.add(new InterchangeObject.InterchangeObjectBO.StrongRef(byteProvider.getBytes((int)cHeader.getSizeOfElement()))); } field.set(object, new CompoundDataTypes.MXFCollections.MXFCollection<>(cHeader, cList, fieldName)); } else if (parameterizedType.getActualTypeArguments()[0] == UL.class){ List<UL> cList = new ArrayList<>(); for (long i=0; i<cHeader.getNumberOfElements(); i++) { cList.add(new UL(byteProvider.getBytes((int)cHeader.getSizeOfElement()))); } field.set(object, new CompoundDataTypes.MXFCollections.MXFCollection<>(cHeader, cList, fieldName)); } else if (parameterizedType.getActualTypeArguments()[0] == JPEG2000PictureComponent.JPEG2000PictureComponentBO.class){ List<JPEG2000PictureComponent.JPEG2000PictureComponentBO> cList = new ArrayList<>(); for (long i=0; i<cHeader.getNumberOfElements(); i++) { cList.add(new JPEG2000PictureComponent.JPEG2000PictureComponentBO(byteProvider.getBytes((int)cHeader.getSizeOfElement()))); } field.set(object, new CompoundDataTypes.MXFCollections.MXFCollection<>(cHeader, cList, fieldName)); } else { throw new MXFException(String.format("Found unsupported type argument = %s", parameterizedType.getActualTypeArguments()[0].toString())); } } else if (field.getType() == Float.class) { byte[] byteArray = byteProvider.getBytes(byteArraySize); field.set(object, getFloat(byteArray, KLVPacket.BYTE_ORDER)); } else if ((field.getType() == Long.class) && (byteArraySize == 8)) {// long byte[] byteArray = byteProvider.getBytes(byteArraySize); field.set(object, getLong(byteArray, KLVPacket.BYTE_ORDER)); } else if ((field.getType() == Long.class) && (byteArraySize == 4)) {// unsigned int byte[] byteArray = byteProvider.getBytes(byteArraySize); field.set(object, getUnsignedIntAsLong(byteArray, KLVPacket.BYTE_ORDER)); } else if ((field.getType() == Integer.class) && (byteArraySize == 4)) {//signed int byte[] byteArray = byteProvider.getBytes(byteArraySize); field.set(object, getInt(byteArray, KLVPacket.BYTE_ORDER)); } else if ((field.getType() == Integer.class) && (byteArraySize == 2)) {//unsigned short byte[] byteArray = byteProvider.getBytes(byteArraySize); field.set(object, getUnsignedShortAsInt(byteArray, KLVPacket.BYTE_ORDER)); } else if ((field.getType() == Short.class) && (byteArraySize == 2)) {//signed short byte[] byteArray = byteProvider.getBytes(byteArraySize); field.set(object, getShort(byteArray, KLVPacket.BYTE_ORDER)); } else if ((field.getType() == Short.class) && (byteArraySize == 1)) {//unsigned byte byte[] byteArray = byteProvider.getBytes(byteArraySize); field.set(object, getUnsignedByteAsShort(byteArray)); } else if ((field.getType() == Byte.class) && (byteArraySize == 1)) {//signed byte byte[] byteArray = byteProvider.getBytes(byteArraySize); field.set(object, getByte(byteArray)); } else if ((field.getType() == Boolean.class) && (byteArraySize == 1)) {//boolean byte byte[] byteArray = byteProvider.getBytes(byteArraySize); field.set(object, getBooleanFromByte(byteArray)); } else { throw new MXFException(String.format("unknown type = %s, size = %d combination encountered for field %s", field.getType().toString(), byteArraySize, fieldName)); } } catch(NoSuchFieldException e) { throw new MXFException(e); } catch(SecurityException e) { throw new MXFException(e); } catch(IllegalAccessException e) { throw new MXFException(e); } catch(IllegalArgumentException e) { throw new MXFException(e); } } /** * Getter for a string representing the byte[] * * @param byteArray the byte array * @param charset the charset * @return the string */ public static String getString(byte[] byteArray, Charset charset) { return new String(byteArray, charset); } /** * A utility method for converting a byte[] to a float value * * @param byteArray the byte array * @param byteOrder the byte order * @return the float */ public static Float getFloat(byte[] byteArray, ByteOrder byteOrder) { return ByteBuffer.wrap(byteArray).order(byteOrder).getFloat(); } /** * A utility method for converting a byte[] to a long value * * @param byteArray the byte array * @param byteOrder the byte order * @return the long */ public static Long getLong(byte[] byteArray, ByteOrder byteOrder) { return ByteBuffer.wrap(byteArray).order(byteOrder).getLong(); } /** * A utility method to convert an unsigned integer to a long * * @param byteArray the byte array * @param byteOrder the byte order * @return the unsigned int as long */ public static Long getUnsignedIntAsLong(byte[] byteArray, ByteOrder byteOrder) { long value; long firstByte = (0xFFL & ((long)byteArray[0])); long secondByte = (0xFFL & ((long)byteArray[1])); long thirdByte = (0xFFL & ((long)byteArray[2])); long fourthByte = (0xFFL & ((long)byteArray[3])); if (byteOrder == ByteOrder.LITTLE_ENDIAN) { value = ((firstByte) | (secondByte << 8) | (thirdByte << 16) | (fourthByte << 24)) & 0xFFFFFFFFL; } else { value = ((firstByte << 24) | (secondByte << 16) | (thirdByte << 8) | (fourthByte )) & 0xFFFFFFFFL; } return value; } /** * A utility method for converting a byte[] to an integer * * @param byteArray the byte array * @param byteOrder the byte order * @return the int */ public static Integer getInt(byte[] byteArray, ByteOrder byteOrder) { return ByteBuffer.wrap(byteArray).order(byteOrder).getInt(); } /** * A utility method to convert a byte[] to an unsigned short * * @param byteArray the byte array * @param byteOrder the byte order * @return the unsigned short as int */ public static Integer getUnsignedShortAsInt(byte[] byteArray, ByteOrder byteOrder) { int value; int firstByte = (0xFF & ((int)byteArray[0])); int secondByte = (0xFF & ((int)byteArray[1])); if (byteOrder == ByteOrder.LITTLE_ENDIAN) { value = (firstByte | (secondByte << 8)) & 0xFFFF; } else { value = ((firstByte << 8) | secondByte) & 0xFFFF; } return value; } /** * A utility method to convert a byte[] to a short * * @param byteArray the byte array * @param byteOrder the byte order * @return the short */ public static Short getShort(byte[] byteArray, ByteOrder byteOrder) { return ByteBuffer.wrap(byteArray).order(byteOrder).getShort(); } /** * Gets unsigned byte as short * * @param byteArray the byte array * @return the unsigned byte as short */ public static Short getUnsignedByteAsShort(byte[] byteArray) { return (short)(((int)byteArray[0]) & (0xFF)); } /** * Gets a byte from a byte[] * * @param byteArray the byte array * @return the byte */ public static Byte getByte(byte[] byteArray) { return ByteBuffer.wrap(byteArray).get(); } /** * Gets boolean from byte[] * * @param byteArray the byte array * @return the boolean from byte */ public static Boolean getBooleanFromByte(byte[] byteArray) { byte value = ByteBuffer.wrap(byteArray).order(KLVPacket.BYTE_ORDER).get(); return ((value != 0)); } /** * Gets the size of a field in a MXF metadata set in bytes * * @param object the object * @param fieldName the field name * @return the field size in bytes */ public static int getFieldSizeInBytes(Object object, String fieldName) { int fieldSizeInBytes; try { Field field = getField(object.getClass(), fieldName); if (field.isAnnotationPresent(MXFProperty.class)) { fieldSizeInBytes = field.getAnnotation(MXFProperty.class).size(); } else { throw new MXFException(String.format("field %s is not annotated with %s", fieldName, MXFProperty.class.getSimpleName())); } } catch(NoSuchFieldException e) { throw new MXFException(e); } return fieldSizeInBytes; } /** * Gets the charset corresponding to a MXF metadata set field * * @param object the object * @param fieldName the field name * @return the field charset */ public static Charset getFieldCharset(Object object, String fieldName) { Charset fieldCharset; try { Field field = getField(object.getClass(), fieldName); if (field.isAnnotationPresent(MXFProperty.class)) { fieldCharset = Charset.forName(field.getAnnotation(MXFProperty.class).charset()); } else { throw new MXFException(String.format("field %s is not annotated with %s", fieldName, MXFProperty.class.getSimpleName())); } } catch(NoSuchFieldException e) { throw new MXFException(e); } return fieldCharset; } private static Field getField(Class aClass, String fieldName) throws NoSuchFieldException { try { return aClass.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { Class superClass = aClass.getSuperclass(); if (superClass == null) { throw e; } else { return getField(superClass, fieldName); } } } /** * Gets a list of UIDs that the Metadata set depends on * * @param interchangeObjectBO the interchange object bO * @return the dependent uI ds */ public static List<MXFUID> getDependentUIDs(InterchangeObject.InterchangeObjectBO interchangeObjectBO) { List<MXFUID> dependentUIDs = new ArrayList<>(); Class aClass = interchangeObjectBO.getClass(); while (aClass != null) { Field[] fields = aClass.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if (field.isAnnotationPresent(MXFProperty.class)) { boolean depends = field.getAnnotation(MXFProperty.class).depends(); if (depends) { try { Object object = field.get(interchangeObjectBO); if (object != null) { if (object instanceof CompoundDataTypes.MXFCollections.MXFCollection) { CompoundDataTypes.MXFCollections.MXFCollection<Object> collection = (CompoundDataTypes.MXFCollections.MXFCollection<Object>) object; if(collection.getEntries().get(0) instanceof InterchangeObject.InterchangeObjectBO.StrongRef) { CompoundDataTypes.MXFCollections.MXFCollection<InterchangeObject.InterchangeObjectBO.StrongRef> collectionStrongRefs = (CompoundDataTypes.MXFCollections.MXFCollection<InterchangeObject.InterchangeObjectBO.StrongRef>) object; for (InterchangeObject.InterchangeObjectBO.StrongRef entry : collectionStrongRefs.getEntries()) { dependentUIDs.add(entry.getInstanceUID()); } } else if(collection.getEntries().get(0) instanceof UL){ CompoundDataTypes.MXFCollections.MXFCollection<UL> collectionULs = (CompoundDataTypes.MXFCollections.MXFCollection<UL>) object; for (UL entry : collectionULs.getEntries()) { dependentUIDs.add(entry.getULAsMXFUid()); } } } else if(object instanceof InterchangeObject.InterchangeObjectBO.StrongRef){ InterchangeObject.InterchangeObjectBO.StrongRef strongRef = (InterchangeObject.InterchangeObjectBO.StrongRef) object; dependentUIDs.add(strongRef.getInstanceUID()); } else if(object instanceof UL){ UL ul = (UL)object; dependentUIDs.add(ul.getULAsMXFUid()); } else { byte[] bytes = (byte[]) object; dependentUIDs.add(new MXFUID(bytes)); } } } catch(IllegalAccessException e) { throw new MXFException(e); } } } } aClass = aClass.getSuperclass(); } return dependentUIDs; } }
4,989
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/JPEG2000.java
package com.netflix.imflibrary; import com.netflix.imflibrary.st0377.header.UL; public class JPEG2000 { public static final UL BROADCAST_PROFILE_NODE_UL = UL .fromULAsURNStringToUL("urn:smpte:ul:060e2b34.04010107.04010202.03010100"); public static final UL J2K_NODE_UL = UL.fromULAsURNStringToUL("urn:smpte:ul:060e2b34.04010107.04010202.03010000"); public static final UL HTJ2K_UL = UL.fromULAsURNStringToUL("urn:smpte:ul:060e2b34.0401010d.04010202.03010801"); public static boolean isBroadcastProfile(UL pictureEssenceCoding) { if (!pictureEssenceCoding.equalsWithMask(BROADCAST_PROFILE_NODE_UL, 0b1111111011111110)) return false; switch (pictureEssenceCoding.getByte(15)) { case 0x11: /* JPEG2000BroadcastContributionSingleTileProfileLevel1 */ case 0x12: /* JPEG2000BroadcastContributionSingleTileProfileLevel2 */ case 0x13: /* JPEG2000BroadcastContributionSingleTileProfileLevel3 */ case 0x14: /* JPEG2000BroadcastContributionSingleTileProfileLevel4 */ case 0x15: /* JPEG2000BroadcastContributionSingleTileProfileLevel5 */ case 0x16: /* JPEG2000BroadcastContributionMultiTileReversibleProfileLevel6 */ case 0x17: /* JPEG2000BroadcastContributionMultiTileReversibleProfileLevel7 */ return true; } return false; } public static boolean isIMF2KProfile(UL pictureEssenceCoding) { if (!pictureEssenceCoding.equalsWithMask(J2K_NODE_UL, 0b1111111011111100)) return false; if (pictureEssenceCoding.getByte(14) == 0x02) { switch (pictureEssenceCoding.getByte(15)) { case 0x03: /* J2K_2KIMF_SingleTileLossyProfile_M1S1 */ case 0x05: /* J2K_2KIMF_SingleTileLossyProfile_M2S1 */ case 0x07: /* J2K_2KIMF_SingleTileLossyProfile_M3S1 */ case 0x09: /* J2K_2KIMF_SingleTileLossyProfile_M4S1 */ case 0x0a: /* J2K_2KIMF_SingleTileLossyProfile_M4S2 */ case 0x0c: /* J2K_2KIMF_SingleTileLossyProfile_M5S1 */ case 0x0d: /* J2K_2KIMF_SingleTileLossyProfile_M5S2 */ case 0x0e: /* J2K_2KIMF_SingleTileLossyProfile_M5S3 */ case 0x10: /* J2K_2KIMF_SingleTileLossyProfile_M6S1 */ case 0x11: /* J2K_2KIMF_SingleTileLossyProfile_M6S2 */ case 0x12: /* J2K_2KIMF_SingleTileLossyProfile_M6S3 */ case 0x13: /* J2K_2KIMF_SingleTileLossyProfile_M6S4 */ return true; } } if (pictureEssenceCoding.getByte(14) == 0x05) { switch (pictureEssenceCoding.getByte(15)) { case 0x02: /* J2K_2KIMF_SingleMultiTileReversibleProfile_M1S0 */ case 0x04: /* J2K_2KIMF_SingleMultiTileReversibleProfile_M2S0 */ case 0x06: /* J2K_2KIMF_SingleMultiTileReversibleProfile_M3S0 */ case 0x08: /* J2K_2KIMF_SingleMultiTileReversibleProfile_M4S0 */ case 0x0b: /* J2K_2KIMF_SingleMultiTileReversibleProfile_M5S0 */ case 0x0f: /* J2K_2KIMF_SingleMultiTileReversibleProfile_M6S0 */ return true; } } return false; } public static boolean isIMF4KProfile(UL pictureEssenceCoding) { if (!pictureEssenceCoding.equalsWithMask(J2K_NODE_UL, 0b1111111011111100)) return false; if (pictureEssenceCoding.getByte(14) == 0x03) { switch (pictureEssenceCoding.getByte(15)) { case 0x03: /* J2K_4KIMF_SingleTileLossyProfile_M1S1 */ case 0x05: /* J2K_4KIMF_SingleTileLossyProfile_M2S1 */ case 0x07: /* J2K_4KIMF_SingleTileLossyProfile_M3S1 */ case 0x09: /* J2K_4KIMF_SingleTileLossyProfile_M4S1 */ case 0x0a: /* J2K_4KIMF_SingleTileLossyProfile_M4S2 */ case 0x0c: /* J2K_4KIMF_SingleTileLossyProfile_M5S1 */ case 0x0d: /* J2K_4KIMF_SingleTileLossyProfile_M5S2 */ case 0x0e: /* J2K_4KIMF_SingleTileLossyProfile_M5S3 */ case 0x10: /* J2K_4KIMF_SingleTileLossyProfile_M6S1 */ case 0x11: /* J2K_4KIMF_SingleTileLossyProfile_M6S2 */ case 0x12: /* J2K_4KIMF_SingleTileLossyProfile_M6S3 */ case 0x13: /* J2K_4KIMF_SingleTileLossyProfile_M6S4 */ case 0x15: /* J2K_4KIMF_SingleTileLossyProfile_M7S1 */ case 0x16: /* J2K_4KIMF_SingleTileLossyProfile_M7S2 */ case 0x17: /* J2K_4KIMF_SingleTileLossyProfile_M7S3 */ case 0x18: /* J2K_4KIMF_SingleTileLossyProfile_M7S4 */ case 0x19: /* J2K_4KIMF_SingleTileLossyProfile_M7S5 */ case 0x1b: /* J2K_4KIMF_SingleTileLossyProfile_M8S1 */ case 0x1c: /* J2K_4KIMF_SingleTileLossyProfile_M8S2 */ case 0x1d: /* J2K_4KIMF_SingleTileLossyProfile_M8S3 */ case 0x1e: /* J2K_4KIMF_SingleTileLossyProfile_M8S4 */ case 0x1f: /* J2K_4KIMF_SingleTileLossyProfile_M8S5 */ case 0x20: /* J2K_4KIMF_SingleTileLossyProfile_M8S6 */ return true; } } if (pictureEssenceCoding.getByte(14) == 0x06) { switch (pictureEssenceCoding.getByte(15)) { case 0x02: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M1S0 */ case 0x04: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M2S0 */ case 0x06: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M3S0 */ case 0x08: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M4S0 */ case 0x0b: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M5S0 */ case 0x0f: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M6S0 */ case 0x14: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M7S0 */ case 0x1a: /* J2K_4KIMF_SingleMultiTileReversibleProfile_M8S0 */ return true; } } return false; } public static boolean isAPP2HT(UL pictureEssenceCoding) { return pictureEssenceCoding.equalsWithMask(HTJ2K_UL, 0b1111111011111111); } }
4,990
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/IMPDelivery.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary; import com.netflix.imflibrary.st0429_8.PackingList; import com.netflix.imflibrary.st0429_9.AssetMap; import com.netflix.imflibrary.st0429_9.BasicMapProfileV2FileSet; import com.netflix.imflibrary.st0429_9.BasicMapProfileV2MappedFileSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; import javax.annotation.concurrent.Immutable; import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.UUID; /** * This class represents the concept of an IMF delivery as defined in Section 8 of st2067-2:2015. Informally, an IMF delivery * corresponds to a single AssetMap document and one or more Interoperable Master Packages. */ @Immutable public final class IMPDelivery { private static final Logger logger = LoggerFactory.getLogger(IMPDelivery.class); private final AssetMap assetMap; private final List<InteroperableMasterPackage> interoperableMasterPackages = new ArrayList<>(); private final IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); /** * Constructor for an IMPDelivery object for deliveries that are based on Basic Map Profile v2 (Annex A st0429-9:2014) * @param basicMapProfileV2FileSet a single mapped file set that is compliant with Basic Map Profile v2 (Annex A st0429-9:2014) * @throws IOException - forwarded from {@link BasicMapProfileV2FileSet#BasicMapProfileV2FileSet(BasicMapProfileV2MappedFileSet) BasicMapProfilev2FileSet} constructor * @throws SAXException - forwarded from {@link BasicMapProfileV2FileSet#BasicMapProfileV2FileSet(BasicMapProfileV2MappedFileSet) BasicMapProfilev2FileSet} constructor * @throws JAXBException - forwarded from {@link BasicMapProfileV2FileSet#BasicMapProfileV2FileSet(BasicMapProfileV2MappedFileSet) BasicMapProfilev2FileSet} constructor * @throws URISyntaxException - forwarded from {@link BasicMapProfileV2FileSet#BasicMapProfileV2FileSet(BasicMapProfileV2MappedFileSet) BasicMapProfilev2FileSet} constructor */ public IMPDelivery(BasicMapProfileV2FileSet basicMapProfileV2FileSet) throws IOException, SAXException, JAXBException, URISyntaxException { this.assetMap = basicMapProfileV2FileSet.getAssetMap(); List<AssetMap.Asset> packingListAssets = this.assetMap.getPackingListAssets(); for (AssetMap.Asset packingListAsset : packingListAssets) { URI absolutePackingListURI = basicMapProfileV2FileSet.getAbsoluteAssetMapURI().resolve(packingListAsset.getPath()); PackingList packingList = new PackingList(new File(absolutePackingListURI)); List<IMPAsset> referencedAssets = new ArrayList<>(); for (PackingList.Asset referencedAsset : packingList.getAssets()) { UUID referencedAssetUUID = referencedAsset.getUUID(); referencedAssets.add(new IMPAsset(basicMapProfileV2FileSet.getAbsoluteAssetMapURI().resolve(this.assetMap.getPath(referencedAssetUUID)), referencedAsset)); } interoperableMasterPackages.add(new InteroperableMasterPackage(packingList, absolutePackingListURI, referencedAssets)); } } /** * Getter for a list of IMPs contained in this delivery * @return a list of type {@link InteroperableMasterPackage} corresponding to IMPs * contained in this delivery */ public List<InteroperableMasterPackage> getInteroperableMasterPackages() { return Collections.unmodifiableList(this.interoperableMasterPackages); } /** * Checks if the IMF delivery is valid. An IMF delivery is considered valid if all associated IMPs are valid * @return true if this delivery is valid, false otherwise */ public boolean isValid() { for (InteroperableMasterPackage interoperableMasterPackage : this.interoperableMasterPackages) { if (!interoperableMasterPackage.isValid()) { return false; } } return true; } @Override public String toString() { final StringBuilder sb = new StringBuilder("IMPDelivery{"); sb.append("assetMap=").append(assetMap); sb.append(",\ninteroperableMasterPackages=").append(Arrays.toString(interoperableMasterPackages.toArray())); sb.append('}'); return sb.toString(); } public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, URISyntaxException, JAXBException { File rootFile = new File(args[0]); BasicMapProfileV2MappedFileSet basicMapProfileV2MappedFileSet = new BasicMapProfileV2MappedFileSet(rootFile); BasicMapProfileV2FileSet basicMapProfileV2FileSet = new BasicMapProfileV2FileSet(basicMapProfileV2MappedFileSet); IMPDelivery impDelivery = new IMPDelivery(basicMapProfileV2FileSet); logger.warn(impDelivery.toString()); } }
4,991
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/InteroperableMasterPackage.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.st0429_8.PackingList; import javax.annotation.concurrent.Immutable; import java.net.URI; import java.util.Collections; import java.util.List; /** * This class is an immutable implementation of the concept of Interoperable Master Package (IMP) defined in Section 7.2.1 * of st2067-2:2015. Per Section 7.2.1 of st2067-2:2015, an IMP consists of one IMF packing list (see st0429-8:2007) and all * the assets it references */ @Immutable public final class InteroperableMasterPackage { private final PackingList packingList; private final URI packingListURI; private final List<IMPAsset> referencedAssets; /** * Constructor for an InterOperableMasterPackage object from a {@link com.netflix.imflibrary.st0429_8.PackingList} object, * the URI corresponding to the PackingList document, and a list of type {@link IMPAsset} that * corresponds to assets referenced by this InteroperableMasterPackage object * @param packingList the corresponding packingList object * @param packingListURI an absolute URI for the PackingList document corresponding to the supplied PackingList object, construction * fails if the URI is not absolute * @param referencedAssets the list of type {@link IMPAsset} corresponding to assets * referenced by this InteroperableMasterPackage object */ public InteroperableMasterPackage(PackingList packingList, URI packingListURI, List<IMPAsset> referencedAssets) { this.packingList = packingList; if (!packingListURI.isAbsolute()) { throw new IMFException(String.format("PackingList URI = %s is not absolute", packingListURI)); } this.packingListURI = packingListURI; this.referencedAssets = referencedAssets; } /** * Getter for the packing list corresponding to this IMP * @return the {@link com.netflix.imflibrary.st0429_8.PackingList PackingList} object corresponding to this InteroperableMasterPackage object */ public PackingList getPackingList() { return this.packingList; } /** * Getter for the absolute URI of the packing list corresponding to this IMP * @return the absolute URI for the packing list corresponding to this IMP */ public URI getPackingListURI() { return this.packingListURI; } /** * Getter for the list of all assets (other than the packing list) contained by this IMP * @return a list of type {@link com.netflix.imflibrary.st0429_8.PackingList.Asset Asset} corresponding to all the assets * contained by this IMP */ public List<IMPAsset> getReferencedAssets() { return Collections.unmodifiableList(this.referencedAssets); } /** * Checks if this InteroperableMasterPackage object is valid. An InteroperableMasterPackage object is valid if all the * assets referenced by it are valid * @return true if this InteroperableMasterPackage object is valid, false otherwise */ public boolean isValid() { for (IMPAsset asset : this.referencedAssets) { if (!asset.isValid()) { return false; } } return true; } @Override public String toString() { final StringBuilder sb = new StringBuilder("InteroperableMasterPackage{"); sb.append("packingList=").append(packingList); sb.append(",\nreferencedAssets=").append(referencedAssets); sb.append('}'); return sb.toString(); } }
4,992
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/IMFErrorLoggerImpl.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary; import com.netflix.imflibrary.utils.ErrorLogger; import javax.annotation.Nonnull; import javax.annotation.concurrent.NotThreadSafe; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static java.lang.Boolean.TRUE; /** * An non-thread-safe implementation of the IMFErrorLogger interface */ @NotThreadSafe public final class IMFErrorLoggerImpl implements IMFErrorLogger //This is really a logging aggregator { private final Set<ErrorLogger.ErrorObject> errorObjects; /** * Instantiates a new IMF error logger impl object */ public IMFErrorLoggerImpl() { this.errorObjects = Collections.synchronizedSet(new HashSet<ErrorLogger.ErrorObject>()); } /** * A method to add error objects to a persistent list * * @param errorCode - error code corresponding to the - error cannot be null * @param errorLevel - error level of the error - cannot be null * @param errorDescription - the error description - cannot be null */ public void addError(@Nonnull IMFErrors.ErrorCodes errorCode, @Nonnull IMFErrors.ErrorLevels errorLevel, @Nonnull String errorDescription) { this.errorObjects.add(new ErrorLogger.ErrorObject(errorCode, errorLevel, errorDescription)); } /** * A method to add an error object to a persistent list * * @param errorObject - error object to be added to a persistent list - cannot be null */ public void addError(@Nonnull ErrorObject errorObject) { this.errorObjects.add(errorObject); } /** * A method to add an error object to a persistent list * * @param errorObjects - a list of error objects to be added to a persistent list - cannot be null */ public void addAllErrors(@Nonnull List<ErrorObject> errorObjects) { this.errorObjects.addAll(errorObjects); } /** * Getter for the number of errors that were detected while reading the MXF file * @return integer representing the number of errors */ public int getNumberOfErrors() { return this.errorObjects.size(); } /** * Getter for the list of errors monitored by this ErrorLogger implementation * @return a list of errors */ public List<ErrorLogger.ErrorObject> getErrors() { List<ErrorObject> errors = new ArrayList<>(this.errorObjects); return Collections.unmodifiableList(errors); } /** * Getter for the list of errors filtered by the ErrorLevel monitored by this ErrorLogger implementation * @param errorLevel to be filtered * @return a list of errors */ public List<ErrorLogger.ErrorObject> getErrors(IMFErrors.ErrorLevels errorLevel) throws IllegalArgumentException { return getErrors(errorLevel, 0, this.errorObjects.size()); } /** * Getter for the list of errors in a specified range of errors filtered by the ErrorLevel monitored by this ErrorLogger implementation * @param errorLevel to be filtered * @param startIndex the start index (inclusive) within the list of errors * @param endIndex the last index (exclusive) within the list of errors * @return a list of errors */ public List<ErrorLogger.ErrorObject> getErrors(IMFErrors.ErrorLevels errorLevel, int startIndex, int endIndex) throws IllegalArgumentException { validateRangeRequest(startIndex, endIndex); List<ErrorObject> errors = new ArrayList<>(this.errorObjects); return Collections.unmodifiableList(errors.subList(startIndex, endIndex).stream().filter(e -> e.getErrorLevel().equals(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL)).collect(Collectors.toList())); } /** * Getter for the list of errors filtered by the ErrorCode monitored by this ErrorLogger implementation * @param errorCode to be filtered * @return a list of errors */ public List<ErrorLogger.ErrorObject> getErrors(IMFErrors.ErrorCodes errorCode) throws IllegalArgumentException { return getErrors(errorCode, 0 , this.errorObjects.size()); } /** * Getter for the list of errors in a specified range of errors filtered by the ErrorLevel monitored by this ErrorLogger implementation * @param errorCode to be filtered * @param startIndex the start index (inclusive) within the list of errors * @param endIndex the last index (exclusive) within the list of errors * @return a list of errors */ public List<ErrorLogger.ErrorObject> getErrors(IMFErrors.ErrorCodes errorCode, int startIndex, int endIndex) throws IllegalArgumentException { validateRangeRequest(startIndex, endIndex); List<ErrorObject> errors = new ArrayList<>(this.errorObjects); return Collections.unmodifiableList(errors.subList(startIndex, endIndex).stream().filter(e -> e.getErrorCode().equals(IMFErrorLogger.IMFErrors.ErrorLevels.FATAL)).collect(Collectors.toList())); } private void validateRangeRequest(int rangeStart, int rangeEnd) throws IllegalArgumentException { if (rangeStart < 0) { throw new IllegalArgumentException(String.format("rangeStart = %d is < 0", rangeStart)); } if (rangeStart > rangeEnd) { throw new IllegalArgumentException(String.format("rangeStart = %d is not <= %d rangeEnd", rangeStart, rangeEnd)); } if (rangeEnd > (this.errorObjects.size())) { throw new IllegalArgumentException(String.format("rangeEnd = %d is not <= (resourceSize) = %d", rangeEnd, (this.errorObjects.size()))); } } public Boolean hasFatalErrors() { return (getErrors(IMFErrors.ErrorLevels.FATAL).size() > 0); } public Boolean hasFatalErrors(int startIndex, int endIndex) { return (getErrors(IMFErrors.ErrorLevels.FATAL, startIndex, endIndex).size() > 0); } }
4,993
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/IMPAsset.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.st0429_8.PackingList; import javax.annotation.concurrent.Immutable; import java.io.File; import java.net.URI; /** * This class represents a thin, immutable wrapper around a PackingList {@link com.netflix.imflibrary.st0429_8.PackingList.Asset Asset}. It holds * a reference to a PackingList Asset along-with the associated absolute URI */ @Immutable public final class IMPAsset { private final URI uri; private final PackingList.Asset asset; /** * Constructor for an {@link IMPAsset IMPAsset} from a PackingList Asset and its URI. Construction * fails if the URI is not absolute * @param uri the absolute URI * @param asset the corresponding asset */ public IMPAsset(URI uri, PackingList.Asset asset) { if (!uri.isAbsolute()) { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); String message = String.format("uri = %s is not absolute", uri); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.URI_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, message); throw new IMFException(message, imfErrorLogger); } this.uri = uri; this.asset = asset; } /** * Checks if this asset is valid * @return true if this asset is valid, false otherwise */ public boolean isValid() {//TODO: this implementation needs to improve return new File(this.uri).exists(); } @Override public String toString() { final StringBuilder sb = new StringBuilder("IMPAsset{"); sb.append("uri=").append(uri); sb.append(", asset=").append(asset); sb.append('}'); return sb.toString(); } }
4,994
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/Colorimetry.java
package com.netflix.imflibrary; import com.netflix.imflibrary.st0377.header.GenericPictureEssenceDescriptor.*; import com.netflix.imflibrary.st0377.header.UL; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * Created by svenkatrav on 10/31/16. */ public enum Colorimetry { Color1(ColorPrimaries.ITU470PAL, TransferCharacteristic.ITU709, CodingEquation.ITU601), Color2(ColorPrimaries.SMPTE170M, TransferCharacteristic.ITU709, CodingEquation.ITU601), Color3(ColorPrimaries.ITU709, TransferCharacteristic.ITU709, CodingEquation.ITU709), Color4(ColorPrimaries.ITU709, TransferCharacteristic.IEC6196624xvYCC, CodingEquation.ITU709), Color5(ColorPrimaries.ITU2020, TransferCharacteristic.ITU2020, CodingEquation.ITU2020NCL), Color6(ColorPrimaries.P3D65, TransferCharacteristic.SMPTEST2084, CodingEquation.None), Color7(ColorPrimaries.ITU2020, TransferCharacteristic.SMPTEST2084, CodingEquation.ITU2020NCL), Color8(ColorPrimaries.ITU2020, TransferCharacteristic.HLG, CodingEquation.ITU2020NCL), Color_App5_AP0(ColorPrimaries.ACES, TransferCharacteristic.Linear, CodingEquation.None), Unknown(ColorPrimaries.Unknown, TransferCharacteristic.Unknown, CodingEquation.Unknown); private final ColorPrimaries colorPrimary; private final TransferCharacteristic transferCharacteristic; private final CodingEquation codingEquation; Colorimetry(@Nonnull ColorPrimaries colorPrimary, @Nonnull TransferCharacteristic transferCharacteristic, @Nonnull CodingEquation codingEquation) { this.colorPrimary = colorPrimary; this.transferCharacteristic = transferCharacteristic; this.codingEquation = codingEquation; } public @Nonnull ColorPrimaries getColorPrimary() { return colorPrimary; } public @Nonnull TransferCharacteristic getTransferCharacteristic() { return transferCharacteristic; } public @Nonnull CodingEquation getCodingEquation() { return codingEquation; } public static @Nonnull Colorimetry valueOf(@Nonnull ColorPrimaries colorPrimary, @Nonnull TransferCharacteristic transferCharacteristic) { for(Colorimetry colorimetry: Colorimetry.values()) { if( colorimetry.getColorPrimary().equals(colorPrimary) && colorimetry.getTransferCharacteristic().equals(transferCharacteristic)) { return colorimetry; } } return Unknown; } public static enum CodingEquation { ITU601(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0E.2B.34.04.01.01.01.04.01.01.01.02.01.00.00")), ITU709(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0E.2B.34.04.01.01.01.04.01.01.01.02.02.00.00")), ITU2020NCL(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0E.2B.34.04.01.01.0D.04.01.01.01.02.06.00.00")), None(null), Unknown(null); private final UL codingEquationUL; CodingEquation(@Nullable UL codingEquationUL) { this.codingEquationUL = codingEquationUL; } public @Nullable UL getCodingEquationUL() { return codingEquationUL; } public static @Nonnull CodingEquation valueOf(@Nullable UL codingEquationUL) { for(CodingEquation codingEquation: CodingEquation.values()) { if( codingEquation.getCodingEquationUL() != null && codingEquation.getCodingEquationUL().equals(codingEquationUL)) { return codingEquation; } } return Unknown; } } public static enum TransferCharacteristic { ITU709(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0E.2B.34.04.01.01.01.04.01.01.01.01.02.00.00")), IEC6196624xvYCC(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0E.2B.34.04.01.01.0D.04.01.01.01.01.08.00.00")), ITU2020(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0E.2B.34.04.01.01.0E.04.01.01.01.01.09.00.00")), SMPTEST2084(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0E.2B.34.04.01.01.0D.04.01.01.01.01.0A.00.00")), HLG(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0E.2B.34.04.01.01.0D.04.01.01.01.01.0B.00.00")), Linear(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0e.2b.34.04.01.01.06.04.01.01.01.01.06.00.00")), Unknown(null); private final UL transferCharacteristicUL; TransferCharacteristic(@Nullable UL transferCharacteristicUL) { this.transferCharacteristicUL = transferCharacteristicUL; } public @Nullable UL getTransferCharacteristicUL() { return this.transferCharacteristicUL; } public static @Nonnull TransferCharacteristic valueOf(@Nullable UL transferCharacteristicUL) { for(TransferCharacteristic transferCharacteristic: TransferCharacteristic.values()) { if( transferCharacteristic.getTransferCharacteristicUL() != null && transferCharacteristic.getTransferCharacteristicUL().equals(transferCharacteristicUL)) { return transferCharacteristic; } } return Unknown; } } public static enum ColorPrimaries { ITU470PAL(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0E.2B.34.04.01.01.06.04.01.01.01.03.02.00.00")), SMPTE170M(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0E.2B.34.04.01.01.06.04.01.01.01.03.01.00.00")), ITU709(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0E.2B.34.04.01.01.06.04.01.01.01.03.03.00.00")), ITU2020(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0E.2B.34.04.01.01.0D.04.01.01.01.03.04.00.00")), P3D65(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0E.2B.34.04.01.01.0D.04.01.01.01.03.06.00.00")), ACES(UL.fromULAsURNStringToUL("urn:smpte:ul:06.0e.2b.34.04.01.01.0d.04.01.01.01.03.07.00.00")), Unknown(null); private final UL colorPrimariesUL; ColorPrimaries(@Nullable UL colorPrimariesUL) { this.colorPrimariesUL = colorPrimariesUL; } public @Nullable UL getColorPrimariesUL() { return this.colorPrimariesUL; } public static @Nonnull ColorPrimaries valueOf(@Nullable UL colorPrimariesUL) { for(ColorPrimaries colorPrimaries: ColorPrimaries.values()) { if( colorPrimaries.getColorPrimariesUL() != null && colorPrimaries.getColorPrimariesUL().equals(colorPrimariesUL)) { return colorPrimaries; } } return Unknown; } } static class ComponentLevel { private final Integer bitDepth; private final Long minLevel; private final Long maxLevel; public ComponentLevel(@Nonnull Integer bitDepth, @Nonnull Long minLevel, @Nonnull Long maxLevel) { this.bitDepth = bitDepth; this.minLevel = minLevel; this.maxLevel = maxLevel; } public @Nonnull Integer getBitDepth() { return bitDepth; } public @Nonnull Long getMaxLevel() { return maxLevel; } public @Nonnull Long getMinLevel() { return minLevel; } public boolean equals(Object other) { if (other == null || !(other instanceof ComponentLevel)) { return false; } ComponentLevel otherObject = (ComponentLevel)other; return (this.bitDepth.equals(otherObject.getBitDepth()) && this.maxLevel.equals(otherObject.getMaxLevel()) && this.minLevel.equals(otherObject.getMinLevel())); } public int hashCode() { Integer hash = 1; hash = hash *31 + this.getBitDepth(); hash = hash *31 + this.getMaxLevel().intValue(); hash = hash *31 + this.getMinLevel().intValue(); return hash; } } public static enum Quantization { QE1(new HashSet<ComponentLevel>() {{ add(new ComponentLevel(8, 16L, 235L)); add(new ComponentLevel(10, 64L, 940L)); add(new ComponentLevel(12, 256L, 3760L)); add(new ComponentLevel(16, 4096L, 60160L)); }} ), QE2(new HashSet<ComponentLevel>() {{ add(new ComponentLevel(8, 0L, 255L)); add(new ComponentLevel(10, 0L, 1023L)); add(new ComponentLevel(12, 0L, 4095L)); add(new ComponentLevel(16, 0L, 65535L)); }} ), Unknown(new HashSet<>()); private final Set<ComponentLevel> componentLevels; Quantization(@Nonnull Set<ComponentLevel> componentLevels) { this.componentLevels = componentLevels; } public @Nonnull Set<ComponentLevel> getComponentLevels() { return this.componentLevels; } public static @Nonnull Quantization valueOf(@Nonnull Integer pixelBitDepth, @Nonnull Long minLevel, @Nonnull Long maxLevel) { ComponentLevel componentLevel = new ComponentLevel(pixelBitDepth, minLevel, maxLevel); for(Quantization quantization: Quantization.values()) { if(quantization.getComponentLevels().contains(componentLevel)) { return quantization; } } return Unknown; } public static @Nonnull Integer componentRangeToBitDepth(@Nonnull Long minLevel, @Nonnull Long maxLevel) { for(Quantization quantization: Quantization.values()) { List<Integer> bitDepths = quantization.getComponentLevels().stream() .filter( e -> e.getMaxLevel().equals(maxLevel) && e.getMinLevel().equals(minLevel)).map(e -> e.bitDepth).collect(Collectors.toList()); if(bitDepths.size() == 1) { return bitDepths.get(0); } } return 0; } } public static enum Sampling { Sampling444(1, 1), Sampling422(2, 1), Unknown(0, 0); Integer horizontalSubSampling; Integer verticalSubSampling; Sampling(@Nonnull Integer horizontalSubSampling, @Nonnull Integer verticalSubSampling) { this.horizontalSubSampling = horizontalSubSampling; this.verticalSubSampling = verticalSubSampling; } public @Nonnull Integer getHorizontalSubSampling() { return horizontalSubSampling; } public @Nonnull Integer getVerticalSubSampling() { return verticalSubSampling; } public static @Nonnull Sampling valueOf(@Nonnull Integer horizontalSubSampling, @Nonnull Integer verticalSubSampling) { for(Sampling sampling: Sampling.values()) { if(sampling.getHorizontalSubSampling().equals(horizontalSubSampling) && sampling.getVerticalSubSampling().equals( verticalSubSampling)) { return sampling; } } return Unknown; } } public static enum ColorModel { RGB(new HashSet<RGBAComponentType>() {{ add(RGBAComponentType.Red); add(RGBAComponentType.Green); add(RGBAComponentType.Blue);}}), YUV(new HashSet<RGBAComponentType>() {{ add(RGBAComponentType.Luma); add(RGBAComponentType.ChromaU); add(RGBAComponentType.ChromaV);}}), Unknown(new HashSet<>()); private final Set<RGBAComponentType> componentTypeSet; ColorModel(@Nonnull Set<RGBAComponentType> componentTypeSet) { this.componentTypeSet = componentTypeSet; } public @Nonnull Set<RGBAComponentType> getComponentTypeSet() { return componentTypeSet; } } }
4,995
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/IMFConstraints.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.st0377.HeaderPartition; import com.netflix.imflibrary.st0377.PartitionPack; import com.netflix.imflibrary.st0377.header.*; import com.netflix.imflibrary.st2067_201.IABEssenceDescriptor; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.utils.Utilities; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * This class consists exclusively of static methods that help verify the compliance of OP1A-conformant * (see st378:2004) MXF header partition as well as MXF partition packs (see st377-1:2011) * with st2067-5:2013 */ public final class IMFConstraints { private static final String IMF_ESSENCE_EXCEPTION_PREFIX = "IMF Essence Component check: "; private static final byte[] IMF_CHANNEL_ASSIGNMENT_UL = {0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x0d, 0x04, 0x02, 0x02, 0x10, 0x04, 0x01, 0x00, 0x00}; public static final String IMSC1TextProfileDesignator = "http://www.w3.org/ns/ttml/profile/imsc1/text"; public static final String IMSC1ImageProfileDesignator = "http://www.w3.org/ns/ttml/profile/imsc1/image"; public static final String IMSC1ImageResourceMimeMediaType = "image/png"; public static final String IMSC1FontResourceMimeMediaType = "application/x-font-opentype"; //to prevent instantiation private IMFConstraints() {} /** * Checks the compliance of an OP1A-conformant header partition with st2067-5:2013. A runtime * exception is thrown in case of non-compliance * * @param headerPartitionOP1A the OP1A-conformant header partition * @param imfErrorLogger - an object for logging errors * @throws IOException - any I/O related error is exposed through an IOException * @return the same header partition wrapped in a HeaderPartitionIMF object */ public static HeaderPartitionIMF checkIMFCompliance(MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A, @Nonnull IMFErrorLogger imfErrorLogger) throws IOException { int previousNumberOfErrors = imfErrorLogger.getErrors().size(); HeaderPartition headerPartition = headerPartitionOP1A.getHeaderPartition(); Preface preface = headerPartition.getPreface(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage; filePackage = (SourcePackage)genericPackage; UUID packageID = filePackage.getPackageMaterialNumberasUUID(); //check 'Operational Pattern' field in Preface byte[] bytes = preface.getOperationalPattern().getULAsBytes(); //Section 8.3.3 st377-1:2011 and Section 5.2 st2067-5:2013 if (OperationalPatternHelper.getPackageComplexity(bytes) != OperationalPatternHelper.PackageComplexity.SinglePackage) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String .format("IMFTrackFile represented by Id %s, Lower four bits of Operational Pattern qualifier byte = 0x%x, should be = 0x01 per the definition of OperationalPattern-1A for Package Complexity.", packageID.toString(), bytes[13])); } //Section 8.3.3 st377-1:2011 if (OperationalPatternHelper.getItemComplexity(bytes) != OperationalPatternHelper.ItemComplexity.SingleItem) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String .format("IMFTrackFile represented by Id %s, Lower four bits of Operational Pattern qualifier byte = 0x%x, should be = 0x01 per the definition of OperationalPattern-1A for Item Complexity.", packageID.toString(), bytes[12])); } //Section 5.1.1#13 st2067-5:2014 , primary package identifier for Preface shall be set to the top-level file package if ((preface.getPrimaryPackage() == null) || (!preface.getPrimaryPackage().equals(preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage()))) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("Primary package identifier for Preface is not set to the top-level file package in the IMFTrackFile represented by ID %s.", packageID.toString())); } //From st2067-5:2013 section 5.1.3, only one essence track shall exist in the file package { MXFUID packageUID = filePackage.getPackageUID(); byte[] packageUID_first16Bytes_Constrained = {0x06, 0x0a, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x01, 0x01, 0x0f, 0x20, 0x13, 0x00, 0x00, 0x00}; byte[] packageUID_first16Bytes = Arrays.copyOfRange(packageUID.getUID(), 0, packageUID_first16Bytes_Constrained.length); boolean result = packageUID_first16Bytes[0] == packageUID_first16Bytes_Constrained[0]; for(int i=1; i < packageUID_first16Bytes_Constrained.length ; i++){ result &= packageUID_first16Bytes[i] == packageUID_first16Bytes_Constrained[i]; } //Section 5.1.5 st2067-2:2016 if(!result){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("PackageUID in FilePackage = %s, which does not obey the constraint that the first 16 bytes = %s in the IMFTrackFile represented by ID %s.", packageUID.toString(), Utilities.serializeBytesToHexString(packageUID_first16Bytes_Constrained), packageID.toString())); } int numEssenceTracks = 0; MXFDataDefinition filePackageMxfDataDefinition = null; for (TimelineTrack timelineTrack : filePackage.getTimelineTracks()) { Sequence sequence = timelineTrack.getSequence(); filePackageMxfDataDefinition = sequence.getMxfDataDefinition(); if (!filePackageMxfDataDefinition.equals(MXFDataDefinition.OTHER)) { numEssenceTracks++; } //Section 5.1.7 st2067-2:2016 if(timelineTrack.getOrigin() != 0){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("The origin property of a timeline track in the IMFTrackFile represented by ID %s is non-zero, only 0 is allowed.", packageID)); } } if (numEssenceTracks != 1) { //Section 5.1.3 of SMPTE st2067-5:2013 imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("Number of essence tracks in FilePackage %s = %d, which is different from 1, this is invalid in the IMFTrackFile represented by ID %s.", filePackage.getInstanceUID(), numEssenceTracks, packageID.toString())); } } //From st2067-2-2013 section 5.3.4.1, top-level file package shall reference a Wave Audio Essence Descriptor //Per st2067-2-2013, section 5.3.4.2, Wave Audio Essence Descriptor shall have 'Channel Assignment' item { for (TimelineTrack timelineTrack : filePackage.getTimelineTracks()) { Sequence sequence = timelineTrack.getSequence(); if (sequence == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("TimelineTrack with instanceUID = %s in the IMFTrackFile represented by ID %s has no sequence.", timelineTrack.getInstanceUID(), packageID.toString())); } else { MXFDataDefinition filePackageMxfDataDefinition = sequence.getMxfDataDefinition(); GenericDescriptor genericDescriptor = filePackage.getGenericDescriptor(); if (filePackageMxfDataDefinition.equals(MXFDataDefinition.SOUND)) { if (genericDescriptor instanceof WaveAudioEssenceDescriptor) { WaveAudioEssenceDescriptor waveAudioEssenceDescriptor = (WaveAudioEssenceDescriptor) genericDescriptor; if ((waveAudioEssenceDescriptor.getChannelAssignmentUL() == null) || (!waveAudioEssenceDescriptor.getChannelAssignmentUL().equals(new MXFUID(IMFConstraints.IMF_CHANNEL_ASSIGNMENT_UL)))) { //Section 5.3.4.2 st2067-2:2016 imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("ChannelAssignment UL for WaveAudioEssenceDescriptor = %s is different from %s in the IMFTrackFile represented by ID %s.", waveAudioEssenceDescriptor.getChannelAssignmentUL(), new MXFUID(IMFConstraints.IMF_CHANNEL_ASSIGNMENT_UL), packageID.toString())); } //RFC-5646 spoken language is a part of the MCALabelSubDescriptor and SoundFieldGroupLabelSubdescriptors according to Section 5.3.6.5 st2067-2:2016 has language around RFC-5646 primary spoken language if (headerPartition.getAudioEssenceSpokenLanguage() == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("WaveAudioEssenceDescriptor in the IMFTrackFile represented by ID %s does not have a RFC5646 spoken language indicated, language code shall be set in the SoundFieldGroupLabelSubDescriptor, unless the AudioEssence does not have a primary spoken language.", packageID.toString())); } else { //Section 6.3.6 st377-4:2012 if (!IMFConstraints.isSpokenLanguageRFC5646Compliant(headerPartition.getAudioEssenceSpokenLanguage())) { List<String> strings = IMFConstraints.getPrimarySpokenLanguageUnicodeString(headerPartition.getAudioEssenceSpokenLanguage()); imfErrorLogger.addError(new ErrorLogger.ErrorObject(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Language Code (%s) in SoundFieldGroupLabelSubdescriptor in the IMFTrackfile represented by ID %s is not RFC5646 compliant", strings, packageID.toString()))); } } //Section 5.3.3 st2067-2:2016 and Section 10 st0382:2007 if (!StructuralMetadata.isAudioWaveClipWrapped(waveAudioEssenceDescriptor.getEssenceContainerUL().getULAsBytes()[14])) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("WaveAudioEssenceDescriptor indicates that the Audio Essence within an Audio Track File is not Wave Clip-Wrapped in the IMFTrackFile represented by ID %s.", packageID.toString())); } List<InterchangeObject.InterchangeObjectBO> subDescriptors = headerPartition.getSubDescriptors(); //Section 5.3.6.2 st2067-2:2016 if (subDescriptors.size() == 0) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("WaveAudioEssenceDescriptor in the IMFTrackFile represented by ID %s indicates a channel count of %d, however there are %d AudioChannelLabelSubdescriptors, every audio channel should refer to exactly one AudioChannelLabelSubDescriptor and vice versa.", packageID.toString(), waveAudioEssenceDescriptor.getChannelCount(), subDescriptors.size())); } else { //Section 5.3.6.2 st2067-2:2016 Map<Long, AudioChannelLabelSubDescriptor> audioChannelLabelSubDescriptorMap = headerPartition.getAudioChannelIDToMCASubDescriptorMap(); if (waveAudioEssenceDescriptor.getChannelCount() == 0 || waveAudioEssenceDescriptor.getChannelCount() != audioChannelLabelSubDescriptorMap.size()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("WaveAudioEssenceDescriptor in the IMFTrackFile represented by ID %s indicates a channel count of %d, however there are %d AudioChannelLabelSubdescriptors, every audio channel should refer to exactly one AudioChannelLabelSubDescriptor and vice versa.", packageID.toString(), waveAudioEssenceDescriptor.getChannelCount(), audioChannelLabelSubDescriptorMap.size())); } for (Long channelID = 1L; channelID <= waveAudioEssenceDescriptor.getChannelCount(); channelID++) { //Section 5.3.6.5 st2067-2:2016 if (!audioChannelLabelSubDescriptorMap.containsKey(channelID)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("AudioChannelLabelSubdescriptor missing for ChannelID %d, in the IMFTrackFile represented by ID %s", channelID, packageID.toString())); } } List<InterchangeObject.InterchangeObjectBO> soundFieldGroupLabelSubDescriptors = subDescriptors.subList(0, subDescriptors.size()).stream().filter(interchangeObjectBO -> interchangeObjectBO.getClass().getEnclosingClass().equals(SoundFieldGroupLabelSubDescriptor.class)).collect(Collectors.toList()); //Section 5.3.6.3 st2067-2:2016 if (soundFieldGroupLabelSubDescriptors.size() != 1) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("WaveAudioEssenceDescriptor in the IMFTrackFile represented by ID %s refers to %d SoundFieldGroupLabelSubDescriptors exactly 1 is required", packageID.toString(), soundFieldGroupLabelSubDescriptors.size())); } else { SoundFieldGroupLabelSubDescriptor.SoundFieldGroupLabelSubDescriptorBO soundFieldGroupLabelSubDescriptorBO = SoundFieldGroupLabelSubDescriptor.SoundFieldGroupLabelSubDescriptorBO.class.cast(soundFieldGroupLabelSubDescriptors.get(0)); //Section 5.3.6.5 st2067-2:2016 if ((soundFieldGroupLabelSubDescriptorBO.getMCATitle() == null || soundFieldGroupLabelSubDescriptorBO.getMCATitle().isEmpty()) || (soundFieldGroupLabelSubDescriptorBO.getMCATitleVersion() == null || soundFieldGroupLabelSubDescriptorBO.getMCATitleVersion().isEmpty()) || (soundFieldGroupLabelSubDescriptorBO.getMCAAudioContentKind() == null || soundFieldGroupLabelSubDescriptorBO.getMCAAudioContentKind().isEmpty()) || (soundFieldGroupLabelSubDescriptorBO.getMCAAudioElementKind() == null || soundFieldGroupLabelSubDescriptorBO.getMCAAudioElementKind().isEmpty())) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("WaveAudioEssenceDescriptor in the IMFTrackFile represented by ID %s refers to a SoundFieldGroupLabelSubDescriptor that is missing one/all of MCATitle, MCATitleVersion, MCAAudioContentKind, MCAAudioElementKind, %n%s.", packageID.toString(), soundFieldGroupLabelSubDescriptorBO.toString())); } SoundFieldGroupLabelSubDescriptor soundFieldGroupLabelSubDescriptor = (SoundFieldGroupLabelSubDescriptor) headerPartition.getSoundFieldGroupLabelSubDescriptors() .get(0); List<InterchangeObject> audioChannelLabelSubDescriptors = headerPartition.getAudioChannelLabelSubDescriptors(); //Section 6.3.2 st377-4:2012 if (soundFieldGroupLabelSubDescriptor.getMCALinkId() == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("SoundFieldGroupLabelSubDescriptor is missing MCALinkID, in the IMFTrackFile represented by ID %s", packageID.toString())); } else { for (InterchangeObject interchangeObject : audioChannelLabelSubDescriptors) { AudioChannelLabelSubDescriptor audioChannelLabelSubDescriptor = AudioChannelLabelSubDescriptor.class.cast(interchangeObject); //Section 5.3.6.3 st2067-2:2016 if (audioChannelLabelSubDescriptor.getSoundfieldGroupLinkId() == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("Audio channel with MCALinkID %s is missing SoundfieldGroupLinkId, in the IMFTrackFile represented by ID %s", audioChannelLabelSubDescriptor.getMCALinkId() != null ? audioChannelLabelSubDescriptor.getMCALinkId().toString() : "", packageID.toString())); } //Section 6.3.2 st377-4:2012 else if (!audioChannelLabelSubDescriptor.getSoundfieldGroupLinkId() .equals(soundFieldGroupLabelSubDescriptor.getMCALinkId())) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("Audio channel with MCALinkID %s refers to wrong SoundfieldGroupLinkId %s, Should refer to %s, in the IMFTrackFile represented by ID %s", audioChannelLabelSubDescriptor.getMCALinkId() != null ? audioChannelLabelSubDescriptor.getMCALinkId().toString() : "", audioChannelLabelSubDescriptor.getSoundfieldGroupLinkId().toString(), soundFieldGroupLabelSubDescriptor.getMCALinkId().toString(), packageID.toString())); } } } } } int audioSampleRate = waveAudioEssenceDescriptor.getAudioSamplingRateNumerator() / waveAudioEssenceDescriptor.getAudioSamplingRateDenominator(); //Section 5.3.2.2 st2067-2:2016 if (audioSampleRate != 48000 && audioSampleRate != 96000) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMF_ESSENCE_EXCEPTION_PREFIX + String.format("WaveAudioEssenceDescriptor in the IMFTrackFile represented by ID %s seems to indicate an Audio Sample Rate = %f, only 48000 and 96000 are allowed.", packageID.toString(), (double) waveAudioEssenceDescriptor.getAudioSamplingRateNumerator() / waveAudioEssenceDescriptor.getAudioSamplingRateDenominator())); } int bitDepth = waveAudioEssenceDescriptor.getQuantizationBits(); //Section 5.3.2.3 st2067-2:2016 if (bitDepth != 24) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMF_ESSENCE_EXCEPTION_PREFIX + String.format("WaveAudioEssenceDescriptor in the IMFTrackFile represented by ID %s seems to indicate an Audio Bit Depth = %d, only 24 is allowed.", packageID.toString(), waveAudioEssenceDescriptor.getQuantizationBits())); } } // else {//Section 5.3.4.1 st2067-2:2016 // imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("Header Partition does not have a WaveAudioEssenceDescriptor set in the IMFTrackFile represented by ID %s", packageID.toString())); // } } else if (filePackageMxfDataDefinition.equals(MXFDataDefinition.DATA)) { if (genericDescriptor instanceof TimedTextDescriptor) { TimedTextDescriptor timedTextDescriptor = TimedTextDescriptor.class.cast(genericDescriptor); //Section 6.8 st2067-2:2016 and st0 429-5 section 7 if (timedTextDescriptor.getEssenceContainerUL().getULAsBytes()[13] != 0x13) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints .IMF_ESSENCE_EXCEPTION_PREFIX + String.format("Invalid Mapping Kind in TimedText essence container UL within IMFTrackFile represented by ID %s.", packageID.toString())); } //https://www.w3.org/TR/ttml-imsc1/ Section 6.1 if (!timedTextDescriptor.getUCSEncoding().equalsIgnoreCase("UTF-8")) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints .IMF_ESSENCE_EXCEPTION_PREFIX + String.format("Invalid UCSEncoding(%s) in TimedTextDescriptor within trackFile represented by ID %s. Only UTF-8 is valid UCSEncoding. ", timedTextDescriptor .getUCSEncoding(), packageID.toString())); } //https://www.w3.org/TR/ttml-imsc1/ Section 6.3 if (!timedTextDescriptor.getNamespaceURI().equals(IMSC1TextProfileDesignator) && !timedTextDescriptor.getNamespaceURI().equals(IMSC1ImageProfileDesignator)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints .IMF_ESSENCE_EXCEPTION_PREFIX + String.format("Invalid NamespaceURI(%s) in TimedTextDescriptor within trackFile represented by ID %s. Valid NamespaceURIs: " + "{%s}, {%s}", timedTextDescriptor.getNamespaceURI(), packageID.toString(), IMSC1TextProfileDesignator, IMSC1ImageProfileDesignator)); } for(TimeTextResourceSubDescriptor textResourceSubDescriptor : timedTextDescriptor.getSubDescriptorList()) { //Section 5.4.5 and 5.4.6 st2067-2:2016 if (!textResourceSubDescriptor.getMimeMediaType().equals(IMSC1ImageResourceMimeMediaType) && !textResourceSubDescriptor.getMimeMediaType().equals (IMSC1FontResourceMimeMediaType)) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, IMFConstraints .IMF_ESSENCE_EXCEPTION_PREFIX + String.format("Invalid MIMEMediaType(%s) in TimedTextResourceSubDescriptor within trackFile represented by ID %s. Valid " + "MIMEMediaTypes: {%s} {%s}", timedTextDescriptor.getNamespaceURI(), packageID.toString(), IMSC1ImageResourceMimeMediaType, IMSC1FontResourceMimeMediaType)); } } } } } } //TODO: data essence core constraints check st 2067-2, 2067-5 and 429-5 //TODO: check for data essence clip wrap } if(imfErrorLogger.hasFatalErrors(previousNumberOfErrors, imfErrorLogger.getNumberOfErrors())){ throw new IMFException(String.format("Found fatal errors in the in the IMFTrackFile represented by ID %s that violate the IMF Core constraints.", packageID.toString()), imfErrorLogger); } return new HeaderPartitionIMF(headerPartitionOP1A); } /** * Checks the compliance of partition packs found in an MXF file with st2067-5:2013. A runtime * exception is thrown in case of non-compliance * * @param partitionPacks the list of partition packs for which the compliance check is performed * @param imfErrorLogger - an object for logging errors */ @SuppressWarnings({"PMD.CollapsibleIfStatements"}) public static void checkIMFCompliance(List<PartitionPack> partitionPacks, IMFErrorLogger imfErrorLogger) { int previousNumberOfErrors = imfErrorLogger.getErrors().size(); //From st2067-5-2013 section 5.1.5, a partition shall only have one of header metadata, essence, index table for (PartitionPack partitionPack : partitionPacks) { if (partitionPack.hasHeaderMetadata()) { if (partitionPack.hasEssenceContainer() || partitionPack.hasIndexTableSegments()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("PartitionPack at offset %d : header metadata = true, essenceContainerData = %s, indexTableSegment = %s, a partition shall have only one of header metadata, essence or index table.", partitionPack.getPartitionByteOffset(), partitionPack.hasEssenceContainer(), partitionPack.hasIndexTableSegments())); } } else if (partitionPack.hasEssenceContainer()) { if (partitionPack.hasHeaderMetadata() || partitionPack.hasIndexTableSegments()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("PartitionPack at offset %d : essenceContainerData = true, header metadata = %s, indexTableSegment = %s, a partition shall have only one of header metadata, essence or index table.", partitionPack.getPartitionByteOffset(), partitionPack.hasHeaderMetadata(), partitionPack.hasIndexTableSegments())); } } else if (partitionPack.hasIndexTableSegments()) { if (partitionPack.hasEssenceContainer() || partitionPack.hasHeaderMetadata()) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("PartitionPack at offset %d : indexTableSegment = true, essenceContainerData = %s, header metadata = %s, a partition shall have only one of header metadata, essence or index table.", partitionPack.getPartitionByteOffset(), partitionPack.hasEssenceContainer(), partitionPack.hasHeaderMetadata())); } } } if(imfErrorLogger.hasFatalErrors(previousNumberOfErrors, imfErrorLogger.getNumberOfErrors())){ throw new MXFException(String.format("Found fatal errors in the IMFTrackFile that violate the IMF Core constraints"), imfErrorLogger); } } /** * Checks if an MXF file containing audio essence is "clip-wrapped" (see st379:2009, st379-2:2010). A * runtime exception is thrown in case the MXF file contains audio essence that is not clip-wrapped * This method does nothing if the MXF file does not contain audio essence * * @param headerPartition the header partition * @param partitionPacks the partition packs */ public static void checkIMFCompliance(HeaderPartition headerPartition, List<PartitionPack> partitionPacks) { Preface preface = headerPartition.getPreface(); MXFDataDefinition filePackageMxfDataDefinition = null; IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage)genericPackage; UUID packageID = filePackage.getPackageMaterialNumberasUUID(); //get essence type { for (TimelineTrack timelineTrack : filePackage.getTimelineTracks()) { Sequence sequence = timelineTrack.getSequence(); if(sequence == null){ imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("TimelineTrack with instanceUID = %s in the IMFTrackFile represented by ID %s has no sequence.", timelineTrack.getInstanceUID(), packageID.toString())); } else if (!sequence.getMxfDataDefinition().equals(MXFDataDefinition.OTHER)) { filePackageMxfDataDefinition = sequence.getMxfDataDefinition(); } } } //check if audio essence is clip-wrapped if (filePackageMxfDataDefinition != null && filePackageMxfDataDefinition.equals(MXFDataDefinition.SOUND)) { int numPartitionsWithEssence = 0; for (PartitionPack partitionPack : partitionPacks) { if (partitionPack.hasEssenceContainer()) { numPartitionsWithEssence++; } } //Section 5.1.5 st2067-5:2013 if (numPartitionsWithEssence != 1) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, IMFConstraints.IMF_ESSENCE_EXCEPTION_PREFIX + String.format("Number of partitions with essence = %d in MXF file with data definition = %s, which is different from 1 in the IMFTrackFile represented by ID %s.", numPartitionsWithEssence, filePackageMxfDataDefinition, packageID.toString())); } } if(imfErrorLogger.hasFatalErrors()){ throw new MXFException(String.format("Found fatal errors in the IMFTrackFile represented by ID %s that violate the IMF Core constraints.", packageID.toString()), imfErrorLogger); } } /** * This class wraps an OP1A-conformant MXF header partition object - wrapping can be done * only if the header partition object is also compliant with st2067-5:2013 */ public static class HeaderPartitionIMF { private final MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A; private final IMFErrorLogger imfErrorLogger; private HeaderPartitionIMF(MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A) { this.headerPartitionOP1A = headerPartitionOP1A; imfErrorLogger = new IMFErrorLoggerImpl(); } /** * Gets the wrapped OP1A-conformant header partition object * @return returns a OP1A-conformant header partition */ public MXFOperationalPattern1A.HeaderPartitionOP1A getHeaderPartitionOP1A() { return this.headerPartitionOP1A; } public boolean hasMatchingEssence(HeaderPartition.EssenceTypeEnum essenceType) { MXFDataDefinition targetMXFDataDefinition; if (essenceType.equals(HeaderPartition.EssenceTypeEnum.MainImageEssence)) { targetMXFDataDefinition = MXFDataDefinition.PICTURE; } else if(essenceType.equals(HeaderPartition.EssenceTypeEnum.MainAudioEssence)) { targetMXFDataDefinition = MXFDataDefinition.SOUND; } else if(essenceType.equals(HeaderPartition.EssenceTypeEnum.IABEssence)) { targetMXFDataDefinition = MXFDataDefinition.SOUND; } else{ targetMXFDataDefinition = MXFDataDefinition.DATA; } GenericPackage genericPackage = this.headerPartitionOP1A.getHeaderPartition().getPreface().getContentStorage(). getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage)genericPackage; boolean hasMatchingEssence = false; for (TimelineTrack timelineTrack : filePackage.getTimelineTracks()) { Sequence sequence = timelineTrack.getSequence(); MXFDataDefinition filePackageMxfDataDefinition = sequence.getMxfDataDefinition(); if (filePackageMxfDataDefinition.equals(targetMXFDataDefinition)) { hasMatchingEssence = true; } } return hasMatchingEssence; } private boolean hasWaveAudioEssenceDescriptor() { GenericPackage genericPackage = this.headerPartitionOP1A.getHeaderPartition().getPreface().getContentStorage(). getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage)genericPackage; boolean hasWaveAudioEssenceDescriptor = false; for (TimelineTrack timelineTrack : filePackage.getTimelineTracks()) { Sequence sequence = timelineTrack.getSequence(); MXFDataDefinition filePackageMxfDataDefinition = sequence.getMxfDataDefinition(); if (filePackageMxfDataDefinition.equals(MXFDataDefinition.SOUND)) { GenericDescriptor genericDescriptor = filePackage.getGenericDescriptor(); if (genericDescriptor instanceof WaveAudioEssenceDescriptor) { hasWaveAudioEssenceDescriptor = true; break; } } } return hasWaveAudioEssenceDescriptor; } /** * Gets the first WaveAudioEssenceDescriptor (st382:2007) structural metadata set from * an OP1A-conformant MXF Header partition. Returns null if none is found * @return returns the first WaveAudioEssenceDescriptor */ public @Nullable WaveAudioEssenceDescriptor getWaveAudioEssenceDescriptor() { if (!hasWaveAudioEssenceDescriptor()) { return null; } WaveAudioEssenceDescriptor waveAudioEssenceDescriptor = null; GenericPackage genericPackage = this.headerPartitionOP1A.getHeaderPartition().getPreface().getContentStorage(). getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage)genericPackage; for (TimelineTrack timelineTrack : filePackage.getTimelineTracks()) { Sequence sequence = timelineTrack.getSequence(); MXFDataDefinition filePackageMxfDataDefinition = sequence.getMxfDataDefinition(); if (filePackageMxfDataDefinition.equals(MXFDataDefinition.SOUND)) { GenericDescriptor genericDescriptor = filePackage.getGenericDescriptor(); if (genericDescriptor instanceof WaveAudioEssenceDescriptor) { waveAudioEssenceDescriptor = (WaveAudioEssenceDescriptor)genericDescriptor; break; } } } return waveAudioEssenceDescriptor; } /** * Gets the first IABEssenceDescriptor structural metadata set from * an OP1A-conformant MXF Header partition. Returns null if none is found * @return returns the first IABEssenceDescriptor */ public @Nullable IABEssenceDescriptor getIABEssenceDescriptor() { IABEssenceDescriptor iabEssenceDescriptor = null; GenericPackage genericPackage = this.headerPartitionOP1A.getHeaderPartition().getPreface().getContentStorage(). getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage)genericPackage; for (TimelineTrack timelineTrack : filePackage.getTimelineTracks()) { Sequence sequence = timelineTrack.getSequence(); MXFDataDefinition filePackageMxfDataDefinition = sequence.getMxfDataDefinition(); if (filePackageMxfDataDefinition.equals(MXFDataDefinition.SOUND)) { GenericDescriptor genericDescriptor = filePackage.getGenericDescriptor(); if (genericDescriptor instanceof IABEssenceDescriptor) { iabEssenceDescriptor = (IABEssenceDescriptor)genericDescriptor; break; } } } return iabEssenceDescriptor; } /** * A method that returns the IMF Essence Component type. * @return essenceTypeEnum an enumeration constant corresponding to the IMFEssenceComponent type */ public HeaderPartition.EssenceTypeEnum getEssenceType(){ HeaderPartition headerPartition = this.headerPartitionOP1A.getHeaderPartition(); Preface preface = headerPartition.getPreface(); MXFDataDefinition filePackageMxfDataDefinition = null; GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage(); SourcePackage filePackage = (SourcePackage)genericPackage; for (TimelineTrack timelineTrack : filePackage.getTimelineTracks()) { Sequence sequence = timelineTrack.getSequence(); if (!sequence.getMxfDataDefinition().equals(MXFDataDefinition.OTHER)) { filePackageMxfDataDefinition = sequence.getMxfDataDefinition(); } } List<HeaderPartition.EssenceTypeEnum> essenceTypes = headerPartition.getEssenceTypes(); if(essenceTypes.size() != 1){ StringBuilder stringBuilder = new StringBuilder(); for(HeaderPartition.EssenceTypeEnum essenceTypeEnum : essenceTypes){ stringBuilder.append(String.format("%s, ", essenceTypeEnum.toString())); } String message = String.format("IMF constrains MXF essences to mono essences only, however more" + " than one EssenceType was detected %s.", stringBuilder.toString()); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, message); throw new MXFException(message, imfErrorLogger); } return essenceTypes.get(0); } /** * A method that returns a string representation of a HeaderPartitionIMF object * * @return string representing the object */ public String toString() { return this.headerPartitionOP1A.toString(); } } /** * A method to verify if the spoken language indicated in the SoundFieldGroupLabelSubDescriptor of the WaveAudioPCMDescriptor * is RFC-5646 compliant or not * @param rfc5646SpokenLanguage the language tag that needs to be verified * @return a boolean indicating the result of the verification check */ public static boolean isSpokenLanguageRFC5646Compliant(String rfc5646SpokenLanguage){ if(rfc5646SpokenLanguage != null){ Matcher matcher = buildRegExpLangRFC5646().matcher(rfc5646SpokenLanguage); return matcher.find(); } return false; } private static List<String> getPrimarySpokenLanguageUnicodeString(String rfc5646SpokenLanguage){ Integer asciiStartRange = 0x21; Integer asciiEndRange = 0x7e; String inputString = rfc5646SpokenLanguage; char[] charArray = inputString.toCharArray(); List<Integer> unicodeCodePoints = new ArrayList<>(); for (int i=0; i<charArray.length;) { if (!Character.isHighSurrogate(charArray[i])) { int unicodeCodePoint = Character.codePointAt(charArray, i, (i+1)); unicodeCodePoints.add(unicodeCodePoint); i++; } else { if ((i + 1) < charArray.length) { int unicodeCodePoint = Character.codePointAt(charArray, i, (i+2)); unicodeCodePoints.add(unicodeCodePoint); i += 2; } else { throw new IllegalArgumentException(String.format("Invalid character in '%s'. Only high surrogate exists", new String(charArray))); } } } StringBuilder unicodeString = new StringBuilder(); unicodeString.append("0x"); StringBuilder stringBuilder = new StringBuilder(); for (int unicodeCodePoint : unicodeCodePoints) { unicodeString.append(String.format("%02x", unicodeCodePoint)); if(unicodeCodePoint < asciiStartRange || unicodeCodePoint > asciiEndRange){ stringBuilder.append("."); } else{ stringBuilder.append(String.format("%s", String.copyValueOf(Character.toChars(unicodeCodePoint)))); } } List<String> strings = new ArrayList<>(); strings.add(unicodeString.toString()); strings.add(stringBuilder.toString()); return strings; } private static Pattern buildRegExpLangRFC5646() { String extLang = "([A-Za-z]{3}(-[A-Za-z]{3}){0,2})"; String language = "(([a-zA-Z]{2,3}(-" + extLang + ")?)|([a-zA-Z]{5,8}))"; String script = "([A-Za-z]{4})"; String region = "([A-Za-z]{2}|\\d{3})"; String variant = "([A-Za-z0-9]{5,8}|(\\d[A-Z-a-z0-9]{3}))"; String singleton = "(\\d|[A-W]|[Y-Z]|[a-w]|[y-z])"; String extension = "(" + singleton + "(-[A-Za-z0-9]{2,8})+)"; String privateUse = "(x(-[A-Za-z0-9]{1,8})+)"; String langTag = language + "(-" + script + ")?(-" + region + ")?(-" + variant + ")*(-" + extension + ")*(-" + privateUse + ")?"; String irregular = "((en-GB-oed)|(i-ami)|(i-bnn)|(i-default)|(i-enochian)|(i-hak)|(i-klingon)|(i-lux)|(i-mingo)|(i-navajo)|(i-pwn)|(i-tao)|(i-tay)|(i-tsu)|(sgn-BE-FR)|(sgn-BE-NL)|(sgn-CH-DE))"; String regular = "((art-lojban)|(cel-gaulish)|(no-bok)|(no-nyn)|(zh-guoyu)|(zh-hakka)|(zh-min)|(zh-min-nan)|(zh-xiang))"; String grandFathered = "(" + irregular + "|" + regular + ")"; StringBuffer languageTag = new StringBuffer(); languageTag.append("(^").append(privateUse).append("$)"); languageTag.append('|'); languageTag.append("(^").append(grandFathered).append("$)"); languageTag.append('|'); languageTag.append("(^").append(langTag).append("$)"); return Pattern.compile(languageTag.toString()); } }
4,996
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/OperationalPatternHelper.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary; import java.util.Arrays; import java.util.EnumSet; /** * An object model for the OperationalPattern defined in st377-1:2011 */ public final class OperationalPatternHelper { private static final int packageComplexity_key_byte_position = 13; //Byte-14 of the OperationalPattern UL identifies the OperationPattern Package Complexity private static final int itemComplexity_key_byte_position = 12; //Byte-13 of the OperationalPattern UL identifies the OperationPattern Package Complexity //Private default constructor to prevent instantiation private OperationalPatternHelper(){ } /** * An enumeration representing the Package Complexity */ public static enum PackageComplexity{ SinglePackage(0x01), GangedPackages(0x02), AlternatePackages (0x03), Unknown(-1); private final int packageComplexityKey; private PackageComplexity (int packageComplexityKey){ this.packageComplexityKey = packageComplexityKey; } private int getPackageComplexityKey(){ return this.packageComplexityKey; } } /** * An enumeration representing ItemComplexity */ public static enum ItemComplexity{ SingleItem(0x01), PlaylistItems(0x02), EditItems (0x03), Unknown(-1); private final int itemComplexityKey; private ItemComplexity (int itemComplexityKey){ this.itemComplexityKey = itemComplexityKey; } private int getItemComplexityKey(){ return this.itemComplexityKey; } } /** * Getter for the Package Complexity corresponding to the UL that is passed in * @param ul the universal label corresponding to the operational pattern that this file complies with * @return returns the Package Complexity corresponding to the Operational Pattern */ public static PackageComplexity getPackageComplexity(byte[] ul){ EnumSet<PackageComplexity> enumSet = EnumSet.copyOf(Arrays.asList(PackageComplexity.values())); for(PackageComplexity packageComplexity : enumSet){ if(packageComplexity.getPackageComplexityKey() == ul[packageComplexity_key_byte_position]){ return packageComplexity; } } return PackageComplexity.Unknown; } /** * Getter for the Item Complexity corresponding to the UL that is passed in * @param ul the universal label corresponding to the operational pattern that this file complies with * @return returns the Item Complexity corresponding to this Operational Pattern */ public static ItemComplexity getItemComplexity(byte[] ul){ EnumSet<ItemComplexity> enumSet = EnumSet.copyOf(Arrays.asList(ItemComplexity.values())); for(ItemComplexity itemComplexity : enumSet){ if(itemComplexity.getItemComplexityKey() == ul[itemComplexity_key_byte_position]){ return itemComplexity; } } return ItemComplexity.Unknown; } }
4,997
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/MXFDataDefinition.java
/* * * * Copyright 2015 Netflix, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.netflix.imflibrary; /** * An enumeration for representing the different MXF essence types */ @SuppressWarnings({"PMD.SingularField"}) public enum MXFDataDefinition { /** * The PICTURE. */ PICTURE(new MXFUID(MXFUID.picture_essence_track)), /** * The SOUND. */ SOUND(new MXFUID(MXFUID.sound_essence_track)), /** * The DATA. */ DATA(new MXFUID(MXFUID.data_essence_track)), /** * The OTHER. */ OTHER(null), ; private final MXFUID mxfUL; private MXFDataDefinition(MXFUID mxfUL) { this.mxfUL = mxfUL; } /** * Getter for data definition corresponding to the Universal Label that was passed * * @param mxfUL the mxf UL * @return the data definition */ public static MXFDataDefinition getDataDefinition(MXFUID mxfUL) { if (mxfUL.equals(PICTURE.mxfUL)) { return PICTURE; } else if (mxfUL.equals(SOUND.mxfUL)) { return SOUND; } else if (mxfUL.equals(DATA.mxfUL)) { return DATA; } else { return OTHER; } } }
4,998
0
Create_ds/photon/src/main/java/com/netflix
Create_ds/photon/src/main/java/com/netflix/imflibrary/MXFUID.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary; import javax.annotation.concurrent.Immutable; import java.util.Arrays; /** * An (immutable) implementation of an MXF UID. Per section 4.1 of st0377-1:2011, a UID is "a generic term which may be * used to refer to a UL, UUID, UMID etc." */ @Immutable public final class MXFUID { /** * from <a href="http://www.smpte-ra.org/mdd/RP224v12-pub-20120418.xls">SMPTE Labels Registry</a> */ static final byte[] picture_essence_track = {0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x01, 0x00, 0x00, 0x00}; /** * The Sound _ essence _ track. */ static final byte[] sound_essence_track = {0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x02, 0x00, 0x00, 0x00}; /** * The Data _ essence _ track. */ static final byte[] data_essence_track = {0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x03, 0x00, 0x00, 0x00}; private final byte[] uid; /** * Instantiates a new MXF uid. * * @param uid the uid */ public MXFUID(byte[] uid) { this.uid = Arrays.copyOf(uid, uid.length); } /** * Getter for uid as a byte[] * * @return the byte [ ] */ public byte[] getUID() { return Arrays.copyOf(this.uid, this.uid.length); } /** * A method that compares 2 MXF UIDs. * Note: this method would return true if and only if the 2 MXF UIDs match. If the object * passed in is not a MXF UID type then this method would return false * @param other the object that needs to compared with this MXFUid object * @return result of the comparison */ public boolean equals(Object other) { if ((other != null) && (other.getClass().equals(MXFUID.class))) { return Arrays.equals(this.uid, ((MXFUID)other).uid); } else { return false; } } /** * A method to generate hash code for this MXF uid * @return hash code corresponding to this MXFUid */ public int hashCode() { return Arrays.hashCode(this.uid); } /** * A method that returns a string representation of a MXFUid object * * @return string representing the object */ public String toString() { if (this.uid.length == 16) { return String.format("0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", this.uid[0], this.uid[1], this.uid[2], this.uid[3], this.uid[4], this.uid[5], this.uid[6], this.uid[7], this.uid[8], this.uid[9], this.uid[10], this.uid[11], this.uid[12], this.uid[13], this.uid[14], this.uid[15]); } else if (this.uid.length == 32) { return String.format("0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", this.uid[0], this.uid[1], this.uid[2], this.uid[3], this.uid[4], this.uid[5], this.uid[6], this.uid[7], this.uid[8], this.uid[9], this.uid[10], this.uid[11], this.uid[12], this.uid[13], this.uid[14], this.uid[15], this.uid[16], this.uid[17], this.uid[18], this.uid[19], this.uid[20], this.uid[21], this.uid[22], this.uid[23], this.uid[24], this.uid[25], this.uid[26], this.uid[27], this.uid[28], this.uid[29], this.uid[30], this.uid[31]); } else { return Arrays.toString(this.uid); } } }
4,999