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/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/ErrorLogger.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 com.netflix.imflibrary.IMFErrorLogger; import java.util.List; public interface ErrorLogger { /** * Getter for the number of errors * * @return the number of errors */ public int getNumberOfErrors(); /** * Getter for the error messages * * @return the errors */ public List<ErrorObject> getErrors(); /** * An object model representing useful information about an Error */ public static final class ErrorObject { private final Enum errorCode; private final Enum errorLevel; private final String errorDescription; /** * Instantiates a new ErrorObject. * * @param errorCode the error code * @param errorLevel the error level * @param errorDescription the error description */ public ErrorObject(Enum errorCode, Enum errorLevel, String errorDescription) { this.errorCode = errorCode; this.errorLevel = errorLevel; this.errorDescription = Utilities.appendPhotonVersionString(errorDescription); ; } /** * Getter for the error description * * @return the error description */ public String getErrorDescription() { return this.errorDescription; } /** * Getter for the ErrorCode of this ErrorObject * @return an errorCode enumeration */ public Enum getErrorCode() { return this.errorCode; } /** * Getter for the ErrorLevel of this ErrorObject * @return an errorLevel enumeration */ public Enum getErrorLevel() { return this.errorLevel; } /** * toString() method to return a string representation of this error object * @return string representation of the error object */ public String toString(){ StringBuilder stringBuilder = new StringBuilder(); if(this.errorLevel == IMFErrorLogger.IMFErrors.ErrorLevels.WARNING){ stringBuilder.append(IMFErrorLogger.IMFErrors.ErrorLevels.WARNING.toString()); } else{ stringBuilder.append("ERROR"); } stringBuilder.append("-"); stringBuilder.append(this.errorDescription); return stringBuilder.toString(); } /** * Equals() method to test for equality of Error Objects * @param other the error object to compare against * @return a boolean representing the result of the equality check */ @Override public boolean equals(Object other){ if(other == null || !other.getClass().equals(ErrorObject.class)){ return false; } ErrorObject otherErrorObject = (ErrorObject) other; return (this.errorCode == otherErrorObject.getErrorCode() && this.errorLevel == otherErrorObject.getErrorLevel() && this.errorDescription.equals(otherErrorObject.getErrorDescription())); } /** * hashCode() method to permit equality checks * @return an integer representing the hashCode of this object */ @Override public int hashCode(){ int hash = 9; hash = hash*31 + this.errorCode.toString().hashCode(); hash = hash*31 + this.errorLevel.toString().hashCode(); hash = hash*31 + this.errorCode.toString().hashCode(); return hash; } } }
5,100
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/UUIDHelper.java
package com.netflix.imflibrary.utils; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.IMFException; import java.util.UUID; public final class UUIDHelper { private static final String UUID_as_a_URN_PREFIX = "urn:uuid:"; private UUIDHelper() { //to prevent instantiation } /** * A helper method to return the UUID without the "urn:uuid:" prefix * @param UUIDasURN a urn:uuid type * @return a UUID without the "urn:uuid:" prefix */ public static UUID fromUUIDAsURNStringToUUID(String UUIDasURN) { if (!UUIDasURN.startsWith(UUIDHelper.UUID_as_a_URN_PREFIX)) { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.UUID_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.FATAL, String.format("Input UUID %s " + "does not start with %s", UUIDasURN, UUIDHelper .UUID_as_a_URN_PREFIX)); throw new IMFException(String.format("Input UUID %s does not start with %s", UUIDasURN, UUIDHelper .UUID_as_a_URN_PREFIX), imfErrorLogger); } return UUID.fromString(UUIDasURN.split(UUIDHelper.UUID_as_a_URN_PREFIX)[1]); } /** * A helper method to return a UUID with the "urn:uuid:" prefix * @param uuid the UUID type * @return a UUID with the "urn:uuid:" prefix as a String */ public static String fromUUID(UUID uuid){ return "urn:uuid:" + uuid.toString(); } }
5,101
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/RegXMLLibDictionary.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 com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.IMFException; import com.sandflow.smpte.register.ElementsRegister; import com.sandflow.smpte.register.GroupsRegister; import com.sandflow.smpte.register.TypesRegister; import com.sandflow.smpte.regxml.dict.DefinitionResolver; import com.sandflow.smpte.regxml.dict.MetaDictionaryCollection; import com.sandflow.smpte.regxml.dict.definitions.Definition; import com.sandflow.smpte.regxml.dict.definitions.EnumerationTypeDefinition; import com.sandflow.smpte.regxml.dict.definitions.RecordTypeDefinition; import com.sandflow.smpte.util.AUID; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import java.util.List; import java.util.stream.Collectors; import static com.sandflow.smpte.regxml.dict.importers.RegisterImporter.fromRegister; /** * A utility class that provides the methods to obtain a RegXML representation of a MXF metadata set */ public final class RegXMLLibDictionary { private final MetaDictionaryCollection metaDictionaryCollection; /** * Constructor for the RegXMLLibHelper * * @throws IMFException - if any error occurs loading registers */ public RegXMLLibDictionary() throws IMFException{ try { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); InputStream in = contextClassLoader.getResourceAsStream("reference-registers/Elements.xml"); Reader elementsRegister = new InputStreamReader(in, Charset.forName("UTF-8")); in = contextClassLoader.getResourceAsStream("reference-registers/Types.xml"); Reader typesRegister = new InputStreamReader(in, Charset.forName("UTF-8")); in = contextClassLoader.getResourceAsStream("reference-registers/Groups.xml"); Reader groupsRegister = new InputStreamReader(in, Charset.forName("UTF-8")); /*in = ClassLoader.getSystemResourceAsStream("reference-registers/Labels.xml"); Reader labelsRegister = new InputStreamReader(in, Charset.forName("UTF-8"));*/ ElementsRegister ereg = ElementsRegister.fromXML(elementsRegister); GroupsRegister greg = GroupsRegister.fromXML(groupsRegister); TypesRegister treg = TypesRegister.fromXML(typesRegister); IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); RegxmlValidationEventHandlerImpl handler = new RegxmlValidationEventHandlerImpl(true); this.metaDictionaryCollection = fromRegister(treg, greg, ereg, handler); if (handler.hasErrors()) { handler.getErrors().stream() .map(e -> new ErrorLogger.ErrorObject( IMFErrorLogger.IMFErrors.ErrorCodes.SMPTE_REGISTER_PARSING_ERROR, e.getValidationEventSeverity(), "Error code : " + e.getCode().name() + " - " + e.getErrorMessage()) ) .forEach(imfErrorLogger::addError); if(imfErrorLogger.hasFatalErrors()) { throw new IMFException(handler.toString(), imfErrorLogger); } } in.close(); } catch (Exception e){ throw new IMFException(String.format("Unable to load resources corresponding to registers")); } } /** * A utility method that gets Symbol name provided URN for an element * @return MetaDictionaryCollection */ public MetaDictionaryCollection getMetaDictionaryCollection() { return this.metaDictionaryCollection; } /** * A utility method that gets Symbol name provided URN for an element * @param URN - URN of the element * @return Symbol name of the element */ public String getSymbolNameFromURN(String URN) { DefinitionResolver definitionResolver = this.metaDictionaryCollection; Definition definition = definitionResolver.getDefinition(AUID.fromURN(URN)); return definition != null ? definition.getSymbol( ) : null; } /** * A utility method that gets an enumeration value provided URN for the enumeration type and the string representation of the enumeration value * @param typeURN - URN for the enumeration type * @param name - String representation of the enumeration * @return Enumeration value */ public Integer getEnumerationValueFromName(String typeURN, String name) { Integer enumValue = null; DefinitionResolver definitionResolver = this.metaDictionaryCollection; Definition definition = definitionResolver.getDefinition(AUID.fromURN(typeURN)); if(definition == null ) { return null; } else if (definition instanceof EnumerationTypeDefinition) { EnumerationTypeDefinition enumerationTypeDefinition = EnumerationTypeDefinition.class.cast(definition); List<Integer> enumList = enumerationTypeDefinition.getElements().stream().filter(e -> e.getName().equals(name)).map(e -> e.getValue()).collect(Collectors.toList()); enumValue = (enumList.size() > 0) ? enumList.get(0) : null; } return enumValue; } /** * A utility method that gets name of a field within a type provided URNs for type and field * @param typeURN - URN for the type * @param fieldURN - URN for the field * @return String representation of the field */ public String getTypeFieldNameFromURN(String typeURN, String fieldURN) { String fieldName = null; DefinitionResolver definitionResolver = this.metaDictionaryCollection; Definition definition = definitionResolver.getDefinition(AUID.fromURN(typeURN)); if(definition == null ) { return null; } else if (definition instanceof RecordTypeDefinition) { RecordTypeDefinition recordTypeDefinition = RecordTypeDefinition.class.cast(definition); List<String> enumList = recordTypeDefinition.getMembers().stream().filter(e -> e.getType().equals(AUID.fromURN(fieldURN))).map(e -> e.getName()).collect(Collectors.toList()); fieldName = (enumList.size() > 0) ? enumList.get(0) : null; } return fieldName; } }
5,102
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/utils/FileByteRangeProvider.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 javax.annotation.concurrent.Immutable; import java.io.*; /** * This class is an implementation of {@link com.netflix.imflibrary.utils.ResourceByteRangeProvider} - the underlying * resource is a file. Unless the underlying file is changed externally, this can be considered to be an immutable * implementation */ @Immutable public final class FileByteRangeProvider implements ResourceByteRangeProvider { private static final int EOF = -1; private static final int BUFFER_SIZE = 1024; private final File resourceFile; private final long fileSize; /** * Constructor for a FileByteRangeProvider * @param resourceFile whose data will be read by this data provider */ public FileByteRangeProvider(File resourceFile) { this.resourceFile = resourceFile; this.fileSize = this.resourceFile.length(); } /** * A method that returns the size in bytes of the underlying resource, in this case a File * @return the size in bytes of the underlying resource, in this case a File */ public long getResourceSize() { return this.fileSize; } /** * A method to obtain bytes in the inclusive range [start, endOfFile] as a file * * @param rangeStart zero indexed inclusive start offset; ranges from 0 through (resourceSize -1) both included * @param workingDirectory the working directory where the output file is placed * @return file containing desired byte range from rangeStart through end of file * @throws IOException - any I/O related error will be exposed through an IOException */ public File getByteRange(long rangeStart, File workingDirectory) throws IOException { return this.getByteRange(rangeStart, this.fileSize - 1, workingDirectory); } /** * A method to obtain bytes in the inclusive range [start, end] as a file * * @param rangeStart zero indexed inclusive start offset; range from [0, (resourceSize -1)] inclusive * @param rangeEnd zero indexed inclusive end offset; range from [0, (resourceSize -1)] inclusive * @param workingDirectory the working directory where the output file is placed * @return file containing desired byte range * @throws IOException - any I/O related error will be exposed through an IOException */ public File getByteRange(long rangeStart, long rangeEnd, File workingDirectory) throws IOException { //validation of range request guarantees that 0 <= rangeStart <= rangeEnd <= (resourceSize - 1) ResourceByteRangeProvider.Utilities.validateRangeRequest(this.fileSize, rangeStart, rangeEnd); File rangeFile = new File(workingDirectory, "range"); try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(this.resourceFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(rangeFile))) { long numBytesSkipped = 0; while (numBytesSkipped < rangeStart) { numBytesSkipped += bis.skip(rangeStart - numBytesSkipped); } long totalNumberOfBytesRead = 0; byte[] bytes = new byte[BUFFER_SIZE]; while (totalNumberOfBytesRead < (rangeEnd - rangeStart + 1)) { int numBytesToRead = (int)Math.min(BUFFER_SIZE, rangeEnd - rangeStart + 1 - totalNumberOfBytesRead); int numBytesRead = bis.read(bytes, 0, numBytesToRead); if (numBytesRead == EOF) { throw new EOFException(); } bos.write(bytes, 0, numBytesRead); totalNumberOfBytesRead += numBytesRead; } } return rangeFile; } /** * This method provides a way to obtain a byte range from the resource in-memory. A limitation of this method is * that the total size of the byte range request is capped at 0x7fffffff (the maximum value possible for type int * in java) * * @param rangeStart zero indexed inclusive start offset; ranges from 0 through (resourceSize -1) both included * @param rangeEnd zero indexed inclusive end offset; ranges from 0 through (resourceSize -1) both included * @return byte[] containing desired byte range * @throws IOException - any I/O related error will be exposed through an IOException */ public byte[] getByteRangeAsBytes(long rangeStart, long rangeEnd) throws IOException { //validation of range request guarantees that 0 <= rangeStart <= rangeEnd <= (resourceSize - 1) ResourceByteRangeProvider.Utilities.validateRangeRequest(this.fileSize, rangeStart, rangeEnd); if((rangeEnd - rangeStart + 1) > Integer.MAX_VALUE){ throw new IOException(String.format("Number of bytes requested = %d is greater than %d", (rangeEnd - rangeStart + 1), Integer.MAX_VALUE)); } int totalNumBytesToRead = (int)(rangeEnd - rangeStart + 1); byte[] bytes = new byte[totalNumBytesToRead]; try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(this.resourceFile))) { long bytesSkipped = bis.skip(rangeStart); if(bytesSkipped != rangeStart){ throw new IOException(String.format("Could not skip %d bytes of data, possible truncated data", rangeStart)); } int totalNumBytesRead = 0; while (totalNumBytesRead < totalNumBytesToRead) { int numBytesRead; numBytesRead = bis.read(bytes, totalNumBytesRead, totalNumBytesToRead - totalNumBytesRead); if (numBytesRead != -1) { totalNumBytesRead += numBytesRead; } else { throw new EOFException(String.format("Tried to read %d bytes from input stream, which ended after reading %d bytes", totalNumBytesToRead, totalNumBytesRead)); } } } return bytes; } public InputStream getByteRangeAsStream(long rangeStart, long rangeEnd) throws IOException { byte[] bytes = this.getByteRangeAsBytes(rangeStart, rangeEnd); return new ByteArrayInputStream(bytes); } }
5,103
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/exceptions/MXFException.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 com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ErrorLogger; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Unchecked exception class that is used when a fatal error occurs in processing of an MXF file */ public class MXFException extends RuntimeException { private final IMFErrorLogger imfErrorLogger; public MXFException() { super(); this.imfErrorLogger = null; } public MXFException(String s) { super(s); this.imfErrorLogger = null; } public MXFException(Throwable t) { super(t); this.imfErrorLogger = null; } public MXFException(String s, Throwable t) { super(s,t); this.imfErrorLogger = null; } public MXFException(String s, @Nonnull IMFErrorLogger imfErrorLogger) { super(s); this.imfErrorLogger = imfErrorLogger; } public List<ErrorLogger.ErrorObject> getErrors() { List errorList = new ArrayList<ErrorLogger.ErrorObject>(); if(this.imfErrorLogger != null) { errorList.addAll(this.imfErrorLogger.getErrors()); } return Collections.unmodifiableList(errorList); } }
5,104
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/exceptions/IMFAuthoringException.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; /** * Unchecked exception class that is used when a fatal error occurs in authoring IMF Assets such as AssetMap, PackingList or CompositionPlaylist */ public class IMFAuthoringException extends RuntimeException { public IMFAuthoringException() { super(); } public IMFAuthoringException(String s) { super(s); } public IMFAuthoringException(Throwable t) { super(t); } public IMFAuthoringException(String s, Throwable t) { super(s,t); } }
5,105
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/exceptions/IMFException.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 com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ErrorLogger; import com.netflix.imflibrary.IMFErrorLogger.IMFErrors; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Unchecked exception class that is used when a fatal error occurs in processing related to IMF layer */ public class IMFException extends RuntimeException { private final IMFErrorLogger errorLogger; public IMFException(String s) { super(s); this.errorLogger = null; } public IMFException(Throwable t) { super(t); this.errorLogger = null; } public IMFException(String s, Throwable t) { super(s, t); this.errorLogger = null; } public IMFException(String s, @Nonnull IMFErrorLogger errorLogger) { super(s); this.errorLogger = errorLogger; } public IMFException(String s, Throwable t, @Nonnull IMFErrorLogger errorLogger) { super(s, t); this.errorLogger = errorLogger; } public List<ErrorLogger.ErrorObject> getErrors() { List errorList = new ArrayList<ErrorLogger.ErrorObject>(); if(this.errorLogger != null) { errorList.addAll(this.errorLogger.getErrors()); } return Collections.unmodifiableList(errorList); } }
5,106
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/CompoundDataTypes.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.st0377.header.InterchangeObject; import com.netflix.imflibrary.st0377.header.UL; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.MXFPropertyPopulator; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.List; /** * This interface provides a namespace for defining object models for various Compound Data Types defined in st377-1:2011 */ public interface CompoundDataTypes { /** * This class corresponds to an object model for "Array" and "Batch" compound data types defined in st377-1:2011 */ final class MXFCollections { //prevent instantiation private MXFCollections() { } /** * Object model corresponding to a Header that represents a collection of MXF metadata sets */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class Header { @MXFProperty(size=4) private final Long numberOfElements = null; @MXFProperty(size=4) private final Long sizeOfElement = null; /** * Instantiates a new collection Header. * * @param byteProvider the mxf byte provider * @throws IOException the iO exception */ public Header(ByteProvider byteProvider) throws IOException { MXFPropertyPopulator.populateField(byteProvider, this, "numberOfElements"); MXFPropertyPopulator.populateField(byteProvider, this, "sizeOfElement"); } /** * Getter for the number of elements in the MXF collection of metadata sets * * @return the number of elements */ public long getNumberOfElements() { return this.numberOfElements; } /** * Getter for the size of the header representing the collection of MXF metadata sets. * * @return the size of element */ public long getSizeOfElement() { return this.sizeOfElement; } /** * A method that returns a string representation of a MXF Collection header object * * @return string representing the object */ public String toString() { return String.format("numberOfElements = %d, sizeOfElement = %d%n", this.numberOfElements, this.sizeOfElement); } } /** * Object model for a generic MXF metadata set collection. * @param <E> the type parameter */ @Immutable public static final class MXFCollection<E> { private final Header header; private final List<E> entries; private final String name; /** * Instantiates a new MXF metadata set collection. * * @param header the header * @param entries the entries * @param name the name */ public MXFCollection(Header header, List<E> entries, String name) { this.header = header; this.entries = java.util.Collections.unmodifiableList(entries); this.name = name; } /** * Getter for the number of MXF metadata sets in the collection * * @return the int */ public int size() { return this.entries.size(); } /** * Getter for an unmodifiable list of MXF metadata sets * * @return the entries */ public List<E> getEntries() { return java.util.Collections.unmodifiableList(this.entries); } /** * A method that returns a string representation of a MXF collection of metadata sets object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("================== %s ======================%n", this.name)); sb.append(this.header.toString()); for (E entry : entries) { if (entry instanceof byte[]) { byte[] bytes = (byte[])entry; sb.append(String.format("0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15])); } else if (entry instanceof Number) { sb.append(String.format("0x%x(%d)%n", entry, entry)); } else if (entry instanceof InterchangeObject.InterchangeObjectBO.StrongRef || entry instanceof UL){ sb.append(String.format("%s%n", entry.toString())); } else { sb.append(entry.toString()); } } return sb.toString(); } } } /** * This class corresponds to an object model for "Rational" compound data type defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) final class Rational { @MXFProperty(size=4) private final Long numerator = null; @MXFProperty(size=4) private final Long denominator = null; /** * Instantiates a new Rational. * * @param byteProvider the mxf byte provider * @throws IOException the iO exception */ public Rational(ByteProvider byteProvider) throws IOException { MXFPropertyPopulator.populateField(byteProvider, this, "numerator"); MXFPropertyPopulator.populateField(byteProvider, this, "denominator"); } /** * Getter for the numerator of the rational * * @return the numerator */ public long getNumerator() { return this.numerator; } /** * Getter for the denominator of the rational * * @return the denominator */ public long getDenominator() { return this.denominator; } /** * A method to compare 2 rationals, returns true if the rationals match or false if they do not * Note : If the object that was passed in is not an instance of rational this method will return * false * @param other the object that this rational object should be compared with * @return result of comparing this rational object with the object that was passed in */ public boolean equals(Object other) { if (!(other instanceof Rational)) { return false; } Rational otherObject = (Rational)other; return (this.numerator != null) && (this.numerator.equals(otherObject.numerator)) && (this.denominator != null) && (this.denominator.equals(otherObject.denominator)); } /** * A method that returns the sum of hashes corresponding to the numerator and denominator of this rational * @return the sum of hashes corresponding to the numerator and denominator of this rational */ public int hashCode() { return numerator.hashCode() + denominator.hashCode(); } /** * A method that returns a string representation of a Rational object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("numerator = %d, denominator = %d%n", this.numerator, this.denominator)); return sb.toString(); } } /** * This class corresponds to an object model for "Timestamp" compound data type defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) final class Timestamp { @MXFProperty(size=2) private final Short year = null; @MXFProperty(size=1) private final Short month = null; @MXFProperty(size=1) private final Short day = null; @MXFProperty(size=1) private final Short hour = null; @MXFProperty(size=1) private final Short minute = null; @MXFProperty(size=1) private final Short second = null; @MXFProperty(size=1) private final Short msecByFour = null; /** * Instantiates a new Timestamp. * * @param byteProvider the input sequence of bytes * @throws IOException - any I/O related error will be exposed through an IOException */ public Timestamp(ByteProvider byteProvider) throws IOException { MXFPropertyPopulator.populateField(byteProvider, this, "year"); MXFPropertyPopulator.populateField(byteProvider, this, "month"); MXFPropertyPopulator.populateField(byteProvider, this, "day"); MXFPropertyPopulator.populateField(byteProvider, this, "hour"); MXFPropertyPopulator.populateField(byteProvider, this, "minute"); MXFPropertyPopulator.populateField(byteProvider, this, "second"); MXFPropertyPopulator.populateField(byteProvider, this, "msecByFour"); } /** * A method that returns a string representation of a Timestamp object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("year = %d, month = %d, day = %d, hour = %d, minute = %d, second = %d, msec = %d%n", this.year, this.month, this.day, this.hour, this.minute, this.second, this.msecByFour*4)); return sb.toString(); } } }
5,107
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/HeaderPartition.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.KLVPacket; import com.netflix.imflibrary.MXFPropertyPopulator; 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.*; import com.netflix.imflibrary.st2067_2.AudioContentKind; import com.netflix.imflibrary.st2067_2.Composition; import com.netflix.imflibrary.st2067_201.IABEssenceDescriptor; import com.netflix.imflibrary.st2067_201.IABSoundfieldLabelSubDescriptor; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * This class corresponds to an object model for the Header Partition construct defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.SingularField"}) public final class HeaderPartition { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: "; private static final Long IMF_MXF_HEADER_PARTITION_OFFSET = 0L; //The IMF Essence component spec (SMPTE ST-2067-5:2013) constrains the byte offset of the Header Partition to the start of the file private final PartitionPack partitionPack; private final PrimerPack primerPack; private final Map<String, List<InterchangeObject>> interchangeObjectsMap = new LinkedHashMap<>(); private final Map<String, List<InterchangeObject.InterchangeObjectBO>> interchangeObjectBOsMap = new LinkedHashMap<>(); private final Map<MXFUID, InterchangeObject> uidToMetadataSets = new LinkedHashMap<>(); private final Map<MXFUID, InterchangeObject.InterchangeObjectBO> uidToBOs = new LinkedHashMap<>(); private final IMFErrorLogger imfErrorLogger; private static final Logger logger = LoggerFactory.getLogger(HeaderPartition.class); /** * Instantiates a new MXF Header partition. * * @param byteProvider the input sequence of bytes * @param byteOffset the byte offset corresponding to the HeaderPartition * @param maxPartitionSize the size of the header partition * @param imfErrorLogger an IMFErrorLogger dedicated to this header partition * @throws IOException - any I/O related error will be exposed through an IOException */ public HeaderPartition(ByteProvider byteProvider, long byteOffset, long maxPartitionSize, IMFErrorLogger imfErrorLogger) throws IOException { this.imfErrorLogger = imfErrorLogger; long numBytesRead = 0; int numErrors = imfErrorLogger.getNumberOfErrors(); //Number of errors prior to parsing and reading the HeaderPartition //read partition pack if(byteOffset != IMF_MXF_HEADER_PARTITION_OFFSET){ throw new MXFException(String.format("Expected the header partition to be at offset %d, whereas it is located at offset %d in the MXF file", IMF_MXF_HEADER_PARTITION_OFFSET, byteOffset)); } this.partitionPack = new PartitionPack(byteProvider, IMF_MXF_HEADER_PARTITION_OFFSET, false, imfErrorLogger); if(!this.partitionPack.isValidHeaderPartition()) { throw new MXFException("Found an invalid header partition"); } numBytesRead += this.partitionPack.getKLVPacketSize(); Long byteOffsetOfNextKLVPacket = byteOffset + numBytesRead; //read primer pack or a single KLV fill item followed by primer pack { KLVPacket.Header header = new KLVPacket.Header(byteProvider, byteOffsetOfNextKLVPacket); byte[] key = Arrays.copyOf(header.getKey(), header.getKey().length); numBytesRead += header.getKLSize(); if (PrimerPack.isValidKey(key)) { this.primerPack = new PrimerPack(byteProvider, header); numBytesRead += header.getVSize(); } else { byteProvider.skipBytes(header.getVSize()); numBytesRead += header.getVSize(); header = new KLVPacket.Header(byteProvider, byteOffsetOfNextKLVPacket); key = Arrays.copyOf(header.getKey(), header.getKey().length); numBytesRead += header.getKLSize(); if (PrimerPack.isValidKey(key)) { this.primerPack = new PrimerPack(byteProvider, header); numBytesRead += header.getVSize(); } else { throw new MXFException("Could not find primer pack"); } } } byteOffsetOfNextKLVPacket = byteOffset + numBytesRead; //read structural metadata + KLV fill items while (numBytesRead < maxPartitionSize) { KLVPacket.Header header = new KLVPacket.Header(byteProvider, byteOffsetOfNextKLVPacket); //logger.info(String.format("Found KLV item with key = %s, length field size = %d, length value = %d", new MXFUID(header.getKey()), header.getLSize(), header.getVSize())); byte[] key = Arrays.copyOf(header.getKey(), header.getKey().length); numBytesRead += header.getKLSize(); if (StructuralMetadata.isStructuralMetadata(Arrays.copyOf(header.getKey(), header.getKey().length)) || StructuralMetadata.isDescriptiveMetadata(Arrays.copyOf(header.getKey(), header.getKey().length))) { Class clazz = StructuralMetadata.getStructuralMetadataSetClass(key); if(!clazz.getSimpleName().equals(Object.class.getSimpleName())){ //logger.info(String.format("KLV item with key = %s corresponds to class %s", new MXFUID(header.getKey()), clazz.getSimpleName())); InterchangeObject.InterchangeObjectBO interchangeObjectBO = this.constructInterchangeObjectBO(clazz, header, byteProvider, this.primerPack.getLocalTagEntryBatch().getLocalTagToUIDMap(), imfErrorLogger); List<InterchangeObject.InterchangeObjectBO> list = this.interchangeObjectBOsMap.get(interchangeObjectBO.getClass().getSimpleName()); if(list == null){ list = new ArrayList<>(); this.interchangeObjectBOsMap.put(interchangeObjectBO.getClass().getSimpleName(), list); } list.add(interchangeObjectBO); uidToBOs.put(interchangeObjectBO.getInstanceUID(), interchangeObjectBO); if(interchangeObjectBO instanceof MaterialPackage.MaterialPackageBO || interchangeObjectBO instanceof SourcePackage.SourcePackageBO){ GenericPackage.GenericPackageBO genericPackageBO = (GenericPackage.GenericPackageBO)interchangeObjectBO; uidToBOs.put(genericPackageBO.getPackageUID(), genericPackageBO); } } else { byteProvider.skipBytes(header.getVSize()); } } else { byteProvider.skipBytes(header.getVSize()); } numBytesRead += header.getVSize(); byteOffsetOfNextKLVPacket = byteOffset + numBytesRead; } //header partition validation int prefaceSetCount = (this.interchangeObjectBOsMap.containsKey(Preface.PrefaceBO.class.getSimpleName()) && this.interchangeObjectBOsMap.get(Preface.PrefaceBO.class.getSimpleName()) != null) ? this.interchangeObjectBOsMap.get(Preface.PrefaceBO.class.getSimpleName()).size() : 0; if (prefaceSetCount != 1) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL, HeaderPartition.ERROR_DESCRIPTION_PREFIX + String.format("Found %d Preface sets, only one is allowed in header partition", prefaceSetCount)); } if (imfErrorLogger.getNumberOfErrors() > numErrors)//Flag an exception if any errors were accumulated while parsing and reading the HeaderPartition { List<ErrorLogger.ErrorObject> errorObjectList = imfErrorLogger.getErrors(); for(int i=numErrors; i< errorObjectList.size(); i++) { logger.error(errorObjectList.get(i).getErrorDescription()); } throw new MXFException(String.format("%d errors encountered when reading header partition", imfErrorLogger.getNumberOfErrors() - numErrors)); } Set<InterchangeObject.InterchangeObjectBO> parsedInterchangeObjectBOs = new LinkedHashSet<>(); for (Map.Entry<MXFUID, InterchangeObject.InterchangeObjectBO> entry : uidToBOs.entrySet()) { parsedInterchangeObjectBOs.add(entry.getValue()); } Map<MXFUID, Node> instanceIDToNodes = new LinkedHashMap<>(); for(InterchangeObject.InterchangeObjectBO interchangeObjectBO : parsedInterchangeObjectBOs) { instanceIDToNodes.put(interchangeObjectBO.getInstanceUID(), new Node(interchangeObjectBO.getInstanceUID())); } for (Map.Entry<MXFUID, Node> entry : instanceIDToNodes.entrySet()) { Node node = entry.getValue(); InterchangeObject.InterchangeObjectBO interchangeObjectBO = uidToBOs.get(node.uid); List<MXFUID> dependentUIDs = MXFPropertyPopulator.getDependentUIDs(interchangeObjectBO); for(MXFUID MXFUID : dependentUIDs) { InterchangeObject.InterchangeObjectBO dependentInterchangeObjectBO = uidToBOs.get(MXFUID); if (dependentInterchangeObjectBO != null) { Node providerNode = instanceIDToNodes.get(dependentInterchangeObjectBO.getInstanceUID()); // providerNode.provides.add(node); node.depends.add(providerNode); } } } List<Node> nodeList = new ArrayList<>(instanceIDToNodes.values()); List<Node> resolvedList = resolve(nodeList); for(Node node : resolvedList) { InterchangeObject.InterchangeObjectBO interchangeObjectBO = uidToBOs.get(node.uid); if (node.depends.size() == 0 && !interchangeObjectBO.getClass().equals(SourceClip.SourceClipBO.class) && !interchangeObjectBO.getClass().equals(Sequence.SequenceBO.class) && !interchangeObjectBO.getClass().equals(TimedTextDescriptor.TimedTextDescriptorBO.class)){ InterchangeObject interchangeObject = this.constructInterchangeObject(interchangeObjectBO.getClass().getEnclosingClass(), interchangeObjectBO, node); this.cacheInterchangeObject(interchangeObject); this.uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), interchangeObject); if (interchangeObjectBO instanceof GenericPackage.GenericPackageBO) { this.uidToMetadataSets.put(((GenericPackage.GenericPackageBO) interchangeObjectBO).getPackageUID(), interchangeObject); } } else { if (interchangeObjectBO.getClass().getEnclosingClass().equals(SourceClip.class)) { GenericPackage genericPackage = null; for (Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); if (dependentInterchangeObject instanceof GenericPackage) { genericPackage = (GenericPackage) dependentInterchangeObject; } } SourceClip sourceClip = new SourceClip((SourceClip.SourceClipBO) interchangeObjectBO, genericPackage); this.cacheInterchangeObject(sourceClip); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), sourceClip); } else if (interchangeObjectBO.getClass().getEnclosingClass().equals(Sequence.class)) { List<StructuralComponent> structuralComponents = new ArrayList<>(); for (Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); if (dependentInterchangeObject instanceof StructuralComponent) { structuralComponents.add((StructuralComponent) dependentInterchangeObject); } } Sequence sequence = new Sequence((Sequence.SequenceBO) interchangeObjectBO, structuralComponents); this.cacheInterchangeObject(sequence); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), sequence); } else if (interchangeObjectBO.getClass().getEnclosingClass().equals(TimelineTrack.class)) { Sequence sequence = null; for (Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); if (dependentInterchangeObject instanceof Sequence) { sequence = (Sequence) dependentInterchangeObject; } TimelineTrack timelineTrack = new TimelineTrack((TimelineTrack.TimelineTrackBO) interchangeObjectBO, sequence); this.cacheInterchangeObject(timelineTrack); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), timelineTrack); } } else if (interchangeObjectBO.getClass().getEnclosingClass().equals(StaticTrack.class)) { Sequence sequence = null; for (Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); if (dependentInterchangeObject instanceof Sequence) { sequence = (Sequence) dependentInterchangeObject; } StaticTrack staticTrack = new StaticTrack((StaticTrack.StaticTrackBO) interchangeObjectBO, sequence); this.cacheInterchangeObject(staticTrack); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), staticTrack); } } else if (interchangeObjectBO.getClass().getEnclosingClass().equals(SourcePackage.class)) { List<GenericTrack> genericTracks = new ArrayList<>(); GenericDescriptor genericDescriptor = null; for (Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); if (dependentInterchangeObject instanceof GenericTrack) { genericTracks.add((GenericTrack) dependentInterchangeObject); } else if (dependentInterchangeObject instanceof GenericDescriptor) { genericDescriptor = (GenericDescriptor) dependentInterchangeObject; } } SourcePackage sourcePackage = new SourcePackage((SourcePackage.SourcePackageBO) interchangeObjectBO, genericTracks, genericDescriptor); this.cacheInterchangeObject(sourcePackage); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), sourcePackage); uidToMetadataSets.put(((SourcePackage.SourcePackageBO) interchangeObjectBO).getPackageUID(), sourcePackage); } else if (interchangeObjectBO.getClass().getEnclosingClass().equals(MaterialPackage.class)) { List<GenericTrack> genericTracks = new ArrayList<>(); for (Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); if (dependentInterchangeObject instanceof GenericTrack) { genericTracks.add((GenericTrack) dependentInterchangeObject); } } MaterialPackage materialPackage = new MaterialPackage((MaterialPackage.MaterialPackageBO) interchangeObjectBO, genericTracks); this.cacheInterchangeObject(materialPackage); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), materialPackage); uidToMetadataSets.put(((MaterialPackage.MaterialPackageBO) interchangeObjectBO).getPackageUID(), materialPackage); } else if (interchangeObjectBO.getClass().getEnclosingClass().equals(EssenceContainerData.class)) { GenericPackage genericPackage = null; for (Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); if (dependentInterchangeObject instanceof GenericPackage) { genericPackage = (GenericPackage) dependentInterchangeObject; } } EssenceContainerData essenceContainerData = new EssenceContainerData( (EssenceContainerData.EssenceContainerDataBO) interchangeObjectBO, genericPackage); this.cacheInterchangeObject(essenceContainerData); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), essenceContainerData); } else if (interchangeObjectBO.getClass().getEnclosingClass().equals(ContentStorage.class)) { List<GenericPackage> genericPackageList = new ArrayList<>(); List<EssenceContainerData> essenceContainerDataList = new ArrayList<>(); for (Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); if (dependentInterchangeObject instanceof GenericPackage) { genericPackageList.add((GenericPackage) dependentInterchangeObject); } else if (dependentInterchangeObject instanceof EssenceContainerData) { essenceContainerDataList.add((EssenceContainerData) dependentInterchangeObject); } } ContentStorage contentStorage = new ContentStorage( (ContentStorage.ContentStorageBO) interchangeObjectBO, genericPackageList, essenceContainerDataList); this.cacheInterchangeObject(contentStorage); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), contentStorage); } else if (interchangeObjectBO.getClass().getEnclosingClass().equals(Preface.class)) { GenericPackage genericPackage = null; ContentStorage contentStorage = null; for (Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); if (dependentInterchangeObject instanceof GenericPackage) { genericPackage = (GenericPackage) dependentInterchangeObject; } else if (dependentInterchangeObject instanceof ContentStorage) { contentStorage = (ContentStorage) dependentInterchangeObject; } } Preface preface = new Preface((Preface.PrefaceBO) interchangeObjectBO, genericPackage, contentStorage); this.cacheInterchangeObject(preface); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), preface); } else if(interchangeObjectBO.getClass().getEnclosingClass().equals(CDCIPictureEssenceDescriptor.class)){ for(Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); /*Although we do retrieve the dependent SubDescriptor for this CDCIPictureEssenceDescriptor we do not really have a need for it, * since it can always be retrieved using the strong reference present in the subDescriptors collection of the CDCIPictureEssenceDescriptor * on the other hand passing a reference to the SubDescriptor to the constructor can be problematic since SubDescriptors are optional*/ JPEG2000PictureSubDescriptor jpeg2000PictureSubDescriptor = null; if(dependentInterchangeObject instanceof JPEG2000PictureSubDescriptor){ jpeg2000PictureSubDescriptor = (JPEG2000PictureSubDescriptor) dependentInterchangeObject; } /*Add similar casting code for other sub descriptors when relevant*/ } CDCIPictureEssenceDescriptor cdciPictureEssenceDescriptor = new CDCIPictureEssenceDescriptor((CDCIPictureEssenceDescriptor.CDCIPictureEssenceDescriptorBO) interchangeObjectBO); this.cacheInterchangeObject(cdciPictureEssenceDescriptor); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), cdciPictureEssenceDescriptor); } else if(interchangeObjectBO.getClass().getEnclosingClass().equals(RGBAPictureEssenceDescriptor.class)){ for(Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); /*Although we do retrieve the dependent SubDescriptor for this RGBAPictureEssenceDescriptor we do not really have a need for it, * since it can always be retrieved using the strong reference present in the subDescriptors collection of the RGBAPictureEssenceDescriptor * on the other hand passing a reference to the SubDescriptor to the constructor can be problematic since SubDescriptors are optional*/ JPEG2000PictureSubDescriptor jpeg2000PictureSubDescriptor = null; if(dependentInterchangeObject instanceof JPEG2000PictureSubDescriptor){ jpeg2000PictureSubDescriptor = (JPEG2000PictureSubDescriptor) dependentInterchangeObject; } ACESPictureSubDescriptor acesPictureSubDescriptor = null; if(dependentInterchangeObject instanceof ACESPictureSubDescriptor){ acesPictureSubDescriptor = (ACESPictureSubDescriptor) dependentInterchangeObject; } TargetFrameSubDescriptor targetFrameSubDescriptor = null; if(dependentInterchangeObject instanceof TargetFrameSubDescriptor){ targetFrameSubDescriptor = (TargetFrameSubDescriptor) dependentInterchangeObject; } /*Add similar casting code for other sub descriptors when relevant*/ } RGBAPictureEssenceDescriptor rgbaPictureEssenceDescriptor = new RGBAPictureEssenceDescriptor((RGBAPictureEssenceDescriptor.RGBAPictureEssenceDescriptorBO) interchangeObjectBO); this.cacheInterchangeObject(rgbaPictureEssenceDescriptor); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), rgbaPictureEssenceDescriptor); } else if(interchangeObjectBO.getClass().getEnclosingClass().equals(WaveAudioEssenceDescriptor.class)){ List<InterchangeObject> subDescriptors = new ArrayList<InterchangeObject>(); for(Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); /* * Although we do retrieve the dependent SubDescriptors for this WaveAudioEssenceDescriptor we do not really have a need for it, * since it can always be retrieved using the strong reference present in the subDescriptors collection of the WaveAudioEssenceDescriptor. * On the other hand passing a reference to a SubDescriptor to the WaveAudioEssenceDescriptor's constructor can be problematic since * SubDescriptors are optional */ AudioChannelLabelSubDescriptor audioChannelLabelSubDescriptor = null; SoundFieldGroupLabelSubDescriptor soundFieldGroupLabelSubDescriptor = null; if(dependentInterchangeObject instanceof AudioChannelLabelSubDescriptor){ audioChannelLabelSubDescriptor = (AudioChannelLabelSubDescriptor) dependentInterchangeObject; subDescriptors.add(audioChannelLabelSubDescriptor); } else if (dependentInterchangeObject instanceof SoundFieldGroupLabelSubDescriptor){ soundFieldGroupLabelSubDescriptor = (SoundFieldGroupLabelSubDescriptor) dependentInterchangeObject; subDescriptors.add(soundFieldGroupLabelSubDescriptor); } } if(node.depends.size() > 0 && subDescriptors.size() == 0){ throw new MXFException(String.format("The WaveAudioEssenceDescriptor in the essence has dependencies, but neither of them is a AudioChannelLabelSubDescriptor nor SoundFieldGroupLabelSubDescriptor")); } WaveAudioEssenceDescriptor waveAudioEssenceDescriptor = new WaveAudioEssenceDescriptor((WaveAudioEssenceDescriptor.WaveAudioEssenceDescriptorBO) interchangeObjectBO); this.cacheInterchangeObject(waveAudioEssenceDescriptor); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), waveAudioEssenceDescriptor); } else if(interchangeObjectBO.getClass().getEnclosingClass().equals(IABEssenceDescriptor.class)){ IABEssenceDescriptor iabEssenceDescriptor = new IABEssenceDescriptor((IABEssenceDescriptor.IABEssenceDescriptorBO) interchangeObjectBO); this.cacheInterchangeObject(iabEssenceDescriptor); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), iabEssenceDescriptor); } else if(interchangeObjectBO.getClass().getEnclosingClass().equals(TimedTextDescriptor.class)){ List<TimeTextResourceSubDescriptor> subDescriptorList = new ArrayList<>(); for(Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); if(dependentInterchangeObject instanceof TimeTextResourceSubDescriptor) { subDescriptorList.add((TimeTextResourceSubDescriptor)dependentInterchangeObject); } } TimedTextDescriptor timedTextDescriptor = new TimedTextDescriptor((TimedTextDescriptor.TimedTextDescriptorBO) interchangeObjectBO, subDescriptorList); this.cacheInterchangeObject(timedTextDescriptor); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), timedTextDescriptor); } else if(interchangeObjectBO.getClass().getEnclosingClass().equals(TextBasedDMFramework.class)){ TextBasedObject textBasedObject = null; for(Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); if(dependentInterchangeObject instanceof TextBasedObject) { textBasedObject = (TextBasedObject)dependentInterchangeObject; } } TextBasedDMFramework textBasedDMFramework = new TextBasedDMFramework((TextBasedDMFramework.TextBasedDMFrameworkBO) interchangeObjectBO, textBasedObject); this.cacheInterchangeObject(textBasedDMFramework); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), textBasedDMFramework); } else if(interchangeObjectBO.getClass().getEnclosingClass().equals(DescriptiveMarkerSegment.class)){ DMFramework dmFramework = null; for(Node dependent : node.depends) { InterchangeObject dependentInterchangeObject = uidToMetadataSets.get(dependent.uid); if(dependentInterchangeObject instanceof TextBasedDMFramework) { dmFramework = (TextBasedDMFramework)dependentInterchangeObject; } } DescriptiveMarkerSegment descriptiveMarkerSegment = new DescriptiveMarkerSegment((DescriptiveMarkerSegment.DescriptiveMarkerSegmentBO) interchangeObjectBO, dmFramework); this.cacheInterchangeObject(descriptiveMarkerSegment); uidToMetadataSets.put(interchangeObjectBO.getInstanceUID(), descriptiveMarkerSegment); } } } } /** * A factory method to reflectively construct InterchangeObjectBO types by classname and argument list * @return the constructed InterchangeBO */ private InterchangeObject.InterchangeObjectBO constructInterchangeObjectBO(Class clazz, KLVPacket.Header header, ByteProvider byteProvider, Map localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException{ try { Constructor<?> constructor = clazz.getConstructor(KLVPacket.Header.class, ByteProvider.class, Map.class, IMFErrorLogger.class); InterchangeObject.InterchangeObjectBO interchangeObjectBO = (InterchangeObject.InterchangeObjectBO)constructor.newInstance(header, byteProvider, localTagToUIDMap, imfErrorLogger); String simpleClassName = interchangeObjectBO.getClass().getSimpleName(); logger.debug(String.format("Parsed and read %s metadata in the header partition.", simpleClassName.substring(0, simpleClassName.length() - 2))); return interchangeObjectBO; } catch(NoSuchMethodException|IllegalAccessException|InstantiationException|InvocationTargetException e){ throw new IOException(String.format("No matching constructor for class %s", clazz.getSimpleName())); } } /** * A factory method to reflectively construct InterchangeObject types by classname * @return the constructed InterchangeObject */ private InterchangeObject constructInterchangeObject(Class clazz, InterchangeObject.InterchangeObjectBO interchangeObjectBO, Node node) throws IOException{ try { Constructor<?> constructor = clazz.getConstructor(interchangeObjectBO.getClass()); InterchangeObject interchangeObject = (InterchangeObject)constructor.newInstance(interchangeObjectBO); logger.debug(String.format("Constructing the object model for %s metadata in the header partition.", interchangeObject.getClass().getSimpleName())); return interchangeObject; } catch(NoSuchMethodException|IllegalAccessException|InstantiationException|InvocationTargetException e){ throw new IOException(String.format("No matching constructor for class %s", clazz.getSimpleName())); } } /** * A helper method to cache an InterchangeObject */ private void cacheInterchangeObject(InterchangeObject interchangeObject){ List<InterchangeObject> list = this.interchangeObjectsMap.get(interchangeObject.getClass().getSimpleName()); if(list == null){ list = new ArrayList<InterchangeObject>(); this.interchangeObjectsMap.put(interchangeObject.getClass().getSimpleName(), list); } list.add(interchangeObject); } /** * Gets the Preface object corresponding to this HeaderPartition object * @return the Preface object in this HeaderPartition */ @Nullable public Preface getPreface() { List<InterchangeObject> list = this.interchangeObjectsMap.get(Preface.class.getSimpleName()); Preface preface = null; if(list != null) { preface = (Preface) list.get(0); } return preface; } /** * Gets the PrimerPack object corresponding to this HeaderPartition object * @return the PrimerPack object in this HeaderPartition */ @Nullable public PrimerPack getPrimerPack() { return this.primerPack; } /** * Gets all of the ContentStorage objects corresponding to this HeaderPartition object * @return list of ContentStorage objects in this HeaderPartition */ public List<InterchangeObject> getContentStorageList() { return this.getInterchangeObjects(ContentStorage.class); } /** * Gets all of the MaterialPackage objects corresponding to this HeaderPartition object * @return list of MaterialPackage objects in this HeaderPartition */ public List<InterchangeObject> getMaterialPackages() { return this.getInterchangeObjects(MaterialPackage.class); } /** * Gets all of the EssenceContainerData objects corresponding to this HeaderPartition object * @return list of EssenceContainerData objects in this HeaderPartition */ public List<InterchangeObject> getEssenceContainerDataList() { return this.getInterchangeObjects(EssenceContainerData.class); } /** * Gets all of the SourcePackage objects corresponding to this HeaderPartition object * @return list of SourcePackages in this HeaderPartition */ public List<InterchangeObject> getSourcePackages() { return this.getInterchangeObjects(SourcePackage.class); } /** * Gets all of the EssenceDescriptor objects corresponding to this HeaderPartition object that are referenced by * the Source Packages in this header partition * @return list of EssenceDescriptor objects referenced by the Source Packages in this HeaderPartition */ public List<InterchangeObject.InterchangeObjectBO> getEssenceDescriptors(){ List<InterchangeObject.InterchangeObjectBO> sourcePackageBOs = this.interchangeObjectBOsMap.get(SourcePackage.SourcePackageBO.class.getSimpleName()); List<InterchangeObject.InterchangeObjectBO> essenceDescriptors = new ArrayList<>(); for(int i=0; i<sourcePackageBOs.size(); i++){ SourcePackage.SourcePackageBO sourcePackageBO = (SourcePackage.SourcePackageBO) sourcePackageBOs.get(i); if(uidToBOs.get(sourcePackageBO.getDescriptorUID()) != null) { essenceDescriptors.add(uidToBOs.get(sourcePackageBO.getDescriptorUID())); } } return essenceDescriptors; } /** * Gets all of the SubDescriptor objects corresponding to this HeaderPartition object that are referenced by all * the source packages in this header partition * @return list of SubDescriptor objects referenced by the Source Packages in this HeaderPartition */ public List<InterchangeObject.InterchangeObjectBO> getSubDescriptors(){ List<InterchangeObject.InterchangeObjectBO> sourcePackageBOs = this.interchangeObjectBOsMap.get(SourcePackage.SourcePackageBO.class.getSimpleName()); List<InterchangeObject.InterchangeObjectBO>subDescriptors = new ArrayList<>(); for(int i=0; i<sourcePackageBOs.size(); i++){ SourcePackage.SourcePackageBO sourcePackageBO = (SourcePackage.SourcePackageBO) sourcePackageBOs.get(i); GenericDescriptor.GenericDescriptorBO genericDescriptorBO = (GenericDescriptor.GenericDescriptorBO)uidToBOs.get(sourcePackageBO.getDescriptorUID()); CompoundDataTypes.MXFCollections.MXFCollection<InterchangeObject.InterchangeObjectBO.StrongRef> strongRefsCollection = genericDescriptorBO.getSubdescriptors(); if(strongRefsCollection != null) { List<InterchangeObject.InterchangeObjectBO.StrongRef> strongRefs = strongRefsCollection.getEntries(); for (InterchangeObject.InterchangeObjectBO.StrongRef strongRef : strongRefs) { if(uidToBOs.get(strongRef.getInstanceUID()) != null) { subDescriptors.add(uidToBOs.get(strongRef.getInstanceUID())); } } } } return subDescriptors; } /** * Gets the SubDescriptor objects corresponding to this HeaderPartition object that are referred by the specified * EssenceDescriptor * @param essenceDescriptor the essence descriptor whose referred subdescriptors are requested * @return list of SubDescriptor objects referenced by the Essence Descriptors in this HeaderPartition */ public List<InterchangeObject.InterchangeObjectBO> getSubDescriptors(InterchangeObject.InterchangeObjectBO essenceDescriptor){ GenericDescriptor.GenericDescriptorBO genericDescriptorBO = (GenericDescriptor.GenericDescriptorBO)essenceDescriptor; return this.getSubDescriptors(genericDescriptorBO.getSubdescriptors()); } /** * Gets the SubDescriptors in this HeaderPartition object that correspond to the specified StrongRefCollection * @param strongRefCollection collection strong references corresponding to the SubDescriptors * @return list of SubDescriptors corresponding to the collection of strong references passed in */ List<InterchangeObject.InterchangeObjectBO> getSubDescriptors(CompoundDataTypes.MXFCollections.MXFCollection<InterchangeObject.InterchangeObjectBO.StrongRef> strongRefCollection){ List<InterchangeObject.InterchangeObjectBO>subDescriptors = new ArrayList<>(); if(strongRefCollection != null) { /*There might be essences that have no SubDescriptors*/ List<InterchangeObject.InterchangeObjectBO.StrongRef> strongRefList = strongRefCollection.getEntries(); for (InterchangeObject.InterchangeObjectBO.StrongRef strongRef : strongRefList) { if(uidToBOs.get(strongRef.getInstanceUID()) != null) { subDescriptors.add(uidToBOs.get(strongRef.getInstanceUID())); } } } return subDescriptors; } /** * Returns the largest duration of all the TimelineTracks within the first (in parsing order) Material Package * associated with this HeaderPartition object * @return the largest duration of all the Timeline tracks within the first Material Package associated with this Header partition */ public BigInteger getEssenceDuration(){ MaterialPackage materialPackage = (MaterialPackage)this.getMaterialPackages().get(0); Long maxDuration = 0L; for (TimelineTrack timelineTrack : materialPackage.getTimelineTracks()) { Long duration = 0L; List<MXFUID> uids = timelineTrack.getSequence().getStructuralComponentInstanceUIDs(); List<InterchangeObject.InterchangeObjectBO> structuralComponentBOs = new ArrayList<>(); for(MXFUID uid : uids){ if(this.uidToBOs.get(uid) != null){ structuralComponentBOs.add(this.uidToBOs.get(uid)); } } for(InterchangeObject.InterchangeObjectBO interchangeObjectBO : structuralComponentBOs){ StructuralComponent.StructuralComponentBO structuralComponentBO = (StructuralComponent.StructuralComponentBO) interchangeObjectBO; duration += structuralComponentBO.getDuration(); } if(duration > maxDuration){ maxDuration = duration; } } return BigInteger.valueOf(maxDuration); } /** * A method that returns the spoken language within this essence provided it is an Audio Essence * @return string representing a spoken language as defined in RFC-5646, null if the spoken language tag is missing * @throws IOException - any I/O related error is exposed through an IOException */ @Nullable public String getAudioEssenceSpokenLanguage() throws IOException { String rfc5646SpokenLanguage = null; if(this.hasWaveAudioEssenceDescriptor()){ List<InterchangeObject> soundfieldGroupLabelSubDescriptors = this.getSoundFieldGroupLabelSubDescriptors(); for (InterchangeObject subDescriptor : soundfieldGroupLabelSubDescriptors) { SoundFieldGroupLabelSubDescriptor soundFieldGroupLabelSubDescriptor = (SoundFieldGroupLabelSubDescriptor) subDescriptor; if (rfc5646SpokenLanguage == null) { rfc5646SpokenLanguage = soundFieldGroupLabelSubDescriptor.getRFC5646SpokenLanguage(); } else if (!rfc5646SpokenLanguage.equals(soundFieldGroupLabelSubDescriptor.getRFC5646SpokenLanguage())) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Language Codes (%s, %s) do not match across the SoundFieldGroupLabelSubDescriptors", rfc5646SpokenLanguage, soundFieldGroupLabelSubDescriptor.getRFC5646SpokenLanguage())); } } /** * According to IMF Core Constraints st2067-2:2013 Section 5.3.6.5 the RFC5646 Spoken Language Tag in AudioChannelLabelSubDescriptor shall be ignored. * However leaving this code commented out to serve as a sample in case we want to enable it in the future and check that this language tag matches * what is present in the SoundFieldGroupLabelSubDescriptors. * / List<InterchangeObject> audioChannelLabelSubDescriptors = this.getAudioChannelLabelSubDescriptors(); for (InterchangeObject subDescriptor : audioChannelLabelSubDescriptors) { AudioChannelLabelSubDescriptor audioChannelLabelSubDescriptor = (AudioChannelLabelSubDescriptor) subDescriptor; if (rfc5646SpokenLanguage == null) { rfc5646SpokenLanguage = audioChannelLabelSubDescriptor.getRFC5646SpokenLanguage(); } else if (!rfc5646SpokenLanguage.equals(audioChannelLabelSubDescriptor.getRFC5646SpokenLanguage())) { throw new MXFException(String.format("Language Codes (%s, %s) do not match across SoundFieldGroupLabelSubdescriptors and AudioChannelLabelSubDescriptors", rfc5646SpokenLanguage, audioChannelLabelSubDescriptor.getRFC5646SpokenLanguage())); } }*/ } else if (this.hasIABEssenceDescriptor()) { List<InterchangeObject> iabSoundFieldLabelSubDescriptors = this.getIABSoundFieldLabelSubDescriptors(); for (InterchangeObject subDescriptor : iabSoundFieldLabelSubDescriptors) { IABSoundfieldLabelSubDescriptor iabSoundfieldLabelSubDescriptor = (IABSoundfieldLabelSubDescriptor) subDescriptor; if (rfc5646SpokenLanguage == null) { rfc5646SpokenLanguage = iabSoundfieldLabelSubDescriptor.getRFC5646SpokenLanguage(); } else if (!rfc5646SpokenLanguage.equals(iabSoundfieldLabelSubDescriptor.getRFC5646SpokenLanguage())) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("Language Codes (%s, %s) do not match across the IABSoundFieldLabelSubDescriptors", rfc5646SpokenLanguage, iabSoundfieldLabelSubDescriptor.getRFC5646SpokenLanguage())); } } } return rfc5646SpokenLanguage; } /** * A method that returns the audio content kind for this Essence * @return AudioContentKind enumeration * @throws IOException - any I/O related error is exposed through an IOException */ public AudioContentKind getAudioContentKind() throws IOException { String audioContentKind = null; if(this.hasWaveAudioEssenceDescriptor()){ List<InterchangeObject> soundfieldGroupLabelSubDescriptors = this.getSoundFieldGroupLabelSubDescriptors(); for (InterchangeObject subDescriptor : soundfieldGroupLabelSubDescriptors) { SoundFieldGroupLabelSubDescriptor soundFieldGroupLabelSubDescriptor = (SoundFieldGroupLabelSubDescriptor) subDescriptor; if (audioContentKind == null) { audioContentKind = soundFieldGroupLabelSubDescriptor.getAudioContentKind(); } else if (!audioContentKind.equals(soundFieldGroupLabelSubDescriptor.getAudioContentKind())) { this.imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_COMPONENT_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, String.format("AudioContentKind (%s, %s) do not match across the SoundFieldGroupLabelSubDescriptors", audioContentKind, soundFieldGroupLabelSubDescriptor.getAudioContentKind())); } } } return AudioContentKind.getAudioContentKindFromSymbol(audioContentKind); } /** * A method that returns the Channel ID to AudioChannelLabelSubDescriptor * @return Channel ID to AudioChannelLabelSubDescriptor mapping */ @Nullable public Map<Long, AudioChannelLabelSubDescriptor> getAudioChannelIDToMCASubDescriptorMap() { List<InterchangeObject> subDescriptors = getAudioChannelLabelSubDescriptors(); Map<Long, AudioChannelLabelSubDescriptor> audioChannelLabelSubDescriptorMap = new HashMap<>(); subDescriptors.stream() .map(e -> AudioChannelLabelSubDescriptor.class.cast(e)) .forEach(e -> audioChannelLabelSubDescriptorMap.put(e.getMCAChannelId() == null? Long.valueOf(1L) : e.getMCAChannelId(), e)); return audioChannelLabelSubDescriptorMap; } /** * Getter for a parsed InterchangeObject by ID * @param structuralMetadataID identifier for the structural metadata set * @return the InterchangeObjectBO corresponding to the class name */ public List<InterchangeObject.InterchangeObjectBO> getStructuralMetadata(StructuralMetadataID structuralMetadataID){ String key = structuralMetadataID.getName() + "BO"; return this.interchangeObjectBOsMap.get(key); } /** * Checks if this HeaderPartition object has a Wave Audio Essence Descriptor * @return true/false depending on whether this HeaderPartition contains a WaveAudioEssenceDescriptor or not */ public boolean hasWaveAudioEssenceDescriptor() { return this.hasInterchangeObject(WaveAudioEssenceDescriptor.class); } /** * Checks if this HeaderPartition object has a IAB Essence Descriptor * @return true/false depending on whether this HeaderPartition contains a IABEssenceDescriptor or not */ public boolean hasIABEssenceDescriptor() { return this.hasInterchangeObject(IABEssenceDescriptor.class); } /** * Checks if this HeaderPartition object has a CDCI Picture Essence Descriptor * @return true/false depending on whether this HeaderPartition contains a CDCIPictureEssenceDescriptor or not */ public boolean hasCDCIPictureEssenceDescriptor() { return this.hasInterchangeObject(CDCIPictureEssenceDescriptor.class); } /** * Checks if this HeaderPartition object has a RGBA Picture Essence Descriptor * @return true/false depending on whether this HeaderPartition contains a RGBAPictureEssenceDescriptor or not */ public boolean hasRGBAPictureEssenceDescriptor() { return this.hasInterchangeObject(RGBAPictureEssenceDescriptor.class); } /** * Checks if this HeaderPartition object has a PHDR Metadata track SubDescriptor * @return true/false depending on whether this HeaderPartition contains a PHDRMetaDataTrackSubDescriptor or not */ public boolean hasPHDRMetaDataTrackSubDescriptor() { return this.hasInterchangeObject(PHDRMetaDataTrackSubDescriptor.class); } /** * Gets all the wave audio essence descriptors associated with this HeaderPartition object * @return list of all the WaveAudioEssenceDescriptors in this header partition */ public List<InterchangeObject> getWaveAudioEssenceDescriptors() { return this.getInterchangeObjects(WaveAudioEssenceDescriptor.class); } /** * Checks if this HeaderPartition object has any audio channel label sub descriptors * @return true/false depending on whether this HeaderPartition contains an AudioChannelLabelSubDescriptor or not */ public boolean hasAudioChannelLabelSubDescriptors() { return this.hasInterchangeObject(AudioChannelLabelSubDescriptor.class); } /** * Gets all the audio channel label sub descriptors associated with this HeaderPartition object * @return list of audio channel label sub descriptors contained in this header partition */ public List<InterchangeObject> getAudioChannelLabelSubDescriptors() { if(this.hasWaveAudioEssenceDescriptor()) { return this.getInterchangeObjects(AudioChannelLabelSubDescriptor.class); } else{ return new ArrayList<InterchangeObject>(); } } /** * Checks if this HeaderPartition object has any sound field group label sub descriptors * @return true/false depending on whether this HeaderPartition contains a SoundFieldGroupLabelSubDescriptor or not */ public boolean hasSoundFieldGroupLabelSubDescriptor() { return this.hasInterchangeObject(SoundFieldGroupLabelSubDescriptor.class); } /** * Gets all the sound field group label sub descriptors associated with this HeaderPartition object * @return list of sound field group label sub descriptors contained in this header partition */ public List<InterchangeObject> getSoundFieldGroupLabelSubDescriptors() { return this.getInterchangeObjects(SoundFieldGroupLabelSubDescriptor.class); } /** * Gets all the IAB Soundfield Label SubDescriptors associated with this HeaderPartition object * @return list of IAB Soundfield Label SubDescriptor contained in this header partition */ public List<InterchangeObject> getIABSoundFieldLabelSubDescriptors() { return this.getInterchangeObjects(IABSoundfieldLabelSubDescriptor.class); } /** * Gets the timeline track associated with this HeaderPartition object corresponding to the specified UID. Returns * null if none is found * @param MXFUID corresponding to the Timeline Track * @return null if this header partition does not contain a timeline track, else a timeline track object */ public @Nullable TimelineTrack getTimelineTrack(MXFUID MXFUID) { Object object = this.uidToMetadataSets.get(MXFUID); TimelineTrack timelineTrack = null; if (object instanceof TimelineTrack) { timelineTrack = (TimelineTrack)object; } return timelineTrack; } /** * Gets the Sequence object associated with this HeaderPartition object corresponding to the specified UID. Returns * null if none is found * @param MXFUID corresponding to the Sequence * @return null if this header partition does not contain a sequence, else a sequence object */ public @Nullable Sequence getSequence(MXFUID MXFUID) { Object object = this.uidToMetadataSets.get(MXFUID); Sequence sequence = null; if (object instanceof Sequence) { sequence = (Sequence)object; } return sequence; } /** * Gets the SourceClip object associated with this HeaderPartition object corresponding to the specified UID. Returns * null if none is found * @param MXFUID corresponding to the Source Clip * @return null if this header partition does not contain a source clip, else a source clip object */ public @Nullable SourceClip getSourceClip(MXFUID MXFUID) { Object object = this.uidToMetadataSets.get(MXFUID); SourceClip sourceClip = null; if (object instanceof SourceClip) { sourceClip = (SourceClip)object; } return sourceClip; } /** * Gets the MaterialPackage object associated with this HeaderPartition object corresponding to the specified UID. Returns * null if none is found * @param MXFUID corresponding to the Material Package * @return null if this header partition does not contain a material package, else a material package object */ public @Nullable MaterialPackage getMaterialPackage(MXFUID MXFUID) { Object object = this.uidToMetadataSets.get(MXFUID); MaterialPackage materialPackage = null; if (object instanceof MaterialPackage) { materialPackage = (MaterialPackage)object; } return materialPackage; } /** * Gets the SourcePackage object associated with this HeaderPartition object corresponding to the specified UID. Returns * null if none is found * @param MXFUID corresponding to the Source Package * @return null if this header partition does not contain a source package, else a source package object */ public @Nullable SourcePackage getSourcePackage(MXFUID MXFUID) { Object object = this.uidToMetadataSets.get(MXFUID); SourcePackage sourcePackage = null; if (object instanceof SourcePackage) { sourcePackage = (SourcePackage)object; } return sourcePackage; } /** * Gets the EssenceContainerData object associated with this HeaderPartition object corresponding to the specified UID. Returns * null if none is found * @param MXFUID corresponding to the EssenceContainerData * @return null if this header partition does not contain an EssenceContainerData object, else a EssenceContainerData object */ public @Nullable EssenceContainerData getEssenceContainerData(MXFUID MXFUID) { Object object = this.uidToMetadataSets.get(MXFUID); EssenceContainerData essenceContainerData = null; if (object instanceof EssenceContainerData) { essenceContainerData = (EssenceContainerData)object; } return essenceContainerData; } /** * Gets the partition pack corresponding to this HeaderPartition * @return the partition pack object corresponding to this HeaderPartition */ public PartitionPack getPartitionPack() { return this.partitionPack; } /** * A method to verify the presence of an InterchangeObject * @boolean */ private boolean hasInterchangeObject(Class clazz){ String simpleName = clazz.getSimpleName(); return (this.interchangeObjectsMap.containsKey(simpleName) && (this.interchangeObjectsMap.get(simpleName) != null && this.interchangeObjectsMap.get(simpleName).size() > 0)); } private List<InterchangeObject> getInterchangeObjects(Class clazz){ String simpleName = clazz.getSimpleName(); if(this.interchangeObjectsMap.get(simpleName) == null){ return Collections.unmodifiableList(new ArrayList<InterchangeObject>()); } else { return Collections.unmodifiableList(this.interchangeObjectsMap.get(simpleName)); } } /** * A method to verify the presence of an InterchangeObjectBO * @boolean */ private boolean hasInterchangeObjectBO(Class clazz){ String simpleName = clazz.getSimpleName(); return (this.interchangeObjectBOsMap.containsKey(simpleName) && (this.interchangeObjectBOsMap.get(simpleName) != null && this.interchangeObjectBOsMap.get(simpleName).size() > 0)); } private List<InterchangeObject.InterchangeObjectBO> getInterchangeObjectBOs(Class clazz){ String simpleName = clazz.getSimpleName(); if(this.interchangeObjectBOsMap.get(simpleName) == null){ return Collections.unmodifiableList(new ArrayList<InterchangeObject.InterchangeObjectBO>()); } else { return Collections.unmodifiableList(this.interchangeObjectBOsMap.get(simpleName)); } } /** * A method that returns the coding equation for underlying image essence * @return Enum representing the coding equation */ public Colorimetry.CodingEquation getImageCodingEquation() { Colorimetry.CodingEquation codingEquation = Colorimetry.CodingEquation.Unknown; Class clazz = RGBAPictureEssenceDescriptor.RGBAPictureEssenceDescriptorBO.class; if(hasCDCIPictureEssenceDescriptor()) { clazz = CDCIPictureEssenceDescriptor.CDCIPictureEssenceDescriptorBO.class; } List<InterchangeObject.InterchangeObjectBO> interchangeObjectBOList = this.getInterchangeObjectBOs(clazz); if(interchangeObjectBOList.size() >0) { GenericPictureEssenceDescriptor.GenericPictureEssenceDescriptorBO genericPictureEssenceDescriptorBO = GenericPictureEssenceDescriptor.GenericPictureEssenceDescriptorBO.class.cast(interchangeObjectBOList.get(0)); codingEquation = Colorimetry.CodingEquation.valueOf(genericPictureEssenceDescriptorBO.getCodingEquationsUL()); } return codingEquation; } /** * A method that returns the transfer characteristic for underlying image essence * @return Enum representing the transfer characteristic */ public Colorimetry.TransferCharacteristic getImageTransferCharacteristic() { Colorimetry.TransferCharacteristic transferCharacteristic = Colorimetry.TransferCharacteristic.Unknown; Class clazz = RGBAPictureEssenceDescriptor.RGBAPictureEssenceDescriptorBO.class; if(hasCDCIPictureEssenceDescriptor()) { clazz = CDCIPictureEssenceDescriptor.CDCIPictureEssenceDescriptorBO.class; } List<InterchangeObject.InterchangeObjectBO> interchangeObjectBOList = this.getInterchangeObjectBOs(clazz); if(interchangeObjectBOList.size() >0) { GenericPictureEssenceDescriptor.GenericPictureEssenceDescriptorBO genericPictureEssenceDescriptorBO = GenericPictureEssenceDescriptor.GenericPictureEssenceDescriptorBO.class.cast(interchangeObjectBOList.get(0)); transferCharacteristic = Colorimetry.TransferCharacteristic.valueOf(genericPictureEssenceDescriptorBO.getTransferCharacteristicUL()); } return transferCharacteristic; } /** * A method that returns the color primaries for underlying image essence * @return Enum representing the color primaries */ public Colorimetry.ColorPrimaries getImageColorPrimaries() { Colorimetry.ColorPrimaries colorPrimaries = Colorimetry.ColorPrimaries.Unknown; Class clazz = RGBAPictureEssenceDescriptor.RGBAPictureEssenceDescriptorBO.class; if(hasCDCIPictureEssenceDescriptor()) { clazz = CDCIPictureEssenceDescriptor.CDCIPictureEssenceDescriptorBO.class; } List<InterchangeObject.InterchangeObjectBO> interchangeObjectBOList = this.getInterchangeObjectBOs(clazz); if(interchangeObjectBOList.size() >0) { GenericPictureEssenceDescriptor.GenericPictureEssenceDescriptorBO genericPictureEssenceDescriptorBO = GenericPictureEssenceDescriptor.GenericPictureEssenceDescriptorBO.class.cast(interchangeObjectBOList.get(0)); colorPrimaries = Colorimetry.ColorPrimaries.valueOf(genericPictureEssenceDescriptorBO.getColorPrimariesUL()); } return colorPrimaries; } /** * A method that returns the pixel bit depth of the underlying image essence * @return Integer representing the pixel bit depth */ public Integer getImagePixelBitDepth() { Integer pixelBitDepth = 0; if(hasCDCIPictureEssenceDescriptor()) { CDCIPictureEssenceDescriptor.CDCIPictureEssenceDescriptorBO cdciPictureEssenceDescriptorBO = CDCIPictureEssenceDescriptor.CDCIPictureEssenceDescriptorBO.class.cast(this.getInterchangeObjectBOs (CDCIPictureEssenceDescriptor.CDCIPictureEssenceDescriptorBO.class).get(0)); pixelBitDepth = Colorimetry.Quantization.componentRangeToBitDepth(cdciPictureEssenceDescriptorBO.getBlackRefLevel(), cdciPictureEssenceDescriptorBO.getWhiteRefLevel()); } else if(hasRGBAPictureEssenceDescriptor()) { RGBAPictureEssenceDescriptor.RGBAPictureEssenceDescriptorBO rgbaPictureEssenceDescriptorBO = RGBAPictureEssenceDescriptor.RGBAPictureEssenceDescriptorBO.class.cast(this .getInterchangeObjectBOs (RGBAPictureEssenceDescriptor.RGBAPictureEssenceDescriptorBO.class).get(0)); pixelBitDepth = Colorimetry.Quantization.componentRangeToBitDepth(rgbaPictureEssenceDescriptorBO.getComponentMinRef(), rgbaPictureEssenceDescriptorBO.getComponentMaxRef()); } return pixelBitDepth; } /** * A method that returns the color primaries for underlying image essence * @return Enum representing the quantization type */ public Colorimetry.Quantization getImageQuantization() { Colorimetry.Quantization quantization = Colorimetry.Quantization.Unknown; Integer pixelBitDepth = getImagePixelBitDepth(); Long signalMin = null; Long signalMax = null; if(hasCDCIPictureEssenceDescriptor()) { CDCIPictureEssenceDescriptor.CDCIPictureEssenceDescriptorBO cdciPictureEssenceDescriptorBO = CDCIPictureEssenceDescriptor.CDCIPictureEssenceDescriptorBO.class.cast(this.getInterchangeObjectBOs (CDCIPictureEssenceDescriptor.CDCIPictureEssenceDescriptorBO.class).get(0)); signalMin = cdciPictureEssenceDescriptorBO.getBlackRefLevel(); signalMax = cdciPictureEssenceDescriptorBO.getWhiteRefLevel(); } else if(hasRGBAPictureEssenceDescriptor()) { RGBAPictureEssenceDescriptor.RGBAPictureEssenceDescriptorBO rgbaPictureEssenceDescriptorBO = RGBAPictureEssenceDescriptor.RGBAPictureEssenceDescriptorBO.class.cast(this .getInterchangeObjectBOs (RGBAPictureEssenceDescriptor.RGBAPictureEssenceDescriptorBO.class).get(0)); signalMin = rgbaPictureEssenceDescriptorBO.getComponentMinRef(); signalMax = rgbaPictureEssenceDescriptorBO.getComponentMaxRef(); } if(pixelBitDepth != 0 && signalMax != null && signalMin != null) { quantization = Colorimetry.Quantization.valueOf(pixelBitDepth, signalMin, signalMax); } return quantization; } /** * A method that returns the color model for underlying image essence * @return Enum representing the color model */ public Colorimetry.ColorModel getImageColorModel() { if(hasCDCIPictureEssenceDescriptor()) { return Colorimetry.ColorModel.YUV; } else if(hasRGBAPictureEssenceDescriptor()) { return Colorimetry.ColorModel.RGB; } return Colorimetry.ColorModel.Unknown; } /** * A method that returns the chroma sampling for underlying image essence * @return Enum representing the chroma sampling */ public Colorimetry.Sampling getImageSampling() { if (hasRGBAPictureEssenceDescriptor()) { return Colorimetry.Sampling.Sampling444; } else if (hasCDCIPictureEssenceDescriptor()) { Colorimetry.Sampling sampling = Colorimetry.Sampling.Unknown; CDCIPictureEssenceDescriptor.CDCIPictureEssenceDescriptorBO cdciPictureEssenceDescriptorBO = CDCIPictureEssenceDescriptor.CDCIPictureEssenceDescriptorBO.class.cast(this.getInterchangeObjectBOs (CDCIPictureEssenceDescriptor.CDCIPictureEssenceDescriptorBO.class).get(0)); Long horizontalSubSampling = cdciPictureEssenceDescriptorBO.getHorizontal_subsampling(); Long verticalSubSampling = cdciPictureEssenceDescriptorBO.getVertical_subsampling(); if( horizontalSubSampling != null && verticalSubSampling != null) { sampling = Colorimetry.Sampling.valueOf(horizontalSubSampling.intValue(), verticalSubSampling.intValue()); } return sampling; } return Colorimetry.Sampling.Unknown; } /* L ← Empty list that will contain the sorted nodes while there are unmarked nodes do select an unmarked node n visit(n) function visit(node n) if n has a temporary mark then stop (not a DAG) if n is not marked (i.e. has not been visited yet) then mark n temporarily for each node m with an edge from n to m do visit(m) mark n permanently add n to head of L */ private static List<Node> resolve(List<Node> adjacencyList) { List<Node> sortedList = new LinkedList<>(); Node node = getUnmarkedNode(adjacencyList); while(node != null) { visit(node, sortedList); node = getUnmarkedNode(adjacencyList); } return sortedList; } private static void visit(Node node, List<Node> sortedList) { if (node.mark.equals(Mark.TEMPORARY)) { throw new MXFException("Cycle detected"); } else if (node.mark.equals(Mark.NONE)) { node.mark = Mark.TEMPORARY; for (Node neighbor : node.depends) { visit(neighbor, sortedList); } node.mark = Mark.PERMANENT; sortedList.add(node); } } private static Node getUnmarkedNode(List<Node> adjacencyList) { Node unmarkedNode = null; for (Node node : adjacencyList) { if (node.mark.equals(Mark.NONE)) { unmarkedNode = node; break; } } return unmarkedNode; } private static class Node { private final MXFUID uid; private final List<Node> depends; private Mark mark; private Node(MXFUID uid) { this.uid = uid; this.mark = Mark.NONE; this.depends = new LinkedList<>(); } } private static enum Mark { /** * The NONE. */ NONE, /** * The TEMPORARY. */ TEMPORARY, /** * The PERMANENT. */ PERMANENT } /** * A method that retrieves all the EssenceTypes present in the MXF file * @return a list of all essence types present in the MXF file */ public List<EssenceTypeEnum> getEssenceTypes() { List<EssenceTypeEnum> essenceTypes = new ArrayList<>(); for(InterchangeObject.InterchangeObjectBO interchangeObjectBO : this.getEssenceDescriptors()){ if(interchangeObjectBO.getClass().getEnclosingClass().equals(WaveAudioEssenceDescriptor.class)){ essenceTypes.add(EssenceTypeEnum.MainAudioEssence); } if(interchangeObjectBO.getClass().getEnclosingClass().equals(IABEssenceDescriptor.class)){ essenceTypes.add(EssenceTypeEnum.IABEssence); } else if(interchangeObjectBO.getClass().getEnclosingClass().equals(CDCIPictureEssenceDescriptor.class)){ essenceTypes.add(EssenceTypeEnum.MainImageEssence); } else if(interchangeObjectBO.getClass().getEnclosingClass().equals(RGBAPictureEssenceDescriptor.class)){ essenceTypes.add(EssenceTypeEnum.MainImageEssence); } else if(interchangeObjectBO.getClass().getEnclosingClass().equals(TimedTextDescriptor.class)){ essenceTypes.add(EssenceTypeEnum.SubtitlesEssence); } } if (essenceTypes.size() == 0){ List<EssenceTypeEnum> essenceTypeList = new ArrayList<>(); essenceTypeList.add(EssenceTypeEnum.UnsupportedEssence); return Collections.unmodifiableList(essenceTypeList); } else{ return Collections.unmodifiableList(essenceTypes); } } /** * An enumeration of all possible essence types that could be contained in a MXF file. */ public enum EssenceTypeEnum { MarkerEssence(Composition.SequenceTypeEnum.MarkerSequence), MainImageEssence(Composition.SequenceTypeEnum.MainImageSequence), MainAudioEssence(Composition.SequenceTypeEnum.MainAudioSequence), SubtitlesEssence(Composition.SequenceTypeEnum.SubtitlesSequence), HearingImpairedCaptionsEssence(Composition.SequenceTypeEnum.HearingImpairedCaptionsSequence), VisuallyImpairedTextEssence(Composition.SequenceTypeEnum.VisuallyImpairedTextSequence), CommentaryEssence(Composition.SequenceTypeEnum.CommentarySequence), KaraokeEssence(Composition.SequenceTypeEnum.CommentarySequence), ForcedNarrativeEssence(Composition.SequenceTypeEnum.ForcedNarrativeSequence), AncillaryDataEssence(Composition.SequenceTypeEnum.AncillaryDataSequence), IABEssence(Composition.SequenceTypeEnum.IABSequence), UnsupportedEssence(Composition.SequenceTypeEnum.UnsupportedSequence); private final Composition.SequenceTypeEnum sequenceType; private final String name; private EssenceTypeEnum(Composition.SequenceTypeEnum sequenceType) { this.sequenceType = sequenceType; this.name = getEssenceTypeString(sequenceType); } private static EssenceTypeEnum getEssenceTypeEnum(String name) { switch (name) { case "MainImageEssence": return MainImageEssence; case "MainAudioEssence": return MainAudioEssence; case "MarkerEssence": return MarkerEssence; case "SubtitlesEssence": return SubtitlesEssence; case "HearingImpairedCaptionsEssence": return HearingImpairedCaptionsEssence; case "VisuallyImpairedTextEssence": return VisuallyImpairedTextEssence; case "CommentaryEssence": return CommentaryEssence; case "KaraokeEssence": return KaraokeEssence; case "ForcedNarrativeEssence": return ForcedNarrativeEssence; case "AncillaryDataEssence": return AncillaryDataEssence; case "IABEssence": return IABEssence; case "UnsupportedEssence": default: return UnsupportedEssence; } } private static String getEssenceTypeString(Composition.SequenceTypeEnum sequenceType) { switch (sequenceType) { case MainImageSequence: return "MainImageEssence"; case MainAudioSequence: return "MainAudioEssence"; case MarkerSequence: return "MarkerEssence"; case SubtitlesSequence: return "SubtitlesEssence"; case HearingImpairedCaptionsSequence: return "HearingImpairedCaptionsEssence"; case VisuallyImpairedTextSequence: return "VisuallyImpairedTextEssence"; case CommentarySequence: return "CommentaryEssence"; case KaraokeSequence: return "KaraokeEssence"; case ForcedNarrativeSequence: return "ForcedNarrativeEssence"; case AncillaryDataSequence: return "AncillaryDataEssence"; case IABSequence: return "IABEssence"; case UnsupportedSequence: default: return "UnsupportedEssence"; } } public String toString(){ return this.name; } } /** * A method that returns a string representation of a HeaderPartition object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== HeaderPartition ======================\n"); sb.append(this.getPartitionPack().toString()); sb.append(this.getPrimerPack().toString()); sb.append(this.getPreface().toString()); /*Set<String> keySet = this.interchangeObjectsMap.keySet(); for(String key : keySet){ if(key.equals(ContentStorage.class.getSimpleName())){ sb.append(this.interchangeObjectsMap.get(ContentStorage.class.getSimpleName()).get(0).toString()); } else if(!key.equals(Preface.class.getSimpleName())) { for(InterchangeObject object : this.interchangeObjectsMap.get(key)){ sb.append(object.toString()); } } }*/ /* According to FindBugs using an iterator over the Map's entrySet() is more efficient than keySet() * (WMI_WRONG_MAP_ITERATOR). * Since with the entrySet we get both the key and the value thereby eliminating the need to use * Map.get(key) to access the value corresponding to a key in the map. */ Set<Map.Entry<String, List<InterchangeObject>>> entrySet = this.interchangeObjectsMap.entrySet(); for(Map.Entry<String, List<InterchangeObject>> entry : entrySet){ if(entry.getKey().equals(ContentStorage.class.getSimpleName())){ sb.append(this.interchangeObjectsMap.get(ContentStorage.class.getSimpleName()).get(0).toString()); } else if(!entry.getKey().equals(Preface.class.getSimpleName())){ for(InterchangeObject object : entry.getValue()){ sb.append(object.toString()); } } } return sb.toString(); } /** * A static method to get the Header Partition from a file * @param inputFile source file to get the Header Partition from * @param imfErrorLogger logging object * @return an HeaderPartition object constructed from the file * @throws IOException any I/O related error will be exposed through an IOException */ public static HeaderPartition fromFile(File inputFile, IMFErrorLogger imfErrorLogger) 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); rangeStart = partitionByteOffsets.get(0); rangeEnd = partitionByteOffsets.get(1) - 1; byte[] headerPartitionBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); ByteProvider byteProvider = new ByteArrayDataProvider(headerPartitionBytes); return new HeaderPartition(byteProvider, 0L, headerPartitionBytes.length, imfErrorLogger); } /** * Method to get the stream id (used in GenericStreamPartition) for the descriptive metadata pointed by * a GenericStreamTextBasedSet object, with a given description * @param description text field to match with the description field of the GenericStreamTextBasedSet object * @return the generic stream id of the metadata or -1 if not found */ public long getGenericStreamIdFromGenericStreamTextBaseSetDescription(@Nonnull String description) { long sid = -1; for (SourcePackage sourcePackage: this.getPreface().getContentStorage().getSourcePackageList()) { for (StaticTrack staticTrack: sourcePackage.getStaticTracks()) { for (DescriptiveMarkerSegment segment: staticTrack.getSequence().getDescriptiveMarkerSegments()) { DMFramework dmFramework = segment.getDmFramework(); if (dmFramework instanceof TextBasedDMFramework) { TextBasedObject textBasedObject =((TextBasedDMFramework) dmFramework).getTextBaseObject(); if (textBasedObject instanceof GenericStreamTextBasedSet) { if (description.equals(textBasedObject.getDescription())) { sid = ((GenericStreamTextBasedSet) textBasedObject).getGenericStreamId(); break; } } } } if (sid != -1) break; } if (sid != -1) break; } return sid; } }
5,108
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/RandomIndexPack.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.utils.ByteProvider; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.MXFPropertyPopulator; import com.netflix.imflibrary.KLVPacket; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Object model corresponding to a Random Index Pack defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public final class RandomIndexPack { private static final byte[] KEY = {0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x11, 0x01, 0x00}; private static final Integer RANDOM_INDEX_PACK_LENGTH_FIELD_SIZE = 4;//Size of the RandomIndexPackLengthField per SMPTE-ST0377-1:2011 see Section 12 private final KLVPacket.Header header; private final Map<Long, List<Long>> partitionMap = new LinkedHashMap<Long, List<Long>>(); private final List<Long> allPartitionByteOffsets = new ArrayList<Long>(); @MXFProperty(size=4) private final Long length = null; /** * Instantiates a new Random index pack. * * @param byteProvider the mxf byte provider * @param byteOffset the byte offset corresponding to this RandomIndexPack * @param fullPackLength the full pack length * @throws IOException the iO exception */ public RandomIndexPack(ByteProvider byteProvider, long byteOffset, long fullPackLength) throws IOException { this.header = new KLVPacket.Header(byteProvider, byteOffset); if (!Arrays.equals(this.header.getKey(), RandomIndexPack.KEY)) { throw new MXFException(String.format("Expected random index pack key = %s, found %s", Arrays.asList(RandomIndexPack.KEY), Arrays.asList(this.header.getKey()))); } if((fullPackLength - KLVPacket.KEY_FIELD_SIZE - this.header.getLSize()) != this.header.getVSize()) { throw new MXFException(String.format("fullPackLength = %d is not consistent with length of length field = %d and length of value field = %d", fullPackLength, this.header.getLSize(), this.header.getVSize())); } //Get the bytestream size of a BodySIDByteOffsetPair 2-tuple Integer bodySIDByteOffsetPairSize = 0; Field[] fields = BodySIDByteOffsetPair.class.getDeclaredFields(); for(Field field : fields){ if(field.isAnnotationPresent(MXFProperty.class)){ bodySIDByteOffsetPairSize += field.getAnnotation(MXFProperty.class).size(); } } if (((fullPackLength - KLVPacket.KEY_FIELD_SIZE - this.header.getLSize() - RANDOM_INDEX_PACK_LENGTH_FIELD_SIZE)%bodySIDByteOffsetPairSize) != 0) { throw new MXFException(String.format("Length of BodySIDByteOffsetPairs portion of RandomIndexPack = %d is not a multiple of %d", fullPackLength - KLVPacket.KEY_FIELD_SIZE - this.header.getLSize() - RANDOM_INDEX_PACK_LENGTH_FIELD_SIZE, bodySIDByteOffsetPairSize)); } long numBodySIDByteOffsetPairs = (fullPackLength - KLVPacket.KEY_FIELD_SIZE - this.header.getLSize() - RANDOM_INDEX_PACK_LENGTH_FIELD_SIZE)/bodySIDByteOffsetPairSize; for (long i=0; i < numBodySIDByteOffsetPairs; i++) { BodySIDByteOffsetPair bodySIDByteOffsetPair = new BodySIDByteOffsetPair(byteProvider); List<Long> partitions = partitionMap.get(bodySIDByteOffsetPair.getBodySID()); if (partitions == null) { partitions = new ArrayList<Long>(); partitionMap.put(bodySIDByteOffsetPair.getBodySID(), partitions); } partitions.add(bodySIDByteOffsetPair.getByteOffset()); allPartitionByteOffsets.add(bodySIDByteOffsetPair.getByteOffset()); } MXFPropertyPopulator.populateField(byteProvider, this, "length"); if (this.length != fullPackLength) { throw new MXFException(String.format("Observed length = %d is different from expected length = %d of RandomIndexPack", this.length, fullPackLength)); } } /** * Gets all the partition byte offsets in the MXF file * * @return all the partition byte offsets the order in which they appear in the file */ public List<Long> getAllPartitionByteOffsets() { return Collections.unmodifiableList(allPartitionByteOffsets); } /** * Getter for the length of the RandomIndex Pack * * @return the length */ public Long getLength() { return this.length; } /** * A method that returns a string representation of a RandomIndex Pack object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== RandomIndexPack ======================\n"); sb.append(this.header.toString()); /*for (long sid : partitionMap.keySet()) { sb.append(String.format("SID = %d%n", sid)); long number = 0; for (long byteOffset : partitionMap.get(sid)) { sb.append(String.format("%02d: byteOffset = %013d(0x%011x)%n", number++, byteOffset, byteOffset)); } }*/ /* * According to FindBugs using an iterator over the Map's entrySet() is more efficient than keySet() * (WMI_WRONG_MAP_ITERATOR). * Since with the entrySet we get both the key and the value thereby eliminating the need to use * Map.get(key) to access the value corresponding to a key in the map. */ Set<Map.Entry<Long, List<Long>>> entrySet = this.partitionMap.entrySet(); for(Map.Entry<Long, List<Long>> entry : entrySet){ sb.append(String.format("SID = %d%n", entry.getKey())); long number = 0; for(long byteOffset : entry.getValue()){ sb.append(String.format("%02d: byteOffset = %013d(0x%011x)%n", number++, byteOffset, byteOffset)); } } sb.append(String.format("length = %d%n", this.length)); return sb.toString(); } /** * Object model representing the mapping of the ID of an Essence container segment and its corresponding byte offset */ @SuppressWarnings("PMD.FinalFieldCouldBeStatic") @Immutable public static final class BodySIDByteOffsetPair { @MXFProperty(size=4) private final Long bodySID = null; @MXFProperty(size=8) private final Long byteOffset = null; /** * Instantiates a new Body sID byte offset pair. * * @param byteProvider the mxf byte provider * @throws IOException the iO exception */ BodySIDByteOffsetPair(ByteProvider byteProvider) throws IOException { MXFPropertyPopulator.populateField(byteProvider, this, "bodySID"); MXFPropertyPopulator.populateField(byteProvider, this, "byteOffset"); } private long getBodySID() { return this.bodySID; } private long getByteOffset() { return this.byteOffset; } } }
5,109
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/PrimerPack.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.utils.ByteProvider; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.KLVPacket; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Arrays; /** * Object model corresponding to a Primer Pack defined in st377-1:2011 */ @Immutable public final class PrimerPack { private static final byte[] KEY = {0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x00, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x05, 0x01, 0x00}; private static final byte[] KEY_MASK = { 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1}; private final KLVPacket.Header header; private final LocalTagEntryBatch localTagEntryBatch; /** * Instantiates a new Primer pack. * * @param byteProvider the mxf byte provider * @throws IOException the iO exception */ PrimerPack(ByteProvider byteProvider, long byteOffset) throws IOException { this.header = new KLVPacket.Header(byteProvider, byteOffset); if(!PrimerPack.isValidKey(Arrays.copyOf(this.header.getKey(), this.header.getKey().length))) { throw new MXFException("Found invalid PrimerPack key"); } this.localTagEntryBatch = new LocalTagEntryBatch(byteProvider); } /** * Instantiates a new Primer pack. * * @param byteProvider the mxf byte provider * @param header the mxf klv packet header * @throws IOException - any I/O related error will be exposed through an IOException */ PrimerPack(ByteProvider byteProvider, KLVPacket.Header header) throws IOException { this.header = header; this.localTagEntryBatch = new LocalTagEntryBatch(byteProvider); } /** * Getter for the PrimerPack's MXFKLV Header * * @return the MXFKLV Header */ public KLVPacket.Header getHeader(){ return this.header; } /** * Checks if the key that was passed in corresponds to a Primer Pack * * @param key the key * @return the boolean */ public static boolean isValidKey(byte[] key) { for (int i=0; i< KLVPacket.KEY_FIELD_SIZE; i++) { if((PrimerPack.KEY_MASK[i] != 0) && (PrimerPack.KEY[i] != key[i])) { return false; } } return true; } /** * Getter for the batch of local tag to UL mappings * * @return the local tag entry batch */ public LocalTagEntryBatch getLocalTagEntryBatch() { return this.localTagEntryBatch; } /** * A method that returns a string representation of a Primer Pack object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== PrimerPack ======================\n"); sb.append(this.header.toString()); sb.append(this.localTagEntryBatch.toString()); return sb.toString(); } }
5,110
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/StructuralMetadataID.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; /** * An enumeration of all the types of Structural and Descriptive Metadata as defined in st377-1:2011 */ public enum StructuralMetadataID { /** * */ ContentStorage("ContentStorage"), /** * */ EssenceContainerData("EssenceContainerData"), /** * */ SourceClip("SourceClip"), /** * */ TimecodeComponent("TimecodeComponent"), /** * */ SourcePackage("SourcePackage"), /** * */ MaterialPackage("MaterialPackage"), /** * */ Preface("Preface"), /** * */ Sequence("Sequence"), /** * */ TimelineTrack("TimelineTrack"), /** * */ WaveAudioEssenceDescriptor("WaveAudioEssenceDescriptor"), /** * */ CDCIPictureEssenceDescriptor("CDCIPictureEssenceDescriptor"), /** * */ RGBAPictureEssenceDescriptor("RGBAPictureEssenceDescriptor"), /** * * */ PHDRMetadataTrackSubDescriptor("PHDRMetadataTrackSubDescriptor"), /** * */ AudioChannelLabelSubDescriptor("AudioChannelLabelSubDescriptor"), /** * */ MCALabelSubDescriptor("MCALabelSubDescriptor"); private final String structuralMetadataName; private StructuralMetadataID(String structuralMetadataName){ this.structuralMetadataName = structuralMetadataName; } public final String getName(){ return this.structuralMetadataName; } }
5,111
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/IndexTableSegment.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.utils.ByteProvider; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.MXFPropertyPopulator; import com.netflix.imflibrary.KLVPacket; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Object model corresponding to an IndexTable segment as defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public final class IndexTableSegment { private static final byte[] KEY = {0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x10, 0x01, 0x00}; private static final byte[] KEY_MASK = { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; private static final Map<Integer, String> LOCAL_TAG_TO_ITEM_NAME; static { Map<Integer, String> localTagToItemName = new HashMap<>(); localTagToItemName.put(0x3c0a, "instance_UID"); localTagToItemName.put(0x3f0b, "indexEditRate"); localTagToItemName.put(0x3f0c, "index_start_position"); localTagToItemName.put(0x3f0d, "index_duration"); localTagToItemName.put(0x3f05, "edit_unit_byte_count"); localTagToItemName.put(0x3f06, "index_SID"); localTagToItemName.put(0x3f07, "body_SID"); localTagToItemName.put(0x3f08, "slice_count"); localTagToItemName.put(0x3f0e, "pos_table_count"); localTagToItemName.put(0x3f0f, "ext_start_offset"); localTagToItemName.put(0x3f10, "vbe_byte_count"); LOCAL_TAG_TO_ITEM_NAME = Collections.unmodifiableMap(localTagToItemName); } private final KLVPacket.Header header; @MXFProperty(size=16) private final byte[] instance_UID = null; @MXFProperty(size=0) private final CompoundDataTypes.Rational indexEditRate = null; @MXFProperty(size=8) private final Long index_start_position = null; @MXFProperty(size=8) private final Long index_duration = null; @MXFProperty(size=4) private final Long edit_unit_byte_count = null; @MXFProperty(size=4) private final Long index_SID = null; @MXFProperty(size=4) private final Long body_SID = null; @MXFProperty(size=1) private final Short slice_count = null; @MXFProperty(size=1) private final Short pos_table_count = null; private final IndexEntryArray indexEntryArray; @MXFProperty(size=8) private final Long ext_start_offset = null; @MXFProperty(size=8) private final Long vbe_byte_count = null; /** * Instantiates a new Index table segment. * * @param byteProvider the mxf byte provider * @param header the header * @throws IOException the iO exception */ public IndexTableSegment(ByteProvider byteProvider, KLVPacket.Header header) throws IOException { if (!IndexTableSegment.isValidKey(header.getKey())) { throw new MXFException(String.format("IndexTableSegment key = %s invalid", Arrays.toString(header.getKey()))); } this.header = header; if ((this.header.getKey()[5] != 0x53) && (this.header.getKey()[5] != 0x13)) { throw new MXFException(String.format("Found index table segment with registry designator byte value = 0x%x, only 0x53h or 0x13h are supported presently", this.header.getKey()[5])); } long numBytesToRead = this.header.getVSize(); long numBytesRead = 0; IndexEntryArray indexEntryArray = null; while (numBytesRead < numBytesToRead) { Integer itemTag = MXFPropertyPopulator.getUnsignedShortAsInt(byteProvider.getBytes(2), KLVPacket.BYTE_ORDER); numBytesRead += 2; long itemSize; if (this.header.getKey()[5] == 0x53) { itemSize = MXFPropertyPopulator.getUnsignedShortAsInt(byteProvider.getBytes(2), KLVPacket.BYTE_ORDER); numBytesRead += 2; } else {//(this.header.getKey()[5] == 0x13) KLVPacket.LengthField lengthField = KLVPacket.getLength(byteProvider); itemSize = lengthField.value; numBytesRead += lengthField.sizeOfLengthField; } String itemName = IndexTableSegment.LOCAL_TAG_TO_ITEM_NAME.get(itemTag); if (itemName != null) { int expectedLength = MXFPropertyPopulator.getFieldSizeInBytes(this, itemName); if((expectedLength > 0) && (itemSize != expectedLength)) { throw new MXFException(String.format("Actual length from bitstream = %d is different from expected length = %d", itemSize, expectedLength)); } MXFPropertyPopulator.populateField(byteProvider, this, itemName); numBytesRead += itemSize; } else if (itemTag == 0x3f0a) { indexEntryArray = new IndexEntryArray(byteProvider); numBytesRead += itemSize; } else { byteProvider.skipBytes(itemSize); numBytesRead += itemSize; } } this.indexEntryArray = indexEntryArray; } /** * A method that returns a string representation of an Index table segment object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== IndexTableSegment ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_UID = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_UID[0], this.instance_UID[1], this.instance_UID[2], this.instance_UID[3], this.instance_UID[4], this.instance_UID[5], this.instance_UID[6], this.instance_UID[7], this.instance_UID[8], this.instance_UID[9], this.instance_UID[10], this.instance_UID[11], this.instance_UID[12], this.instance_UID[13], this.instance_UID[14], this.instance_UID[15])); if (this.indexEditRate != null) { sb.append("================== IndexEditRate ======================\n"); sb.append(this.indexEditRate.toString()); } sb.append(String.format("index_start_position = 0x%x%n", this.index_start_position)); sb.append(String.format("index_duration = 0x%x%n", this.index_duration)); sb.append(String.format("edit_unit_byte_count = %d%n", this.edit_unit_byte_count)); sb.append(String.format("index_SID = %d%n", this.index_SID)); sb.append(String.format("body_SID = %d%n", this.body_SID)); sb.append(String.format("slice_count = %d%n", this.slice_count)); sb.append(String.format("pos_table_count = %d%n", this.pos_table_count)); if (this.indexEntryArray != null) { sb.append(this.indexEntryArray.toString()); } sb.append(String.format("ext_start_offset = 0x%x%n", this.ext_start_offset)); sb.append(String.format("vbe_byte_count = %d%n", this.vbe_byte_count)); return sb.toString(); } /** * Getter for the index entries. * * @return a read-only copy of a list of IndexTableSegment.IndexEntryArray.IndexEntry or null when not present */ public List<IndexEntryArray.IndexEntry> getIndexEntries() { if (this.indexEntryArray != null) { return Collections.unmodifiableList(this.indexEntryArray.indexEntries); } else { return null; } } public CompoundDataTypes.Rational getIndexEditRate() { return indexEditRate; } /** * Checks if the key passed in corresponds to a IndexTable segment * * @param key the key * @return the boolean */ public static boolean isValidKey(byte[] key) { for (int i=0; i< KLVPacket.KEY_FIELD_SIZE; i++) { if((IndexTableSegment.KEY_MASK[i] != 0) && (IndexTableSegment.KEY[i] != key[i])) { return false; } } return true; } /** * Object model corresponding to a collection of Index Table entries */ @Immutable public static final class IndexEntryArray { private final CompoundDataTypes.MXFCollections.Header header; private final List<IndexEntry> indexEntries = new ArrayList<>(); /** * Instantiates a new Index entry array. * * @param byteProvider the mxf byte provider * @throws IOException the iO exception */ IndexEntryArray(ByteProvider byteProvider) throws IOException { this.header = new CompoundDataTypes.MXFCollections.Header(byteProvider); for (long i=0; i<header.getNumberOfElements(); i++) { indexEntries.add(new IndexEntry(byteProvider)); byteProvider.skipBytes(this.header.getSizeOfElement() - 11); } } /** * A method that returns a string representation of an IndexEntryArray object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== IndexEntryArray ======================\n"); sb.append(this.header.toString()); for (IndexEntry indexEntry : indexEntries) { sb.append(indexEntry.toString()); } return sb.toString(); } /** * Object model corresponding to an Index table entry */ @Immutable public static final class IndexEntry { @MXFProperty(size=1) private final Byte temporal_offset = null; @MXFProperty(size=1) private final Byte key_frame_offset = null; @MXFProperty(size=1) private final Byte flags = null; @MXFProperty(size=8) private final Long stream_offset = null; /** * Instantiates a new Index entry. * * @param byteProvider the mxf byte provider * @throws IOException the iO exception */ IndexEntry(ByteProvider byteProvider) throws IOException { MXFPropertyPopulator.populateField(byteProvider, this, "temporal_offset"); MXFPropertyPopulator.populateField(byteProvider, this, "key_frame_offset"); MXFPropertyPopulator.populateField(byteProvider, this, "flags"); MXFPropertyPopulator.populateField(byteProvider, this, "stream_offset"); } /** * Gets stream offset. * * @return the stream offset */ public long getStreamOffset() { return this.stream_offset; } /** * A method that returns a string representation of an IndexEntry object * * @return string representing the object */ public String toString() { return String.format("temporal_offset = %d, key_frame_offset = %d, flags = 0x%x, stream_offset = 0x%x%n", this.temporal_offset, this.key_frame_offset, this.flags, this.stream_offset); } } } }
5,112
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/PartitionPack.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.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.st0377.header.UL; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.MXFPropertyPopulator; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Object model corresponding to a PartitionPack defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public final class PartitionPack { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + PartitionPack.class.getSimpleName() + " : "; private static final byte[] KEY = {0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x00, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00}; private static final byte[] KEY_MASK = { 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1}; private static final Long UNKNOWN_BYTE_OFFSET = -1L; private static final byte GENERIC_STREAM_PARTITION_PACK_KEY_PARTITION_STATUS = 0x11; private final KLVPacket.Header header; @MXFProperty(size=2) private final Integer major_version = null; @MXFProperty(size=2) private final Integer minor_version = null; @MXFProperty(size=4) private final Long KAG_size = null; @MXFProperty(size=8) private final Long this_partition = null; @MXFProperty(size=8) private final Long previous_partition = null; @MXFProperty(size=8) private final Long footer_partition = null; @MXFProperty(size=8) private final Long header_byte_count = null; @MXFProperty(size=8) private final Long index_byte_count = null; @MXFProperty(size=4) private final Long index_SID = null; @MXFProperty(size=8) private final Long body_offset = null; @MXFProperty(size=4) private final Long body_SID = null; @MXFProperty(size=16) private final byte[] operational_pattern = null; private final CompoundDataTypes.MXFCollections.MXFCollection<UL> essenceContainerBatch; private final KLVPacket.Header nextHeader; private final PartitionPackType partitionPackType; /** * An enum to represent the PartitionPackTypes which can be extended only by the PartitionPack class */ public static enum PartitionPackType { /* Enum corresponding to the HeaderPartitionPack, based on the KeyValue as defined in SMPTE ST-0377-1:2011 */ HeaderPartitionPack(0x02, "HeaderPartitionPack"), /* Enum corresponding to the BodyPartitionPack, based on the KeyValue as defined in SMPTE ST-0377-1:2011 */ BodyPartitionPack(0x03, "BodyPartitionPack"), /* Enum corresponding to the FooterPartitionPack, based on the KeyValue as defined in SMPTE ST-0377-1:2011 */ FooterPartitionPack(0x04, "FooterPartitionPack"); private final Integer partitionTypeKey; private final String partitionTypeString; //To prevent other objects from constructing new PartitionTypes private PartitionPackType(Integer partitionTypeKey, String partitionTypeString){ this.partitionTypeKey = partitionTypeKey; this.partitionTypeString = partitionTypeString; } /** * Accessor for the PartitionTypeString * @return string representing this partition type * */ public String getPartitionTypeString(){ return this.partitionTypeString; } /** * Accessor for the PartitionTypeKey * @return key corresponding to this Partition Pack */ public Integer getPartitionPackTypeKey(){ return this.partitionTypeKey; } /** * Given a key this method returns the corresponding PartitionPackType * @param partitionTypeKey the key corresponding to this Partition Pack * @return a PartitionPackType corresponding to the PartitionTypeKey that was passed in. * @throws MXFException if an invalid PartitionTypeKey was passed in. */ public static PartitionPackType getPartitionPackTypeKey(Integer partitionTypeKey) throws MXFException{ if(partitionTypeKey.equals(HeaderPartitionPack.getPartitionPackTypeKey())){ return HeaderPartitionPack; } else if(partitionTypeKey.equals(BodyPartitionPack.getPartitionPackTypeKey())){ return BodyPartitionPack; } else if(partitionTypeKey .equals(FooterPartitionPack.getPartitionPackTypeKey())){ return FooterPartitionPack; } else{ throw new MXFException(String.format("Unrecognized partition pack type")); } } } /** * Instantiates a new Partition pack. * * @param byteProvider the mxf byte provider * @throws IOException the iO exception */ public PartitionPack(ByteProvider byteProvider) throws IOException { this(byteProvider, UNKNOWN_BYTE_OFFSET, false); } /** * Getter for the operational pattern that this MXF file complies to * * @return the byte [ ] */ public byte[] getOperationalPattern() { return Arrays.copyOf(this.operational_pattern, this.operational_pattern.length); } /** * Getter for the number of essence container ULs that are referred by this partition pack * @return the number of essence container ULs that are referred by this partition pack */ public int getNumberOfEssenceContainerULs() { return this.essenceContainerBatch.size(); } /** * Instantiates a new Partition pack. * * @param byteProvider the mxf byte provider * @param byteOffset the byteOffset from the HeaderPartition of this partition pack * @param checkForSucceedingKLVFillItem the check for succeeding kLV fill item * @throws IOException - any I/O related error will be exposed through an IOException */ public PartitionPack(ByteProvider byteProvider, Long byteOffset, boolean checkForSucceedingKLVFillItem) throws IOException { this(byteProvider, byteOffset, checkForSucceedingKLVFillItem, null); } /** * Instantiates a new Partition pack. * * @param byteProvider the mxf byte provider * @param byteOffset the byteOffset from the HeaderPartition of this partition pack * @param checkForSucceedingKLVFillItem the check for succeeding kLV fill item * @param imfErrorLogger the imf error logger * @throws IOException - any I/O related error will be exposed through an IOException */ public PartitionPack(ByteProvider byteProvider, Long byteOffset, boolean checkForSucceedingKLVFillItem, @Nullable IMFErrorLogger imfErrorLogger) throws IOException { this.header = new KLVPacket.Header(byteProvider, byteOffset); validateHeaderKey(); this.partitionPackType = PartitionPackType.getPartitionPackTypeKey(this.header.getSetOrPackKindKey()); MXFPropertyPopulator.populateField(byteProvider, this, "major_version"); MXFPropertyPopulator.populateField(byteProvider, this, "minor_version"); MXFPropertyPopulator.populateField(byteProvider, this, "KAG_size"); MXFPropertyPopulator.populateField(byteProvider, this, "this_partition"); if (this.this_partition < 0) { String errorMessage = String.format("Value of this_partition = %d(0x%x) which is outside the supported range 0-0x%x", this.this_partition, this.this_partition, Long.MAX_VALUE); handleError(imfErrorLogger, errorMessage); } MXFPropertyPopulator.populateField(byteProvider, this, "previous_partition"); if (this.previous_partition < 0) { String errorMessage = String.format("Value of previous_partition = %d(0x%x) which is outside the supported range 0-0x%x", this.previous_partition, this.previous_partition, Long.MAX_VALUE); handleError(imfErrorLogger, errorMessage); } MXFPropertyPopulator.populateField(byteProvider, this, "footer_partition"); if (this.footer_partition < 0) { String errorMessage = String.format("Value of footer_partition = %d(0x%x) which is outside the supported range 0-0x%x", this.footer_partition, this.footer_partition, Long.MAX_VALUE); handleError(imfErrorLogger, errorMessage); } MXFPropertyPopulator.populateField(byteProvider, this, "header_byte_count"); if (this.header_byte_count < 0) { String errorMessage = String.format("Value of header_byte_count = %d(0x%x) which is outside the supported range 0-0x%x", this.header_byte_count, this.header_byte_count, Long.MAX_VALUE); handleError(imfErrorLogger, errorMessage); } MXFPropertyPopulator.populateField(byteProvider, this, "index_byte_count"); if (this.index_byte_count < 0) { String errorMessage = String.format("Value of index_byte_count = %d(0x%x) which is outside the supported range 0-0x%x", this.index_byte_count, this.index_byte_count, Long.MAX_VALUE); handleError(imfErrorLogger, errorMessage); } MXFPropertyPopulator.populateField(byteProvider, this, "index_SID"); MXFPropertyPopulator.populateField(byteProvider, this, "body_offset"); if (this.body_offset < 0) { String errorMessage = String.format("Value of body_offset = %d(0x%x) which is outside the supported range 0-0x%x", this.body_offset, this.body_offset, Long.MAX_VALUE); handleError(imfErrorLogger, errorMessage); } MXFPropertyPopulator.populateField(byteProvider, this, "body_SID"); MXFPropertyPopulator.populateField(byteProvider, this, "operational_pattern"); CompoundDataTypes.MXFCollections.Header cHeader = new CompoundDataTypes.MXFCollections.Header(byteProvider); List<UL> cList = new ArrayList<>(); if ((cHeader.getNumberOfElements() != 0) && (cHeader.getSizeOfElement() != KLVPacket.KEY_FIELD_SIZE)) { throw new MXFException(String.format("Element size = %d in EssenceContainerBatch header is different from expected size = %d", cHeader.getSizeOfElement(), KLVPacket.KEY_FIELD_SIZE)); } for (long i=0; i<cHeader.getNumberOfElements(); i++) { cList.add(new UL(byteProvider.getBytes(KLVPacket.KEY_FIELD_SIZE))); } this.essenceContainerBatch = new CompoundDataTypes.MXFCollections.MXFCollection<UL>(cHeader, cList, "EssenceContainerBatch"); if (checkForSucceedingKLVFillItem) { //Offset of the next KLV packet would be the offset of the current KLV packet + KLV size this.nextHeader = new KLVPacket.Header(byteProvider, byteOffset+this.header.getKLSize()+this.header.getVSize()); } else { this.nextHeader = null; } } private void validateHeaderKey() { for (int i=0; i< KLVPacket.KEY_FIELD_SIZE; i++) { if( (PartitionPack.KEY_MASK[i] != 0) && (PartitionPack.KEY[i] != this.header.getKey()[i]) ) { throw new MXFException(String.format("Partition Pack key value = 0x%x at position (zero-indexed) = %d, is different from expected value = 0x%x", this.header.getKey()[i], i, PartitionPack.KEY[i])); } } } private void handleError(IMFErrorLogger imfErrorLogger, String errorMessage) { if (imfErrorLogger == null) { throw new MXFException(errorMessage); } else { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, PartitionPack.ERROR_DESCRIPTION_PREFIX + errorMessage); } } /** * Partition pack type of this pack. * * @return PartitionPackType */ public PartitionPackType getPartitionPackType() { return (this.partitionPackType); } /** * Checks if this is a header partition. * * @return the boolean */ public boolean isHeaderPartition() { return (this.partitionPackType == PartitionPackType.HeaderPartitionPack); } /** * Checks if this is a valid header partition. * * @return the boolean */ public boolean isValidHeaderPartition() { return (isHeaderPartition() && (this.this_partition == 0) && (this.previous_partition == 0) && (this.header_byte_count != 0)); } /** * Checks if this is a body partition. * * @return the boolean */ public boolean isBodyPartition() { return (this.partitionPackType == PartitionPackType.BodyPartitionPack); } /** * Checks of this is a footer partition. * * @return the boolean */ public boolean isFooterPartition() { return (this.partitionPackType == PartitionPackType.FooterPartitionPack); } /** * Checks if this is a valid footer partition. * * @return the boolean */ public boolean isValidFooterPartition() { return ( (this.footer_partition.equals(this.this_partition)) && (this.body_offset == 0) && (this.body_SID == 0)); } /** * Checks if this is a Generic Stream partition. * * @return the boolean */ public boolean isGenericStreamPartition() { return this.isBodyPartition() && (this.header.getKey()[14] == PartitionPack.GENERIC_STREAM_PARTITION_PACK_KEY_PARTITION_STATUS); } /** * Getter for the header byte count that represents the count of bytes used for HeaderMetadata and Primer pack. * * @return the header byte count */ public long getHeaderByteCount() { return this.header_byte_count; } /** * Checks if this partition pack has header metadata. * * @return the boolean */ public boolean hasHeaderMetadata() { return (this.header_byte_count != 0); } /** * Getter for count of bytes used for IndexTable segments. * * @return the index byte count */ public long getIndexByteCount() { return this.index_byte_count; } /** * Getter for the index table segment identifier in this partition. * * @return the index sID */ public long getIndexSID() { return this.index_SID; } /** * Checks if this partition has index table segments. * * @return the boolean */ public boolean hasIndexTableSegments() { return ((this.index_byte_count != 0) && (this.index_SID != 0)); } /** * Getter for identifier of the Essence container segment found in this partition. * * @return the body sID */ public long getBodySID() { return this.body_SID; } /** * Checks if this partition has essence container data. * * @return the boolean */ public boolean hasEssenceContainer() { return (this.body_SID != 0); } /** * Getter for the KLV packet size. * * @return the KLV packet size */ public long getKLVPacketSize() { return KLVPacket.KEY_FIELD_SIZE + this.header.getLSize() + this.header.getVSize(); } /** * Getter for the size of the value field of a KLV packet. * * @return the value size */ public long getVSize() { return this.header.getVSize(); } /** * Getter for the size field of a KLV packet. * * @return the size */ public long getSize() { return this.header.getKLSize() + this.header.getVSize(); } /** * Getter for this partition's byte offset. * * @return the partition byte offset */ public long getPartitionByteOffset() { return this.this_partition; } /** * Getter for this partition's previous_partition byte offset. * * @return the previous_partition byte offset */ public long getPreviousPartitionByteOffset(){ return this.previous_partition; } /** * Gets essence stream segment start stream position. * * @return byte offset of the start of the essence segment, relative to the start of the essence stream * @throws MXFException if the partition does not contain essence */ public long getEssenceStreamSegmentStartStreamPosition() throws MXFException { if (!this.hasEssenceContainer()) { throw new MXFException("This partition does not contain essence data"); } return this.body_offset; } /** * Checks if the next header was read. * * @return the boolean */ public boolean nextHeaderWasRead() { return (this.nextHeader != null); } /** * Checks if the next packet is a KLV fill item. * * @return the boolean */ public boolean nextPacketIsKLVFillItem() { return (this.nextHeaderWasRead() && KLVPacket.isKLVFillItem(Arrays.copyOf(this.nextHeader.getKey(), this.nextHeader.getKey().length))); } /** * Getter for the partition data byte offset. * * @return the partition data byte offset */ public long getPartitionDataByteOffset() { if (this.nextPacketIsKLVFillItem()) { return this.this_partition + this.getSize() + this.nextHeader.getKLSize() + this.nextHeader.getVSize(); } else { return this.this_partition + this.getSize(); } } /** * A method that returns a string representation of a PartitionPack object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== PartitionPack ======================\n"); sb.append(this.header.toString()); sb.append(String.format("major_version = %d%n", this.major_version)); sb.append(String.format("minor_version = %d%n", this.minor_version)); sb.append(String.format("KAG_size = %d%n", this.KAG_size)); sb.append(String.format("this_partition = 0x%x%n", this.this_partition)); sb.append(String.format("previous_partition = 0x%x%n", this.previous_partition)); sb.append(String.format("footer_partition = 0x%x%n", this.footer_partition)); sb.append(String.format("header_byte_count = 0x%x%n", this.header_byte_count)); sb.append(String.format("index_byte_count = 0x%x%n", this.index_byte_count)); sb.append(String.format("index_SID = %d%n", this.index_SID)); sb.append(String.format("body_offset = 0x%x%n", this.body_offset)); sb.append(String.format("body_SID = %d%n", this.body_SID)); sb.append(String.format("operational_pattern = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.operational_pattern[0], this.operational_pattern[1], this.operational_pattern[2], this.operational_pattern[3], this.operational_pattern[4], this.operational_pattern[5], this.operational_pattern[6], this.operational_pattern[7], this.operational_pattern[8], this.operational_pattern[9], this.operational_pattern[10], this.operational_pattern[11], this.operational_pattern[12], this.operational_pattern[13], this.operational_pattern[14], this.operational_pattern[15])); sb.append(this.essenceContainerBatch.toString()); return sb.toString(); } private static enum PartitionKind { /** * The Header. */ Header(0x02), /** * The Body. */ Body(0x03), /** * The Footer. */ Footer(0x04); private final int value; private PartitionKind(int value) { this.value = value; } /** * Gets value. * * @return the value */ public int getValue() { return this.value; } } }
5,113
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/LocalTagEntryBatch.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.utils.ByteProvider; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.MXFPropertyPopulator; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * Object model corresponding to a batch of LocalTags */ @Immutable public final class LocalTagEntryBatch { /** * The constant LOCAL_TAG_ENTRY_SIZE. */ public static final int LOCAL_TAG_ENTRY_SIZE = 18; private final CompoundDataTypes.MXFCollections.Header header; private final Map<Integer, MXFUID> localTagToUID; /** * Instantiates a new Local tag entry batch. * * @param byteProvider the mxf byte provider * @throws IOException the iO exception */ LocalTagEntryBatch(ByteProvider byteProvider) throws IOException { this.header = new CompoundDataTypes.MXFCollections.Header(byteProvider); if (this.header.getSizeOfElement() != LocalTagEntryBatch.LOCAL_TAG_ENTRY_SIZE) { throw new MXFException(String.format("Element size = %d in LocalTagEntryBatch header is different from expected size = %d", this.header.getSizeOfElement(), LocalTagEntryBatch.LOCAL_TAG_ENTRY_SIZE)); } this.localTagToUID = new HashMap<>(); for (long i=0; i<this.header.getNumberOfElements(); i++) { int localTag = MXFPropertyPopulator.getUnsignedShortAsInt(byteProvider.getBytes(2), KLVPacket.BYTE_ORDER); //smpte st 377-1:2011, section 9.2 if (localTag == 0) { throw new MXFException(String.format("localTag = 0x%04x(%d) is not permitted", localTag, localTag)); } //smpte st 377-1:2011, section 9.2 if (localTagToUID.get(localTag) != null) { throw new MXFException(String.format("localTag = 0x%04x(%d) has already been observed", localTag, localTag)); } MXFUID mxfUL = new MXFUID(byteProvider.getBytes(16)); localTagToUID.put(localTag, mxfUL); } } /** * Getter for the unmodifiable local tag to UID map. * * @return the local tag to uID map */ public Map getLocalTagToUIDMap() { return java.util.Collections.unmodifiableMap(localTagToUID); } /** * A method that returns a string representation of a LocalTagEntryBatch object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== LocalTagEntryBatch ======================\n"); sb.append(this.header.toString()); for (Map.Entry<Integer, MXFUID> entry : this.localTagToUID.entrySet()) { int localTag = entry.getKey(); byte[] bytes = entry.getValue().getUID(); sb.append(String.format("localTag = 0x%04x UID = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", localTag, bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15])); } return sb.toString(); } }
5,114
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/SourceClip.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.MXFDataDefinition; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to SourceClip descriptive metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.SingularField", "PMD.UnusedPrivateField"}) public final class SourceClip extends StructuralComponent { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + SourceClip.class.getSimpleName() + " : "; private final SourceClipBO sourceClipBO; private final GenericPackage genericPackage; private final MXFDataDefinition mxfDataDefinition; /** * Instantiates a new SourceClip object * * @param sourceClipBO the parsed SourceClip object * @param genericPackage the generic package referred by this SourceClip object */ public SourceClip(SourceClipBO sourceClipBO, GenericPackage genericPackage) { this.sourceClipBO = sourceClipBO; this.genericPackage = genericPackage; this.mxfDataDefinition = MXFDataDefinition.getDataDefinition(new MXFUID(this.sourceClipBO.data_definition)); } /** * Getter for the instance UID of this SourceClip object * @return the instance UID of this SourceClip object */ public MXFUID getInstanceUID() { return new MXFUID(this.sourceClipBO.instance_uid); } /** * Getter for the ID of the referenced Source Package * @return the ID of the referenced Source Package */ public MXFUID getSourcePackageID() { return new MXFUID(this.sourceClipBO.source_package_id); } /** * Getter for the duration of the sequence in units of Edit Rate * @return the duration of the sequence in units of Edit Rate */ public Long getDuration() { return this.sourceClipBO.duration; } /** * A method that returns a string representation of a SourceClip object * * @return string representing the object */ public String toString() { return this.sourceClipBO.toString(); } /** * Object corresponding to a parsed SourceClip structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class SourceClipBO extends StructuralComponentBO { @MXFProperty(size=8) private final Long start_position = null; @MXFProperty(size=32, depends=true) private final byte[] source_package_id = null; //Package Ref type @MXFProperty(size=4) private final Long source_track_id = null; /** * Instantiates a new parsed SourceClip object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public SourceClipBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, SourceClip.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.source_package_id == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, SourceClip.ERROR_DESCRIPTION_PREFIX + "source_package_id is null"); } if (this.duration == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, SourceClip.ERROR_DESCRIPTION_PREFIX + "duration is null"); } } /** * Getter for the ID of the referenced Source Package * @return the ID of the referenced Source Package */ public MXFUID getSourcePackageID() { return new MXFUID(this.source_package_id); } /** * A method that returns a string representation of a SourceClipBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== SourceClip ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("data_definition = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.data_definition[0], this.data_definition[1], this.data_definition[2], this.data_definition[3], this.data_definition[4], this.data_definition[5], this.data_definition[6], this.data_definition[7], this.data_definition[8], this.data_definition[9], this.data_definition[10], this.data_definition[11], this.data_definition[12], this.data_definition[13], this.data_definition[14], this.data_definition[15])); sb.append(String.format("duration = %d%n", this.duration)); sb.append(String.format("start_position = %d%n", this.start_position)); sb.append(String.format("source_package_id = 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%n", this.source_package_id[0], this.source_package_id[1], this.source_package_id[2], this.source_package_id[3], this.source_package_id[4], this.source_package_id[5], this.source_package_id[6], this.source_package_id[7], this.source_package_id[8], this.source_package_id[9], this.source_package_id[10], this.source_package_id[11], this.source_package_id[12], this.source_package_id[13], this.source_package_id[14], this.source_package_id[15], this.source_package_id[16], this.source_package_id[17], this.source_package_id[18], this.source_package_id[19], this.source_package_id[20], this.source_package_id[21], this.source_package_id[22], this.source_package_id[23], this.source_package_id[24], this.source_package_id[25], this.source_package_id[26], this.source_package_id[27], this.source_package_id[28], this.source_package_id[29], this.source_package_id[30], this.source_package_id[31])); sb.append(String.format("source_track_id = 0x%04x(%d)%n", this.source_track_id, this.source_track_id)); return sb.toString(); } } }
5,115
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/FileDescriptor.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.header; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.st0377.CompoundDataTypes; import java.util.ArrayList; import java.util.List; /** * Object model corresponding to FileDescriptor structural metadata set defined in st377-1:2011 */ public abstract class FileDescriptor extends GenericDescriptor { public static abstract class FileDescriptorBO extends GenericDescriptorBO { @MXFProperty(size = 0) protected final CompoundDataTypes.Rational sample_rate = null; @MXFProperty(size = 16) protected final UL essence_container = null; @MXFProperty(size = 16) protected final UL codec = null; /** * Constructor for a File descriptor ByteObject. * * @param header the MXF KLV header (Key and Length field) */ FileDescriptorBO(final KLVPacket.Header header) { super(header); } /** * Accessor for the SampleRate field * @return returns a list of long integers representing the numerator and denominator of the sample rate in that order */ public List<Long> getSampleRate(){ List<Long> list = new ArrayList<>(); Long numerator = this.sample_rate.getNumerator(); list.add(numerator); Long denominator = this.sample_rate.getDenominator(); list.add(denominator); return list; } /** * Accessor for the Essence Container UL of this FileDescriptor * @return a UL representing the Essence Container */ public UL getEssenceContainerUL(){ return this.essence_container; } /** * Accessor for the Codec UL of this FileDescriptor * @return a UL to identify a codec compatible with this Essence Container. */ public UL getCodecUL(){ return this.codec; } } }
5,116
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/GenericPackage.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.header; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.st0377.CompoundDataTypes; import java.nio.ByteBuffer; import java.util.*; /** * Object model corresponding to GenericPackage structural metadata set defined in st377-1:2011 */ public abstract class GenericPackage extends InterchangeObject { private final GenericPackageBO genericPackageBO; public GenericPackage(GenericPackageBO genericPackageBO) { this.genericPackageBO = genericPackageBO; } /** * Getter for the immutable unique packager identifier which is a basic UMID (see st0330:2011) * @return the immutable unique packager identifier represented as a MXFUid object */ public MXFUID getPackageUID() { return new MXFUID(this.genericPackageBO.package_uid); } /** * Getter for the material number part of the immutable unique package identifier * @return the material number part as a UUID */ public UUID getPackageMaterialNumberasUUID() { long mostSignificantBits = ByteBuffer.wrap(this.genericPackageBO.package_uid, 16, 8).getLong(); long leastSignificantBits = ByteBuffer.wrap(this.genericPackageBO.package_uid, 24, 8).getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public abstract static class GenericPackageBO extends InterchangeObjectBO { private static final byte[] NULL_PACKAGE_UID = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; /** * The Package _ uid. */ @MXFProperty(size=32) protected final byte[] package_uid = null; //PackageID type /** * The Package _ creation _ date. */ @MXFProperty(size=0) protected final CompoundDataTypes.Timestamp package_creation_date = null; /** * The Package _ modified _ date. */ @MXFProperty(size=0) protected final CompoundDataTypes.Timestamp package_modified_date = null; /** * The Tracks. */ @MXFProperty(size=0, depends=true) protected final CompoundDataTypes.MXFCollections.MXFCollection<StrongRef> tracks = null; /** * The Generic track instance uI ds. */ protected final List<MXFUID> genericTrackInstanceUIDs = new ArrayList<>(); /** * Instantiates a new Generic package ByteObject. * * @param header the header */ GenericPackageBO(KLVPacket.Header header) { super(header); } /** * Gets package uID. * * @return the package uID */ public MXFUID getPackageUID() { return new MXFUID(this.package_uid); } /** * Gets null package uID. * * @return the null package uID */ public static MXFUID getNullPackageUID() { return new MXFUID(GenericPackageBO.NULL_PACKAGE_UID); } /** * Gets generic track instance uI ds. * * @return the generic track instance uI ds */ public List<MXFUID> getGenericTrackInstanceUIDs() { return Collections.unmodifiableList(this.genericTrackInstanceUIDs); } } }
5,117
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/MaterialPackage.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * Object model corresponding to MaterialPackage structural metadata set defined in st377-1:2011 */ @Immutable public final class MaterialPackage extends GenericPackage { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + MaterialPackage.class.getSimpleName() + " : "; private final MaterialPackageBO materialPackageBO; private final List<GenericTrack> genericTracks; /** * Instantiates a new MaterialPackage object * * @param materialPackageBO the parsed MaterialPackage object * @param genericTracks the list of generic tracks referred by this MaterialPackage object */ public MaterialPackage(MaterialPackageBO materialPackageBO, List<GenericTrack> genericTracks) { super(materialPackageBO); this.materialPackageBO = materialPackageBO; this.genericTracks = Collections.unmodifiableList(genericTracks); } /** * Getter for a list of GenericTracks referred by this Material Package * @return a list of GenericTracks referred by this Material Package */ public List<GenericTrack> getGenericTracks() { return this.genericTracks; } /** * Getter for the subset of generic tracks that are of type TimelineTrack * @return subset of generic tracks that are of type TimelineTrack */ public List<TimelineTrack> getTimelineTracks() { List<TimelineTrack> timelineTracks = new ArrayList<>(); for (GenericTrack genericTrack : this.genericTracks) { if (genericTrack instanceof TimelineTrack) { timelineTracks.add((TimelineTrack)genericTrack); } } return timelineTracks; } /** * Getter for the instance UID corresponding to this MaterialPackage set in the MXF file * @return the instance UID corresponding to this MaterialPackage set in the MXF file */ public MXFUID getInstanceUID() { return new MXFUID(this.materialPackageBO.instance_uid); } public List<MXFUID> getTrackInstanceUIDs() { List<MXFUID> trackInstanceUIDs = new ArrayList<MXFUID>(); for (InterchangeObjectBO.StrongRef strongRef : this.materialPackageBO.tracks.getEntries()) { trackInstanceUIDs.add(strongRef.getInstanceUID()); } return trackInstanceUIDs; } /** * A method that returns a string representation of a parsed MaterialPackage object * * @return string representing the object */ public String toString() { return this.materialPackageBO.toString(); } /** * Object corresponding to parsed MaterialPackage structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class MaterialPackageBO extends GenericPackageBO { /** * Instantiates a new parsed MaterialPackage object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public MaterialPackageBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, MaterialPackage.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.tracks == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, MaterialPackage.ERROR_DESCRIPTION_PREFIX + "tracks is null"); } else { for (StrongRef strongRef : this.tracks.getEntries()) { this.genericTrackInstanceUIDs.add(strongRef.getInstanceUID()); } } } /** * A method that returns a string representation of a MaterialPackageBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== MaterialPackage ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("package_uid = 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%n", this.package_uid[0], this.package_uid[1], this.package_uid[2], this.package_uid[3], this.package_uid[4], this.package_uid[5], this.package_uid[6], this.package_uid[7], this.package_uid[8], this.package_uid[9], this.package_uid[10], this.package_uid[11], this.package_uid[12], this.package_uid[13], this.package_uid[14], this.package_uid[15], this.package_uid[16], this.package_uid[17], this.package_uid[18], this.package_uid[19], this.package_uid[20], this.package_uid[21], this.package_uid[22], this.package_uid[23], this.package_uid[24], this.package_uid[25], this.package_uid[26], this.package_uid[27], this.package_uid[28], this.package_uid[29], this.package_uid[30], this.package_uid[31])); sb.append("================== PackageCreationDate ======================\n"); sb.append(this.package_creation_date.toString()); sb.append("================== PackageModifiedDate ======================\n"); sb.append(this.package_modified_date.toString()); sb.append(this.tracks.toString()); return sb.toString(); } } }
5,118
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/StaticTrack.java
package com.netflix.imflibrary.st0377.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.utils.ByteProvider; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; public class StaticTrack extends GenericTrack { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + StaticTrack.class.getSimpleName() + " : "; private final StaticTrackBO staticTrackBO; /** * Instantiates a new StaticTrack object * * @param staticTrackBO the parsed StaticTrack object * @param sequence the sequence referred by this StaticTrack object */ public StaticTrack(StaticTrackBO staticTrackBO, Sequence sequence) { super(staticTrackBO, sequence); this.staticTrackBO = staticTrackBO; } /** * Object corresponding to a parsed StaticTrack structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class StaticTrackBO extends GenericTrackBO { /** * Instantiates a new parsed StaticTrack object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public StaticTrackBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header, imfErrorLogger); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); postPopulateCheck(); } /** * A method that returns a string representation of a Timeline Track object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); return sb.toString(); } } }
5,119
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/EssenceContainerData.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to EssenceContainerData structural metadata set defined in st377-1:2011 */ @Immutable public final class EssenceContainerData extends InterchangeObject { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + EssenceContainerData.class.getSimpleName() + " : "; private final EssenceContainerDataBO essenceContainerDataBO; private final GenericPackage genericPackage; /** * Instantiates a new EssenceContainerData object * * @param essenceContainerDataBO the parsed EssenceContainerData object * @param genericPackage the generic package referenced by this EssenceContainerData object */ public EssenceContainerData(EssenceContainerDataBO essenceContainerDataBO, GenericPackage genericPackage) { this.essenceContainerDataBO = essenceContainerDataBO; this.genericPackage = genericPackage; } /** * Getter for the generic package referenced by this EssenceContainerData object * @return returns the generic package referenced by this Essence Container Data object */ public GenericPackage getLinkedPackage() { return this.genericPackage; } /** * Getter for the instance UID corresponding to this EssenceContainerData set in the MXF file * @return returns the instanceUID corresponding to this Essence Container data object */ public MXFUID getInstanceUID() { return new MXFUID(this.essenceContainerDataBO.instance_uid); } /** * Getter for the identifier of the package linked to this EssenceContainerData set * @return returns the identified of the package linked to this Essence Container data */ public MXFUID getLinkedPackageUID() { return new MXFUID(this.essenceContainerDataBO.linked_package_uid); } /** * Getter for the ID of the Index Table linked to this EssenceContainerData set * @return returns the ID of the Index Table linked with this Essence Container data */ public long getIndexSID() { return this.essenceContainerDataBO.index_sid; } /** * Getter for the ID of the Essence Container to which this EssenceContainerData set is linked * @return returns the ID of the essence container liked to this Essence Container data */ public long getBodySID() { return this.essenceContainerDataBO.body_sid; } /** * A method that returns a string representation of an EssenceContainerData object * * @return string representing the object */ public String toString() { return this.essenceContainerDataBO.toString(); } /** * Object corresponding to parsed EssenceContainerData structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class EssenceContainerDataBO extends InterchangeObjectBO { @MXFProperty(size=32, depends=true) private final byte[] linked_package_uid = null; //PackageRef type @MXFProperty(size=4) private final Long index_sid = null; @MXFProperty(size=4) private final Long body_sid = null; /** * Instantiates a new parsed EssenceContainerData object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public EssenceContainerDataBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, EssenceContainerData.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.linked_package_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, EssenceContainerData.ERROR_DESCRIPTION_PREFIX + "linked_package_uid is null"); } } /** * Getter for the identifier of the package to which this EssenceContainerData set is linked * @return returns the identifier of the package linked to this Essence container data */ public MXFUID getLinkedPackageUID() { return new MXFUID(this.linked_package_uid); } /** * A method that returns a string representation of an EssenceContainerDataBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== EssenceContainerData ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("linked_package_uid = 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%n", this.linked_package_uid[0], this.linked_package_uid[1], this.linked_package_uid[2], this.linked_package_uid[3], this.linked_package_uid[4], this.linked_package_uid[5], this.linked_package_uid[6], this.linked_package_uid[7], this.linked_package_uid[8], this.linked_package_uid[9], this.linked_package_uid[10], this.linked_package_uid[11], this.linked_package_uid[12], this.linked_package_uid[13], this.linked_package_uid[14], this.linked_package_uid[15], this.linked_package_uid[16], this.linked_package_uid[17], this.linked_package_uid[18], this.linked_package_uid[19], this.linked_package_uid[20], this.linked_package_uid[21], this.linked_package_uid[22], this.linked_package_uid[23], this.linked_package_uid[24], this.linked_package_uid[25], this.linked_package_uid[26], this.linked_package_uid[27], this.linked_package_uid[28], this.linked_package_uid[29], this.linked_package_uid[30], this.linked_package_uid[31])); sb.append(String.format("index_sid = 0x%x(%d)%n", this.index_sid, this.index_sid)); sb.append(String.format("body_sid = 0x%x(%d)%n", this.body_sid, this.body_sid)); return sb.toString(); } } }
5,120
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/Sequence.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.MXFDataDefinition; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.st0377.CompoundDataTypes; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * Object model corresponding to Sequence descriptive metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.SingularField", "PMD.UnusedPrivateField"}) public final class Sequence extends StructuralComponent { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + Sequence.class.getSimpleName() + " : "; private final SequenceBO sequenceBO; private final List<StructuralComponent> structuralComponents; private final MXFDataDefinition mxfDataDefinition; /** * Instantiates a new Sequence object * * @param sequenceBO the parsed Sequence object * @param structuralComponents the list of structural components referred by this Sequence object */ public Sequence(SequenceBO sequenceBO, List<StructuralComponent> structuralComponents) { this.sequenceBO = sequenceBO; this.structuralComponents = structuralComponents; this.mxfDataDefinition = MXFDataDefinition.getDataDefinition(new MXFUID(this.sequenceBO.data_definition)); } /** * Getter for the instance UID corresponding to this Sequence object * @return the instance UID corresponding to this Sequence object */ public MXFUID getInstanceUID() { return new MXFUID(this.sequenceBO.instance_uid); } /** * Getter for the number of structural components referred by this Sequence object * @return the number of structural components referred by this Sequence object */ public int getNumberOfStructuralComponents() { return this.sequenceBO.structural_components.size(); } /** * Getter for the subset of structural components that are of type SourceClip * * @return the source clips */ public List<SourceClip> getSourceClips() { List<SourceClip> sourceClips = new ArrayList<>(); for (StructuralComponent structuralComponent : this.structuralComponents) { if (structuralComponent instanceof SourceClip) { sourceClips.add((SourceClip)structuralComponent); } } return sourceClips; } /** * Getter for the subset of structural components that are of type SourceClip * * @return the source clips */ public List<DescriptiveMarkerSegment> getDescriptiveMarkerSegments() { List<DescriptiveMarkerSegment> descriptiveMarkerSegments = new ArrayList<>(); for (StructuralComponent structuralComponent : this.structuralComponents) { if (structuralComponent instanceof DescriptiveMarkerSegment) { descriptiveMarkerSegments.add((DescriptiveMarkerSegment)structuralComponent); } } return descriptiveMarkerSegments; } /** * Getter for the instance UID of a SourceClip structural component in the list of structural components referred by this Sequence object * @param index - the index in the list corresponding to the SourceClip structural component * @return the source clips */ public MXFUID getSourceClipUID(int index) { return this.sequenceBO.structural_components.getEntries().get(index).getInstanceUID(); } /** * Getter for the data type of this structural metadata set * @return the data type of this structural metadata set */ public MXFDataDefinition getMxfDataDefinition() { return this.mxfDataDefinition; } /** * Getter for the duration of the Sequence in units of edit rate * @return the duration of the Sequence in units of edit rate */ public Long getDuration() { return this.sequenceBO.duration; } /** * Getter for the list of instance UIDs of structural components referred by this sequence * @return the list of instance UIDs of structural components referred by this sequence */ public List<MXFUID> getStructuralComponentInstanceUIDs(){ return this.sequenceBO.getStructuralComponentInstanceUIDs(); } /** * A method that returns a string representation of a Sequence object * * @return string representing the object */ public String toString() { return this.sequenceBO.toString(); } /** * Object corresponding to a parsed Sequence descriptive metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class SequenceBO extends StructuralComponentBO { @MXFProperty(size=0, depends=true) private final CompoundDataTypes.MXFCollections.MXFCollection<StrongRef> structural_components = null; private final List<MXFUID> structuralComponentInstanceUIDs = new ArrayList<>(); /** * Instantiates a new parsed Sequence object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public SequenceBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, Sequence.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.structural_components == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, Sequence.ERROR_DESCRIPTION_PREFIX + "structural_components is null"); } else { for (StrongRef strongRef : this.structural_components.getEntries()) { structuralComponentInstanceUIDs.add(strongRef.getInstanceUID()); } } if (this.data_definition == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, Sequence.ERROR_DESCRIPTION_PREFIX + "data_definition is null"); } if (this.duration == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, Sequence.ERROR_DESCRIPTION_PREFIX + "duration is null"); } } /** * Getter for an unmodifiable list of instance UIDs of structural components referred by this sequence * @return an unmodifiable list of instance UIDs of structural components referred by this sequence */ public List<MXFUID> getStructuralComponentInstanceUIDs() { return Collections.unmodifiableList(this.structuralComponentInstanceUIDs); } /** * A method that returns a string representation of a SequenceBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== Sequence ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("data_definition = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.data_definition[0], this.data_definition[1], this.data_definition[2], this.data_definition[3], this.data_definition[4], this.data_definition[5], this.data_definition[6], this.data_definition[7], this.data_definition[8], this.data_definition[9], this.data_definition[10], this.data_definition[11], this.data_definition[12], this.data_definition[13], this.data_definition[14], this.data_definition[15])); sb.append(String.format("duration = %d%n", this.duration)); sb.append(this.structural_components.toString()); return sb.toString(); } } }
5,121
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/WaveAudioEssenceDescriptor.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to WaveAudioEssenceDescriptor structural metadata set defined in st382:2007 */ @Immutable public final class WaveAudioEssenceDescriptor extends GenericSoundEssenceDescriptor { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + WaveAudioEssenceDescriptor.class.getSimpleName() + " : "; public WaveAudioEssenceDescriptor(WaveAudioEssenceDescriptorBO waveAudioEssenceDescriptorBO) { this.genericSoundEssenceDescriptorBO = waveAudioEssenceDescriptorBO; } public WaveAudioEssenceDescriptorBO getWaveAudioEssenceDescriptorBO() { return ((WaveAudioEssenceDescriptorBO)this.genericSoundEssenceDescriptorBO); } /** * Getter for the block align of this WaveAudioEssenceDescriptor * * @return block align in the inclusive range [1, Integer.MAX_VALUE] * @throws MXFException when block align is out of range */ public int getBlockAlign() throws MXFException { long value = getWaveAudioEssenceDescriptorBO().block_align; if ((value <=0) || (value > Integer.MAX_VALUE)) { throw new MXFException(String.format("Observed block align = %d, which is not supported at this time", value)); } return (int)value; } /** * Getter for channel assignment UL (can be null) * @return channel assignment UL (can be null) */ public @Nullable MXFUID getChannelAssignmentUL() { if (getWaveAudioEssenceDescriptorBO().channel_assignment != null) { return getWaveAudioEssenceDescriptorBO().channel_assignment.getULAsMXFUid(); } return null; } /** * A method that compares this WaveAudioEssenceDescriptor with the object that was passed in and returns true/false depending on whether the objects * match field for field. * Note: If the object passed in is not an instance of a WaveAudioEssenceDescriptor this method would return * false. * @param other object that this WaveAudioEssenceDescriptor should be compared with * @return boolean indicating the result of comparing this WaveAudioEssenceDescriptor with the object that was passed in */ public boolean equals(Object other) { if(!(other instanceof WaveAudioEssenceDescriptor)) { return false; } WaveAudioEssenceDescriptor otherObject = (WaveAudioEssenceDescriptor)other; return this.genericSoundEssenceDescriptorBO.equals((otherObject.genericSoundEssenceDescriptorBO)); } /** * Getter for the sum of hash codes of AudioSamplingRate, Channel Count, Quantization Bits and Block Align fields * of this WaveAudioEssenceDescriptor * @return the sum of hash codes of AudioSamplingRate, Channel Count, Quantization Bits and Block Align fields of this * WaveAudioEssenceDescriptor */ public int hashCode() { return this.genericSoundEssenceDescriptorBO.hashCode(); } /** * A method that returns a string representation of a WaveAudioEssenceDescriptor object * * @return string representing the object */ public String toString() { return getWaveAudioEssenceDescriptorBO().toString(); } /** * Object corresponding to a parsed WaveAudioEssenceDescriptor structural metadata set defined in st382:2007 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class WaveAudioEssenceDescriptorBO extends GenericSoundEssenceDescriptor.GenericSoundEssenceDescriptorBO { @MXFProperty(size=2) private final Integer block_align = null; @MXFProperty(size=4) private final Long average_bytes_per_second = null; @MXFProperty(size=16) private final UL channel_assignment = null; /** * Instantiates a new parsed WaveAudioEssenceDescriptor object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public WaveAudioEssenceDescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header, imfErrorLogger); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); postPopulateCheck(); if (this.block_align == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, WaveAudioEssenceDescriptor.ERROR_DESCRIPTION_PREFIX + "block_align is null"); } } /** * A method that compares this WaveAudioEssenceDescriptorBO with the object that was passed in and returns true/false depending on whether the objects * match field for field. * Note: If the object passed in is not an instance of a WaveAudioEssenceDescriptorBO this method would return * false. * @param other the object that this parsed WaveAudioEssenceDescriptor should be compared with * @return result of comparing this parsed WaveAudioEssenceDescriptor with the object that was passed in */ public boolean equals(Object other) { if(!(other instanceof WaveAudioEssenceDescriptorBO)) { return false; } boolean genericEqual = super.equals(other); if (!genericEqual) return false; WaveAudioEssenceDescriptorBO otherObject = (WaveAudioEssenceDescriptorBO)other; return !((this.block_align == null) || (!this.block_align.equals(otherObject.block_align))); } /** * Getter for the sum of hash codes of AudioSamplingRate, Channel Count, Quantization Bits and Block Align fields * of this WaveAudioEssenceDescriptor * @return the sum of hash codes of AudioSamplingRate, Channel Count, Quantization Bits and Block Align fields * of this WaveAudioEssenceDescriptor */ public int hashCode() { return super.hashCode() + this.block_align.hashCode(); } /** * A method that returns a string representation of a WaveAudioEssenceDescriptorBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); sb.append(String.format("block_align = %d%n", this.block_align)); sb.append(String.format("average_bytes_per_second = %d%n", this.average_bytes_per_second)); if (this.channel_assignment != null) { sb.append(String.format("channel_assignment = %s%n", this.channel_assignment.toString())); } return sb.toString(); } } }
5,122
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/InterchangeObject.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.header; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.annotations.MXFProperty; import javax.annotation.Nullable; import java.util.Arrays; /** * Object model corresponding to InterchangeObject structural metadata defined in st377-1:2011 */ public abstract class InterchangeObject { @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public abstract static class InterchangeObjectBO { /** * The Header. */ protected final KLVPacket.Header header; /** * The Instance _ uid. */ @MXFProperty(size=16) protected final byte[] instance_uid = null; /** * Instantiates a new Interchange object ByteObject. * * @param header the header */ InterchangeObjectBO(KLVPacket.Header header) { this.header = header; } /** * Gets header. * * @return the header */ public KLVPacket.Header getHeader() { return this.header; } /** * Gets instance uID. * * @return the instance uID */ public @Nullable MXFUID getInstanceUID() { if (this.instance_uid != null) { return new MXFUID(this.instance_uid); } return null; } /** * A logical representation of a Strong Reference */ public static final class StrongRef{ private final byte[] instance_uid; /** * Constructor for a StrongRef object * @param instance_uid that this Strong reference object represents */ public StrongRef(byte[] instance_uid){ this.instance_uid = Arrays.copyOf(instance_uid, instance_uid.length); } /** * Accessor for the underlying instance_uid * @return MXFUId type corresponding to the instance_uid that this Strong reference object represents */ public MXFUID getInstanceUID(){ return new MXFUID(this.instance_uid); } /** * toString() method * @return string representation of the StrongRef object */ public String toString(){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(String.format("0x")); for(byte b : this.instance_uid) { stringBuilder.append(String.format("%02x", b)); } return stringBuilder.toString(); } } } }
5,123
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/GenericDataEssenceDescriptor.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.header; import com.netflix.imflibrary.KLVPacket; /** * Object model corresponding to GenericDataEssenceDescriptor structural metadata set defined in st377-1:2011 */ public abstract class GenericDataEssenceDescriptor extends FileDescriptor { public static abstract class GenericDataEssenceDescriptorBO extends FileDescriptorBO { /** * Constructor for a File descriptor ByteObject. * * @param header the MXF KLV header (Key and Length field) */ GenericDataEssenceDescriptorBO(final KLVPacket.Header header) { super(header); } } }
5,124
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/GenericDescriptor.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.header; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.st0377.CompoundDataTypes; /** * Object model corresponding to GenericDescriptor structural metadata set defined in st377-1:2011 */ public abstract class GenericDescriptor extends InterchangeObject { public abstract static class GenericDescriptorBO extends InterchangeObjectBO { /** * Collection of subdescriptors. */ @MXFProperty(size = 0, depends = true) protected final CompoundDataTypes.MXFCollections.MXFCollection<StrongRef> subdescriptors = null; /** * Instantiates a new Generic descriptor ByteObject. * * @param header the header */ GenericDescriptorBO(final KLVPacket.Header header) { super(header); } /** * Accessor for the SubDescriptors in the EssenceDescriptor * @return list of references to subdescriptors */ public CompoundDataTypes.MXFCollections.MXFCollection<StrongRef> getSubdescriptors(){ return this.subdescriptors; } } }
5,125
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/TimedTextDescriptor.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.utils.ByteProvider; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; /** * Object model corresponding to TimedTextDescriptor structural metadata set defined in st429-5:2009 */ @Immutable public final class TimedTextDescriptor extends GenericDataEssenceDescriptor { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + TimedTextDescriptor.class.getSimpleName() + " : "; private final TimedTextDescriptorBO timedTextDescriptorBO; private final List<TimeTextResourceSubDescriptor> subDescriptorList; /** * Constructor for a TimedTextDescriptor object * @param timedTextDescriptorBO the parsed TimedTextDescriptor object * @param subDescriptorList List containing TimeTextResourceSubDescriptor objects */ public TimedTextDescriptor(TimedTextDescriptorBO timedTextDescriptorBO, List<TimeTextResourceSubDescriptor> subDescriptorList) { this.timedTextDescriptorBO = timedTextDescriptorBO; this.subDescriptorList = Collections.unmodifiableList(subDescriptorList); } /** * Getter for the TimeTextResourceSubDescriptor list * @return a list containing TimeTextResourceSubDescriptors */ public List<TimeTextResourceSubDescriptor> getSubDescriptorList() { return subDescriptorList; } /** * Getter for the UCSEncoding * @return a String representing the ISO/IEC 10646-1encoding of the essence data */ public String getUCSEncoding() { return this.timedTextDescriptorBO.ucs_encoding; } /** * Getter for the NamespaceURI * @return a String representing the URI value which is the XML namespace name of the top-level * XML element in the essence data */ public String getNamespaceURI(){ return this.timedTextDescriptorBO.namespace_uri; } /** * Getter for the Essence Container UL of this FileDescriptor * @return a UL representing the Essence Container */ public UL getEssenceContainerUL(){ return this.timedTextDescriptorBO.getEssenceContainerUL(); } /** * A method that returns a string representation of a TimedTextDescriptor object * * @return string representing the object */ public String toString() { return this.timedTextDescriptorBO.toString(); } /** * Object corresponding to a parsed TimedTextDescriptor structural metadata set defined in st429-5:2009 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class TimedTextDescriptorBO extends FileDescriptorBO { @MXFProperty(size=16) private final UL resource_id = null; @MXFProperty(size=0, charset="UTF-16") private final String ucs_encoding = null; @MXFProperty(size=0, charset="UTF-16") private final String namespace_uri = null; /** * Instantiates a new parsed TimedTextDescriptor object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public TimedTextDescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, TimedTextDescriptor.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } } /** * A method that returns a string representation of a TimedTextDescriptorBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== TimedTextDescriptor ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); if (this.subdescriptors != null) { sb.append(this.subdescriptors.toString()); } sb.append("================== SampleRate ======================\n"); sb.append(super.sample_rate.toString()); sb.append(String.format("essence_container = %s%n", this.essence_container.toString())); return sb.toString(); } } }
5,126
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/TextBasedObject.java
package com.netflix.imflibrary.st0377.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.annotations.MXFProperty; import javax.annotation.concurrent.Immutable; public class TextBasedObject extends InterchangeObject { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + TextBasedObject.class.getSimpleName() + " : "; private final TextBasedObjectBO textBasedObjectBO; public TextBasedObject(TextBasedObjectBO textBasedObjectBO) { this.textBasedObjectBO = textBasedObjectBO; } public String getDescription() { return this.textBasedObjectBO.description; } public String getMimeType() { return this.textBasedObjectBO.mime_type; } public String getLanguageCode() { return this.textBasedObjectBO.language_code; } /** * Object corresponding to a parsed TextBasedObject structural metadata set defined in RP 2057:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static class TextBasedObjectBO extends InterchangeObjectBO { @MXFProperty(size=16) protected final byte[] metadata_payload_scheme_id = null; @MXFProperty(size=0, charset = "UTF-16") protected final String mime_type = null; @MXFProperty(size=0, charset = "UTF-16") protected final String language_code = null; @MXFProperty(size=0, charset = "UTF-16") protected final String description = null; private final IMFErrorLogger imfErrorLogger; /** * Instantiates a new parsed TextBasedObjectBO object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param imfErrorLogger logger for recording any parsing errors */ TextBasedObjectBO(KLVPacket.Header header, IMFErrorLogger imfErrorLogger) { super(header); this.imfErrorLogger = imfErrorLogger; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== TextBasedObject ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("mime_type = %s%n", this.mime_type)); sb.append(String.format("language_code = %s%n", this.language_code)); if (this.description != null) { sb.append(String.format("description = %s%n", this.description)); } return sb.toString(); } protected void postPopulateCheck() { if (this.metadata_payload_scheme_id == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, ERROR_DESCRIPTION_PREFIX + "metadata_payload_scheme_id is null"); } if (this.mime_type == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, ERROR_DESCRIPTION_PREFIX + "mime_type is null"); } if (this.language_code == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, ERROR_DESCRIPTION_PREFIX + "language_code is null"); } } } }
5,127
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/DMFramework.java
package com.netflix.imflibrary.st0377.header; import com.netflix.imflibrary.KLVPacket; import javax.annotation.concurrent.Immutable; public class DMFramework extends InterchangeObject { private final DMFrameworkBO dmFrameworkBO; public DMFramework(DMFrameworkBO dmFrameworkBO) { this.dmFrameworkBO = dmFrameworkBO; } /** * Object corresponding to a parsed DMFramework structural metadata set defined in RP 2057:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static class DMFrameworkBO extends InterchangeObjectBO { public DMFrameworkBO(KLVPacket.Header header) { super(header); } } }
5,128
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/GenericStreamTextBasedSet.java
package com.netflix.imflibrary.st0377.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.utils.ByteProvider; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; public class GenericStreamTextBasedSet extends TextBasedObject { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + GenericStreamTextBasedSet.class.getSimpleName() + " : "; private final GenericStreamTextBasedSetBO genericStreamTextBasedSetBO; public GenericStreamTextBasedSet(GenericStreamTextBasedSetBO genericStreamTextBasedSetBO) { super(genericStreamTextBasedSetBO); this.genericStreamTextBasedSetBO = genericStreamTextBasedSetBO; } public Long getGenericStreamId() { return this.genericStreamTextBasedSetBO.generic_stream_id; } /** * Object corresponding to a parsed GenericStreamTextBasedSet structural metadata set defined in RP 2057:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class GenericStreamTextBasedSetBO extends TextBasedObjectBO { @MXFProperty(size=4) protected final Long generic_stream_id = null; private final IMFErrorLogger imfErrorLogger; /** * Instantiates a new parsed GenericStreamTextBasedSetBO object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public GenericStreamTextBasedSetBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header, imfErrorLogger); this.imfErrorLogger = imfErrorLogger; long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); postPopulateCheck(); } protected void postPopulateCheck() { super.postPopulateCheck(); if (generic_stream_id == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, ERROR_DESCRIPTION_PREFIX + "generic_stream_id is null"); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== TextBasedObject ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("mime_type = %s%n", this.mime_type)); sb.append(String.format("language_code = %s%n", this.language_code)); if (this.description != null) { sb.append(String.format("description = %s%n", this.description)); } sb.append(String.format("generic_stream_id = %d%n", this.generic_stream_id)); return sb.toString(); } } }
5,129
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/DescriptiveMarkerSegment.java
package com.netflix.imflibrary.st0377.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.st0377.CompoundDataTypes; import com.netflix.imflibrary.utils.ByteProvider; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; public class DescriptiveMarkerSegment extends Event { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + DescriptiveMarkerSegment.class.getSimpleName() + " : "; private final DescriptiveMarkerSegmentBO descriptiveMarkerSegmentBO; private final DMFramework dmFramework; public DescriptiveMarkerSegment(DescriptiveMarkerSegmentBO descriptiveMarkerSegmentBO, DMFramework dmFramework) { super(descriptiveMarkerSegmentBO); this.descriptiveMarkerSegmentBO = descriptiveMarkerSegmentBO; this.dmFramework = dmFramework; } public DMFramework getDmFramework() { return dmFramework; } /** * Object corresponding to a parsed DescriptiveMarkerSegment structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class DescriptiveMarkerSegmentBO extends EventBO { @MXFProperty(size=16, depends=true) private final StrongRef dm_framework = null; /** * Instantiates a new parsed DescriptiveMarkerSegment object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public DescriptiveMarkerSegmentBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, DescriptiveMarkerSegment.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.dm_framework == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, DescriptiveMarkerSegment.ERROR_DESCRIPTION_PREFIX + "dmframework is null"); } } /** * A method that returns a string representation of a DescriptiveMarkerSegmentBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== DescriptiveMarkerSegment ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("duration = %d%n", this.duration)); if (this.event_start_position != null) { sb.append(String.format("event_start_position = %d%n", this.event_start_position)); } if (this.event_comment != null) { sb.append(String.format("event_comment = %s%n", this.event_comment)); } sb.append(this.dm_framework.toString()); return sb.toString(); } } }
5,130
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/StructuralMetadata.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.header; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.st2067_201.IABEssenceDescriptor; import com.netflix.imflibrary.st2067_201.IABSoundfieldLabelSubDescriptor; import com.netflix.imflibrary.st379_2.ContainerConstraintsSubDescriptor; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.MXFPropertyPopulator; import com.netflix.imflibrary.KLVPacket; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * A class that contains helper methods to identify and populate Structural Metadata set objects */ public final class StructuralMetadata { private StructuralMetadata() { //to prevent instantiation } private static final byte[] KEY_BASE = {0x06, 0x0e, 0x2b, 0x34, 0x02, 0x00, 0x01, 0x00, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00}; private static final byte[] KEY_MASK = { 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1}; private static final byte[] DESCRIPTIVE_METADATA_KEY_BASE = {0x06, 0x0e, 0x2b, 0x34, 0x02, 0x00, 0x01, 0x00, 0x0d, 0x01, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00}; private static final byte[] DESCRIPTIVE_METADATA_KEY_MASK = { 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1}; private static final byte[] PHDR_METADATA_TRACK_SUBDESCRIPTOR = {0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x05, 0x0e, 0x09, 0x06, 0x07, 0x01, 0x01, 0x01, 0x03}; private static final Map<MXFUID, String> ItemULToItemName; static { Map<MXFUID, String> map = new HashMap<>(); //Preface { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x15, 0x02, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "instance_uid"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07, 0x02, 0x01, 0x10, 0x02, 0x04, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "last_modified_date"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x02, 0x01, 0x05, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "version"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x06, 0x01, 0x01, 0x04, 0x01, 0x08, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "primary_package"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x02, 0x01, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "content_storage"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x01, 0x02, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "operational_pattern"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x01, 0x02, 0x02, 0x10, 0x02, 0x01, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "essencecontainers"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x01, 0x02, 0x02, 0x10, 0x02, 0x02, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "dm_schemes"); } //TimelineTrack { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x01, 0x07, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "track_id"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x01, 0x04, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "track_number"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x02, 0x04, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "sequence"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05, 0x30, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "edit_rate"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07 , 0x02, 0x01, 0x03, 0x01, 0x03, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "origin"); } //Event { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07 , 0x02, 0x01, 0x03, 0x03, 0x03, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "event_start_position"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05 , 0x30, 0x04, 0x04, 0x01, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "event_comment"); } //DMSegment { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x01, 0x07, 0x01, 0x05, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "track_ids"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x06, 0x01, 0x01, 0x04, 0x02, 0x0c, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "dm_framework"); } //CDCIPictureEssenceDescriptor { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x06, 0x01, 0x01, 0x04, 0x06, 0x10, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "subdescriptors"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x06, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "sample_rate"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x01, 0x02, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "essence_container"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x03, 0x01, 0x04, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "frame_layout"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x02, 0x02, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "stored_width"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x02, 0x01, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "stored_height"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "aspect_ratio"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x03, 0x02, 0x05, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "video_line_map"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x06, 0x01, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "picture_essence_coding"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x05, 0x03, 0x0A, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "component_depth"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x01, 0x05, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "horizontal_subsampling"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x05, 0x01, 0x10, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "vertical_subsampling"); } //Sequence { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "data_definition"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07, 0x02, 0x02, 0x01, 0x01, 0x03, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "duration"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x06, 0x09, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "structural_components"); } //SourceClip { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07, 0x02, 0x01, 0x03, 0x01, 0x04, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "start_position"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x03, 0x01, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "source_package_id"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x03, 0x02, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "source_track_id"); } //ContentStorage { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x05, 0x01, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "packages"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x05, 0x02, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "essencecontainer_data"); } //EssenceContainerData { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x06, 0x01, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "linked_package_uid"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x01, 0x03, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "index_sid"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x01, 0x03, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "body_sid"); } //MaterialPackage { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x15, 0x10, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "package_uid"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07, 0x02, 0x01, 0x10, 0x01, 0x03, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "package_creation_date"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07, 0x02, 0x01, 0x10, 0x02, 0x05, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "package_modified_date"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x06, 0x05, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "tracks"); } //SourcePackage { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x02, 0x03, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "descriptor"); } //WaveAudioEssenceDescriptor { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "audio_sampling_rate"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x01, 0x01, 0x04, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "channelcount"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x04, 0x02, 0x03, 0x03, 0x04, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "quantization_bits"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x02, 0x04, 0x02, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "sound_essence_coding"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x03, 0x02, 0x01, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "block_align"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x03, 0x03, 0x05, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "average_bytes_per_second"); } { byte[] byteArray = {0x06, 0x0e ,0x2b ,0x34 ,0x01 ,0x01 ,0x01 ,0x07 ,0x04 ,0x02 ,0x01 ,0x01 ,0x05 ,0x00 ,0x00 ,0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "channel_assignment"); } //GenericSoundEssenceDescriptor { byte[] byteArray = {0x06, 0x0e ,0x2b ,0x34 ,0x01 ,0x01 ,0x01 ,0x0e ,0x04 ,0x02 ,0x01 ,0x01 ,0x06 ,0x00 ,0x00 ,0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "reference_image_edit_rate"); } { byte[] byteArray = {0x06, 0x0e ,0x2b ,0x34 ,0x01 ,0x01 ,0x01 ,0x0e ,0x04 ,0x02 ,0x01 ,0x01 ,0x07 ,0x00 ,0x00 ,0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "reference_audio_alignment_level"); } //AudioChannelLabelSubDescriptor { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x01, 0x03, 0x07, 0x01, 0x01, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "mca_label_dictionary_id"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x01, 0x03, 0x07, 0x01, 0x05, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "mca_link_id"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x01, 0x03, 0x07, 0x01, 0x02, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "mca_tag_symbol"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x01, 0x03, 0x07, 0x01, 0x03, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "mca_tag_name"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x01, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "mca_channel_id"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x03, 0x01, 0x01, 0x02, 0x03, 0x15, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "rfc_5646_spoken_language"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x01, 0x05, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "mca_title"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x01, 0x05, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "mca_title_version"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x03, 0x02, 0x01, 0x02, 0x20, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "mca_audio_content_kind"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x03, 0x02, 0x01, 0x02, 0x21, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "mca_audio_element_kind"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x01, 0x03, 0x07, 0x01, 0x06, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "soundfield_group_link_id"); } /*{ byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x01, 0x03, 0x07, 0x01, 0x04, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "group_of_soundfield_groups_linkID"); }*/ //JPEG2000SubDescriptor { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x01, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "rSiz"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x02, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "xSiz"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x03, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "ySiz"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x04, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "xoSiz"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x05, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "yoSiz"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x06, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "xtSiz"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x07, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "ytSiz"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x08, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "xtoSiz"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x09, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "ytoSiz"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x0A, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "cSiz"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x0B, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "picture_component_sizing"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x0C, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "coding_style_default"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x0D, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "quantisation_default"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x04, 0x01, 0x02, 0x01, 0x01, 0x06, 0x01, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "color_primaries"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x02, 0x01, 0x01, 0x03, 0x01, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "coding_equations"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x02, 0x01, 0x01, 0x01, 0x02, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "transfer_characteristic"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x05, 0x03, 0x0b, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "component_max_ref"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x05, 0x03, 0x0c, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "component_min_ref"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x03, 0x03, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "black_ref_level"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x03, 0x04, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "white_ref_level"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x01, 0x01, 0x15, 0x12, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "resource_id"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x04, 0x09, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "ucs_encoding"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x08, 0x01, 0x02, 0x01, 0x05, 0x01, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "namespace_uri"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x07, 0x04, 0x09, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "mime_media_type"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x01, 0x02, 0x02, 0x10, 0x02, 0x04, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "conforms_to_specifications"); } // ACESPictureSubDescriptor { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x0a, 0x01, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "aces_authoring_information"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x0a, 0x02, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "aces_mastering_display_primaries"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x0a, 0x03, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "aces_mastering_white"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x0a, 0x04, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "aces_max_luminance"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x0a, 0x05, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "aces_min_luminance"); } //TargetFrameSubDescriptor { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x09, 0x01, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "ancillary_resource_uid"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x09, 0x02, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "media_type"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x09, 0x03, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "target_frame_index"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x09, 0x04, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "target_frame_transfer_characteristic"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x09, 0x05, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "color_primaries"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x09, 0x06, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "max_ref"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x09, 0x07, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "min_ref"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x09, 0x08, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "essence_stream_id"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x09, 0x09, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "aces_picture_subdescriptor_uid"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0e, 0x04, 0x01, 0x06, 0x09, 0x0a, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "viewing_environment"); } //Text-based DM Framework { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x06, 0x01, 0x01, 0x04, 0x05, 0x41, 0x01, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "text_based_object"); } //Text-based Object { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x04, 0x06, 0x08, 0x06, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "metadata_payload_scheme_id"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x04, 0x09, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "mime_type"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x03, 0x01, 0x01, 0x02, 0x02, 0x14, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "language_code"); } { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x03, 0x02, 0x01, 0x06, 0x03, 0x02, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "description"); } //Generic Stream Text-based Set { byte[] byteArray = {0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x03, 0x04, 0x08, 0x00, 0x00, 0x00, 0x00}; MXFUID mxfUL = new MXFUID(byteArray); map.put(mxfUL, "generic_stream_id"); } ItemULToItemName = Collections.unmodifiableMap(map); } /** * A method that determines of the key passed in corresponds to a structural metadata set. * * @param key the key * @return the boolean */ public static boolean isStructuralMetadata(byte[] key) { if (isPHDRMetadataTrackSubDescriptor(key)) { return true; } for (int i=0; i< KLVPacket.KEY_FIELD_SIZE; i++) { if( (StructuralMetadata.KEY_MASK[i] != 0) && (StructuralMetadata.KEY_BASE[i] != key[i]) ) { return false; } } return ((key[5] == 0x53) || (key[5] == 0x13)); } /** * A method that determines of the key passed in corresponds to a descriptive metadata set. * * @param key the key * @return the boolean */ public static boolean isDescriptiveMetadata(byte[] key) { for (int i=0; i< KLVPacket.KEY_FIELD_SIZE; i++) { if( (StructuralMetadata.DESCRIPTIVE_METADATA_KEY_MASK[i] != 0) && (StructuralMetadata.DESCRIPTIVE_METADATA_KEY_BASE[i] != key[i]) ) { return false; } } return ((key[5] == 0x53) || (key[5] == 0x13)); } /** * A method that determines if the key passed in corresponds to a PHDRMetadataTrackSubDescriptor. * * @param key the key * @return the boolean */ public static boolean isPHDRMetadataTrackSubDescriptor(byte[] key) { return Arrays.equals(key, StructuralMetadata.PHDR_METADATA_TRACK_SUBDESCRIPTOR); } public static boolean isAudioWaveClipWrapped(int contentKind){ if(contentKind == 0x02){ return true; } else{ return false; } } /** * Gets structural metadata set class object. * Note: For all structural metadata set items that we do not read we will return an Object.class * @param key the key * @return the structural metadata set name */ public static Class getStructuralMetadataSetClass(byte[] key) { if (isPHDRMetadataTrackSubDescriptor(key)) { return PHDRMetaDataTrackSubDescriptor.PHDRMetaDataTrackSubDescriptorBO.class; } else if (isStructuralMetadata(key) && (key[13] == 0x01)) { switch (key[14]) { case 0x2f : return Preface.PrefaceBO.class; case 0x30 : return Object.class; //Identification case 0x18 : return ContentStorage.ContentStorageBO.class; case 0x23 : return EssenceContainerData.EssenceContainerDataBO.class; case 0x36 : return MaterialPackage.MaterialPackageBO.class; case 0x37 : return SourcePackage.SourcePackageBO.class; case 0x3b : return TimelineTrack.TimelineTrackBO.class; case 0x39 : return Object.class; //Event Track case 0x3A : return StaticTrack.StaticTrackBO.class; case 0x0F: return Sequence.SequenceBO.class; case 0x11 : return SourceClip.SourceClipBO.class; case 0x14 : return TimecodeComponent.TimecodeComponentBO.class; case 0x41 : return DescriptiveMarkerSegment.DescriptiveMarkerSegmentBO.class; //DM Segment case 0x45 : return Object.class; //DM Source Clip case 0x09 : return Object.class; //Filler case 0x60 : return Object.class; //Package Marker Object case 0x25 : return FileDescriptor.FileDescriptorBO.class; case 0x27 : return GenericPictureEssenceDescriptor.GenericPictureEssenceDescriptorBO.class; case 0x28 : return CDCIPictureEssenceDescriptor.CDCIPictureEssenceDescriptorBO.class; case 0x29 : return RGBAPictureEssenceDescriptor.RGBAPictureEssenceDescriptorBO.class; case 0x42 : return GenericSoundEssenceDescriptor.GenericSoundEssenceDescriptorBO.class; case 0x43 : return Object.class; //Generic Data Essence Descriptor case 0x44 : return Object.class; //Multiple Descriptor case 0x32 : return Object.class; //Network Locator case 0x33 : return Object.class; //Text Locator case 0x61 : return Object.class; //Application Plug-In Object case 0x62 : return Object.class; //Application Referenced Object case 0x48 : return WaveAudioEssenceDescriptor.WaveAudioEssenceDescriptorBO.class; case 0x64 : return TimedTextDescriptor.TimedTextDescriptorBO.class; case 0x65 : return TimeTextResourceSubDescriptor.TimeTextResourceSubdescriptorBO.class; case 0x67 : return ContainerConstraintsSubDescriptor.ContainerConstraintsSubDescriptorBO.class; case 0x6b : return AudioChannelLabelSubDescriptor.AudioChannelLabelSubDescriptorBO.class; case 0x6c : return SoundFieldGroupLabelSubDescriptor.SoundFieldGroupLabelSubDescriptorBO.class; case 0x6d : return GroupOfSoundFieldGroupLabelSubDescriptor.GroupOfSoundFieldGroupLabelSubDescriptorBO.class; case 0x5A : return JPEG2000PictureSubDescriptor.JPEG2000PictureSubDescriptorBO.class; case 0x7B : return IABEssenceDescriptor.IABEssenceDescriptorBO.class; case 0x7C : return IABSoundfieldLabelSubDescriptor.IABSoundfieldLabelSubDescriptorBO.class; case 0x79 : return ACESPictureSubDescriptor.ACESPictureSubDescriptorBO.class; case 0x7a : return TargetFrameSubDescriptor.TargetFrameSubDescriptorBO.class; default : return Object.class; } } else if (isDescriptiveMetadata(key)) { // Metadata Sets for the Text-based Metadata if (key[13] == 0x02 && key[14] == 0x01) { return GenericStreamTextBasedSet.GenericStreamTextBasedSetBO.class; } else if (key[13] == 0x01 && key[14] == 0x01) { return TextBasedDMFramework.TextBasedDMFrameworkBO.class; } else { return Object.class; } } else { return Object.class; } } /** * A method that populates the fields of a Structural Metadata set * * @param object the InterchangeObjectBO object * @param byteProvider the mxf byte provider * @param numBytesToRead the num bytes to read * @param localTagToUIDMap the local tag to uID map * @throws IOException the iO exception */ public static void populate(InterchangeObject.InterchangeObjectBO object, ByteProvider byteProvider, long numBytesToRead, Map<Integer, MXFUID> localTagToUIDMap) throws IOException { long numBytesRead = 0; while (numBytesRead < numBytesToRead) { /*From smpte st 377-1:2011 section 9.6, all structural header metadata objects shall be implemented as MXF Local Sets which implies that the data item local tag is always 2 bytes long*/ //read local tag int localTag = MXFPropertyPopulator.getUnsignedShortAsInt(byteProvider.getBytes(2), KLVPacket.BYTE_ORDER); numBytesRead += 2; //read length long length; if (object.getHeader().getRegistryDesignator() == 0x53) { length = MXFPropertyPopulator.getUnsignedShortAsInt(byteProvider.getBytes(2), KLVPacket.BYTE_ORDER); numBytesRead += 2; } else if (object.getHeader().getRegistryDesignator() == 0x13) { KLVPacket.LengthField lengthField = KLVPacket.getLength(byteProvider); length = lengthField.value; numBytesRead += lengthField.sizeOfLengthField; } else { throw new MXFException(String.format("Byte 5 (zero-indexed) for MXF Structural Metadata key = %s is invalid", Arrays.toString(object.getHeader().getKey()))); } //read or skip value MXFUID mxfUL = localTagToUIDMap.get(localTag); if ((mxfUL != null) && (StructuralMetadata.ItemULToItemName.get(mxfUL) != null)) { String itemName = StructuralMetadata.ItemULToItemName.get(mxfUL); int expectedLength = MXFPropertyPopulator.getFieldSizeInBytes(object, itemName); if((expectedLength > 0) && (length != expectedLength)) { throw new MXFException(String.format("Actual length from bitstream = %d is different from expected length = %d", length, expectedLength)); } MXFPropertyPopulator.populateField((int) length, byteProvider, object, itemName); } else { byteProvider.skipBytes(length); } numBytesRead += length; } } }
5,131
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/GroupOfSoundFieldGroupLabelSubDescriptor.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.utils.ByteProvider; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to GroupOfSoundFieldGroupLabelSubDescriptor structural metadata set defined in st377-4:2012 */ @Immutable public final class GroupOfSoundFieldGroupLabelSubDescriptor extends SubDescriptor { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + GroupOfSoundFieldGroupLabelSubDescriptor.class.getSimpleName() + " : "; private final GroupOfSoundFieldGroupLabelSubDescriptorBO groupOfSoundFieldGroupLabelSubDescriptorBO; /** * Constructor for a GroupOfSoundFieldGroupLabelSubDescriptor object * @param groupOfSoundFieldGroupLabelSubDescriptorBO the parsed GroupOfSoundFieldGroupLabelSubDescriptor object */ public GroupOfSoundFieldGroupLabelSubDescriptor(GroupOfSoundFieldGroupLabelSubDescriptorBO groupOfSoundFieldGroupLabelSubDescriptorBO) { this.groupOfSoundFieldGroupLabelSubDescriptorBO = groupOfSoundFieldGroupLabelSubDescriptorBO; } /** * Getter for the MCALabelDictionary ID referred by this GroupOfSoundFieldGroupLabelSubDescriptor object * @return the MCALabelDictionary ID referred by this GroupOfSoundFieldGroupLabelSubDescriptor object */ public MXFUID getMCALabelDictionaryId() { return this.groupOfSoundFieldGroupLabelSubDescriptorBO.mca_label_dictionary_id.getULAsMXFUid(); } /** * Getter for the MCALink Id that links the instances of the MCALabelSubDescriptors * @return the MCALink Id that links the instances of the MCALabelSubDescriptors */ public MXFUID getMCALinkId() { if(this.groupOfSoundFieldGroupLabelSubDescriptorBO.mca_link_id == null) { return null; } return new MXFUID(this.groupOfSoundFieldGroupLabelSubDescriptorBO.mca_link_id); } /** * A getter for the spoken language in this SubDescriptor * @return string representing the spoken language as defined in RFC-5646 */ public String getRFC5646SpokenLanguage(){ return this.groupOfSoundFieldGroupLabelSubDescriptorBO.rfc_5646_spoken_language; } /** * A method that returns a string representation of a GroupOfSoundFieldGroupLabelSubDescriptor object * * @return string representing the object */ public String toString() { return this.groupOfSoundFieldGroupLabelSubDescriptorBO.toString(); } /** * Object corresponding to a parsed GroupOfSoundFieldGroupLabelSubDescriptor structural metadata set defined in st377-4:2012 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class GroupOfSoundFieldGroupLabelSubDescriptorBO extends MCALabelSubDescriptor.MCALabelSubDescriptorBO { //@MXFProperty(size=0, charset="UTF-16") protected final String group_of_soundfield_groups_linkID = null; /** * Instantiates a new parsed GroupOfSoundFieldGroupLabelSubDescriptor object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public GroupOfSoundFieldGroupLabelSubDescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, GroupOfSoundFieldGroupLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.mca_label_dictionary_id == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, GroupOfSoundFieldGroupLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "mca_label_dictionary_id is null"); } if (this.mca_link_id == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, GroupOfSoundFieldGroupLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "mca_link_id is null"); } if (this.mca_tag_symbol == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, GroupOfSoundFieldGroupLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "mca_tag_symbol is null"); } } } }
5,132
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/SubDescriptor.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.header; import com.netflix.imflibrary.KLVPacket; /** * Object model corresponding to Subdescriptor structural metadata set defined in st377-1:2011 */ public abstract class SubDescriptor extends InterchangeObject { /** * Object corresponding to a parsed Subdescriptor structural metadata set defined in st377-1:2011 */ public static abstract class SubDescriptorBO extends InterchangeObjectBO { /** * Constructor for a Sub descriptor ByteObject. * * @param header the MXF KLV header (Key and Length field) */ protected SubDescriptorBO(final KLVPacket.Header header) { super(header); } } }
5,133
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/TimeTextResourceSubDescriptor.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.utils.ByteProvider; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to TimeTextResourceSubdescriptor as defined in st429-5:2009 */ @Immutable public final class TimeTextResourceSubDescriptor extends SubDescriptor { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + TimeTextResourceSubDescriptor.class.getSimpleName() + " : "; private final TimeTextResourceSubdescriptorBO subDescriptorBO; /** * Constructor for a TimeTextResourceSubdescriptor object * @param subDescriptorBO the parsed TimeTextResourceSubdescriptor object */ public TimeTextResourceSubDescriptor(TimeTextResourceSubdescriptorBO subDescriptorBO){ this.subDescriptorBO = subDescriptorBO; } /** * Getter for the MIMEMediaType * @return a String representing the A MIME Type identifier which identifies the resource data type */ public String getMimeMediaType() { return this.subDescriptorBO.mime_media_type; } /** * A method that returns a string representation of a TimeTextResourceSubdescriptor object * * @return string representing the object */ public String toString() { return this.subDescriptorBO.toString(); } /** * Object corresponding to a parsed TimeTextResourceSubdescriptor as defined in st429-5-2009 */ @Immutable public static final class TimeTextResourceSubdescriptorBO extends SubDescriptorBO{ @MXFProperty(size=4) private final Long body_sid = null; @MXFProperty(size=16) protected final byte[] generation_uid = null; @MXFProperty(size=0, charset="UTF-16") private final String mime_media_type = null; /** * Instantiates a new time text resource sub descriptor ByteObject. * * @param header the header * @param byteProvider the mxf byte provider * @param localTagToUIDMap the local tag to uID map * @param imfErrorLogger the imf error logger * @throws IOException - any I/O related error will be exposed through an IOException */ public TimeTextResourceSubdescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, TimeTextResourceSubDescriptor.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } } /** * A method that returns a string representation of a TimeTextResourceSubdescriptorBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== TimeTextResourceSubdescriptor ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); return sb.toString(); } } }
5,134
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/PHDRMetaDataTrackSubDescriptor.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to PHDRMetaDataTrackSubDescriptor structural metadata set */ @Immutable public final class PHDRMetaDataTrackSubDescriptor extends SubDescriptor { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + PHDRMetaDataTrackSubDescriptor.class.getSimpleName() + " : "; private final PHDRMetaDataTrackSubDescriptorBO phdrMetaDataTrackSubDescriptorBO; /** * Instantiates a new PHDR meta data track sub descriptor. * * @param phdrMetaDataTrackSubDescriptorBO the phdr meta data track sub descriptor bO */ public PHDRMetaDataTrackSubDescriptor(PHDRMetaDataTrackSubDescriptorBO phdrMetaDataTrackSubDescriptorBO) { this.phdrMetaDataTrackSubDescriptorBO = phdrMetaDataTrackSubDescriptorBO; } /** * A method that returns a string representation of a PHDRMetaDataTrackSubDescriptor object * * @return string representing the object */ public String toString() { return this.phdrMetaDataTrackSubDescriptorBO.toString(); } /** * The type PHDR meta data track sub descriptor ByteObject. */ @Immutable public static final class PHDRMetaDataTrackSubDescriptorBO extends SubDescriptorBO { /** * Instantiates a new PHDR meta data track sub descriptor ByteObject. * * @param header the header * @param byteProvider the mxf byte provider * @param localTagToUIDMap the local tag to uID map * @param imfErrorLogger the imf error logger * @throws IOException the iO exception */ public PHDRMetaDataTrackSubDescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, PHDRMetaDataTrackSubDescriptor.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } } /** * A method that returns a string representation of a PHDRMetaDataTrackSubDescriptorBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== PHDRMetaDataTrackSubdescriptor ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); return sb.toString(); } } }
5,135
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/Event.java
package com.netflix.imflibrary.st0377.header; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.annotations.MXFProperty; import javax.annotation.concurrent.Immutable; public class Event extends StructuralComponent { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + Event.class.getSimpleName() + " : "; private final EventBO eventBO; /** * Instantiates a new Event object * * @param eventBO the parsed Event object */ public Event(EventBO eventBO) { this.eventBO = eventBO; } /** * Object corresponding to a parsed Event structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static class EventBO extends StructuralComponentBO { @MXFProperty(size=8) protected final Long event_start_position = null; @MXFProperty(size=0, charset = "UTF-16") protected final String event_comment = null; //UTF-16 String /** * Instantiates a new parsed Event object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) */ public EventBO(KLVPacket.Header header) { super(header); } /** * A method that returns a string representation of a EventBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== Event ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("duration = %d%n", this.duration)); if (this.event_start_position != null) { sb.append(String.format("event_start_position = %d%n", this.event_start_position)); } if (this.event_comment != null) { sb.append(String.format("event_comment = %s%n", this.event_comment)); } return sb.toString(); } } }
5,136
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/RGBAPictureEssenceDescriptor.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to RGBAPictureEssenceDescriptor structural metadata set defined in st377-1:2011 */ @Immutable public final class RGBAPictureEssenceDescriptor extends GenericPictureEssenceDescriptor { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + RGBAPictureEssenceDescriptor.class.getSimpleName() + " : "; private final RGBAPictureEssenceDescriptorBO rgbaPictureEssenceDescriptorBO; /** * Constructor for a RGBAPictureEssenceDescriptor object * @param rgbaPictureEssenceDescriptorBO the parsed RGBAPictureEssenceDescriptor object */ public RGBAPictureEssenceDescriptor(RGBAPictureEssenceDescriptorBO rgbaPictureEssenceDescriptorBO) { this.rgbaPictureEssenceDescriptorBO = rgbaPictureEssenceDescriptorBO; } /** * Getter for the Essence Container UL of this FileDescriptor * @return a UL representing the Essence Container */ public UL getEssenceContainerUL(){ return this.rgbaPictureEssenceDescriptorBO.getEssenceContainerUL(); } /** * A method that returns a string representation of a RGBAPictureEssenceDescriptor object * * @return string representing the object */ public String toString() { return this.rgbaPictureEssenceDescriptorBO.toString(); } /** * Object corresponding to a parsed RGBAPictureEssenceDescriptor structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class RGBAPictureEssenceDescriptorBO extends GenericPictureEssenceDescriptor.GenericPictureEssenceDescriptorBO { @MXFProperty(size=4) protected final Long component_max_ref = null; @MXFProperty(size=4) protected final Long component_min_ref = null; /** * Instantiates a new parsed RGBAPictureEssenceDescriptor object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public RGBAPictureEssenceDescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, RGBAPictureEssenceDescriptor.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } } /** * Accessor for the ComponentMaxRef UL * @return a long integer representing the maximum value for RGB components */ public Long getComponentMaxRef(){ return this.component_max_ref; } /** * Accessor for the ComponentMinRef UL * @return a long integer representing the minimum value for RGB components */ public Long getComponentMinRef(){ return this.component_min_ref; } /** * A method that returns a string representation of a RGBAPictureEssenceDescriptorBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== RGBAPictureEssenceDescriptor ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); if (this.subdescriptors != null) { sb.append(this.subdescriptors.toString()); } sb.append("================== SampleRate ======================\n"); sb.append(super.sample_rate.toString()); sb.append(String.format("essence_container = %s%n", this.essence_container.toString())); sb.append(String.format("frame_layout = %d%n", this.frame_layout)); sb.append(String.format("stored_width = %d%n", this.stored_width)); sb.append(String.format("stored_height = %d%n", this.stored_height)); sb.append("================== AspectRatio ======================\n"); sb.append(this.aspect_ratio.toString()); if (this.video_line_map != null) { sb.append(this.video_line_map.toString()); } sb.append(String.format("picture_essence_coding = %s%n", this.picture_essence_coding.toString())); return sb.toString(); } } }
5,137
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/MCALabelSubDescriptor.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.header; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.annotations.MXFProperty; /** * Object model corresponding to MultiChannelAudioLabelSubDescriptor structural metadata set defined in st377-4:2012 */ public abstract class MCALabelSubDescriptor extends SubDescriptor { /** * Object corresponding to a parsed MultiChannelAudioLabelSubDescriptor structural metadata set defined in st377-4:2012 */ public static abstract class MCALabelSubDescriptorBO extends SubDescriptorBO{ @MXFProperty(size=16) protected final UL mca_label_dictionary_id = null; @MXFProperty(size=16) protected final byte[] mca_link_id = null; //UUID type @MXFProperty(size=0, charset = "UTF-16") protected final String mca_tag_symbol = null; //UTF-16 String @MXFProperty(size=0, charset = "UTF-16") protected final String mca_tag_name = null; //UTF-16 String @MXFProperty(size=4) protected final Long mca_channel_id = null; @MXFProperty(size=0, charset="ISO-8859-1") protected final String rfc_5646_spoken_language = null; //ISO-8 String @MXFProperty(size=0, charset="UTF-16") protected final String mca_title = null; @MXFProperty(size=0, charset="UTF-16") protected final String mca_title_version = null; @MXFProperty(size=0, charset="UTF-16") protected final String mca_audio_content_kind = null; @MXFProperty(size=0, charset="UTF-16") protected final String mca_audio_element_kind = null; /** * Constructor for a parsed MCA Label Sub descriptor object * * @param header the MXF KLV header (Key and Length field) */ public MCALabelSubDescriptorBO(final KLVPacket.Header header) { super(header); } /** * Accessor for the ChannelID of this MCA Label Subdescriptor * @return a long integer representing the channel Id for the MCALabelSubDescriptor */ public Long getMCAChannelID(){ return this.mca_channel_id; } /** * Accessor for the MCA Tag Name of this MCA Label Subdescriptor * @return a String representing the MCA Tag Name */ public String getMCATagName(){ return this.mca_tag_name; } /** * Accessor for the MCA Tag Symbol of this MCA Label Subdescriptor * @return a String representing the MCA Tag Symbol */ public String getMCATagSymbol(){ return this.mca_tag_symbol; } /** * Accessor for the MCA Label Dictionnary ID of this MCA Label Subdescriptor * @return a UL representing the MCA Label Dictionnary ID */ public UL getMCALabelDictionnaryId(){ return this.mca_label_dictionary_id; } /** * Accessor for the MCA Title of this MCA Label Subdescriptor * @return a String representing the MCA Title */ public String getMCATitle(){ return this.mca_title; } /** * Accessor for the MCA Title Version of this MCA Label Subdescriptor * @return a String representing the MCA Title Version */ public String getMCATitleVersion(){ return this.mca_title_version; } /** * Accessor for the MCA Audio Content Kind of this MCA Label Subdescriptor * @return a String representing the MCA Audio Content Kind */ public String getMCAAudioContentKind(){ return this.mca_audio_content_kind; } /** * Accessor for the MCA Audio Element Kind of this MCA Label Subdescriptor * @return a String representing the MCA Audio Element Kind */ public String getMCAAudioElementKind(){ return this.mca_audio_element_kind; } /** * Accessor for the RFC 5646 Spoken Language of this MCA Label Subdescriptor * @return a String representing the RFC 5646 Spoken Language */ public String getRFC5646SpokenLanguage(){ return this.rfc_5646_spoken_language; } /** * A method that returns a string representation of a SoundFieldGroupLabelSubDescriptorBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("================== %s ======================%n", this.getClass().getSimpleName())); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("mca_label_dictionary_id = %s%n", this.mca_label_dictionary_id.toString())); sb.append(String.format("mca_link_id = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.mca_link_id[0], this.mca_link_id[1], this.mca_link_id[2], this.mca_link_id[3], this.mca_link_id[4], this.mca_link_id[5], this.mca_link_id[6], this.mca_link_id[7], this.mca_link_id[8], this.mca_link_id[9], this.mca_link_id[10], this.mca_link_id[11], this.mca_link_id[12], this.mca_link_id[13], this.mca_link_id[14], this.mca_link_id[15])); sb.append(String.format("mca_tag_symbol = %s%n", this.mca_tag_symbol)); if (this.mca_tag_name != null) { sb.append(String.format("mca_tag_name = %s%n", this.mca_tag_name)); } if (this.mca_channel_id != null) { sb.append(String.format("mca_channel_id = %d%n", this.mca_channel_id)); } if (this.rfc_5646_spoken_language != null) { sb.append(String.format("rfc_5646_spoken_language = %s%n", this.rfc_5646_spoken_language)); } if (this.mca_title != null) { sb.append(String.format("mca_title = %s%n", this.mca_title)); } if (this.mca_title_version != null) { sb.append(String.format("mca_title_version = %s%n", this.mca_title_version)); } if (this.mca_audio_content_kind != null) { sb.append(String.format("mca_audio_content_kind = %s%n", this.mca_audio_content_kind)); } if (this.mca_audio_element_kind != null) { sb.append(String.format("mca_audio_element_kind = %s%n", this.mca_audio_element_kind)); } return sb.toString(); } } }
5,138
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/TargetFrameSubDescriptor.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.st0377.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.st0377.CompoundDataTypes; import com.netflix.imflibrary.utils.ByteProvider; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to TargetFrameSubDescriptor as defined in st429-4:2006 */ @Immutable public final class TargetFrameSubDescriptor extends SubDescriptor { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + TargetFrameSubDescriptor.class.getSimpleName() + " : "; private final TargetFrameSubDescriptorBO subDescriptorBO; /** * Constructor for a TargetFrameSubDescriptor object * @param subDescriptorBO the parsed TargetFrameSubDescriptor object */ public TargetFrameSubDescriptor(TargetFrameSubDescriptorBO subDescriptorBO){ this.subDescriptorBO = subDescriptorBO; } /** * A method that returns a string representation of a TargetFrameSubDescriptor object * * @return string representing the object */ public String toString() { return this.subDescriptorBO.toString(); } /** * Object corresponding to a parsed TargetFrameSubDescriptor as defined in st429-4-2006 */ @Immutable public static final class TargetFrameSubDescriptorBO extends SubDescriptorBO{ @MXFProperty(size=16) private final UL ancillary_resource_uid = null; @MXFProperty(size=0, charset="UTF-16") private final String media_type = null; @MXFProperty(size=8) private final Long target_frame_index = null; @MXFProperty(size=16) private final UL target_frame_transfer_characteristic = null; @MXFProperty(size=16) private final UL color_primaries = null; @MXFProperty(size=4) private final Integer max_ref = null; @MXFProperty(size=4) private final Integer min_ref = null; @MXFProperty(size=4) private final Integer essence_stream_id = null; @MXFProperty(size=16) private final UL aces_picture_subdescriptor_uid = null; @MXFProperty(size=16) private final UL viewing_environment = null; /** * Instantiates a new TargetFrameSubDescriptor ByteObject. * * @param header the header * @param byteProvider the mxf byte provider * @param localTagToUIDMap the local tag to uID map * @param imfErrorLogger the imf error logger * @throws IOException - any I/O related error will be exposed through an IOException */ public TargetFrameSubDescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, TargetFrameSubDescriptor.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } } /** * A method that returns a string representation of a TargetFrameSubDescriptorBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== TargetFrameSubDescriptor ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); if (this.ancillary_resource_uid != null) sb.append(String.format("ancillary_resource_uid = %s%n", this.ancillary_resource_uid.toString())); sb.append(String.format("media_type = %s%n", this.media_type)); sb.append(String.format("target_frame_index = %d%n", this.target_frame_index)); if (this.target_frame_transfer_characteristic != null) sb.append(String.format("target_frame_transfer_characteristic = %s%n", this.target_frame_transfer_characteristic.toString())); if (this.color_primaries != null) sb.append(String.format("color_primaries = %s%n", this.color_primaries.toString())); sb.append(String.format("max_ref = %d%n", this.max_ref)); sb.append(String.format("min_ref = %d%n", this.min_ref)); sb.append(String.format("essence_stream_id = %d%n", this.essence_stream_id)); if (this.aces_picture_subdescriptor_uid != null) sb.append(String.format("aces_picture_subdescriptor_uid = %s%n", this.aces_picture_subdescriptor_uid.toString())); if (this.viewing_environment != null) sb.append(String.format("viewing_environment = %s%n", this.viewing_environment.toString())); return sb.toString(); } } }
5,139
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/TextBasedDMFramework.java
package com.netflix.imflibrary.st0377.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.utils.ByteProvider; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; public class TextBasedDMFramework extends DMFramework { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + TextBasedObject.class.getSimpleName() + " : "; private final TextBasedDMFrameworkBO textBasedDMFrameworkBO; private final TextBasedObject textBaseObject; public TextBasedDMFramework(TextBasedDMFrameworkBO textBasedDMFrameworkBO, TextBasedObject textBasedObject) { super(textBasedDMFrameworkBO); this.textBasedDMFrameworkBO = textBasedDMFrameworkBO; this.textBaseObject = textBasedObject; } public TextBasedObject getTextBaseObject() { return textBaseObject; } /** * Object corresponding to a parsed TextBasedDMFramework structural metadata set defined in RP 2057:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static class TextBasedDMFrameworkBO extends DMFrameworkBO { @MXFProperty(size=16, depends=true) private final StrongRef text_based_object = null; private final IMFErrorLogger imfErrorLogger; /** * Instantiates a new parsed GenericStreamTextBasedSetBO object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public TextBasedDMFrameworkBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); this.imfErrorLogger = imfErrorLogger; long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== TextBasedDMFramework ======================\n"); sb.append(this.header.toString()); if (this.text_based_object != null) { sb.append(String.format("description = %s%n", this.text_based_object)); } return sb.toString(); } } }
5,140
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/TimelineTrack.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.st0377.CompoundDataTypes; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to TimelineTrack structural metadata set defined in st377-1:2011 */ @Immutable public final class TimelineTrack extends GenericTrack { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + TimelineTrack.class.getSimpleName() + " : "; private final TimelineTrackBO timelineTrackBO; /** * Instantiates a new TimelineTrack object * * @param timelineTrackBO the parsed TimelineTrack object * @param sequence the sequence referred by this TimelineTrack object */ public TimelineTrack(TimelineTrackBO timelineTrackBO, Sequence sequence) { super(timelineTrackBO, sequence); this.timelineTrackBO = timelineTrackBO; } /** * Getter for the numerator of this Timeline Track's edit rate * @return the numerator of this Timeline Track's edit rate */ public long getEditRateNumerator() { return this.timelineTrackBO.edit_rate.getNumerator(); } /** * Getter for the denominator of this Timeline Track's edit rate * @return the denominator of this Timeline Track's edit rate */ public long getEditRateDenominator() { return this.timelineTrackBO.edit_rate.getDenominator(); } /** * Getter for the Origin property of this TimelineTrack * @return a long integer representing the origin property of this timeline track */ public long getOrigin(){ return this.timelineTrackBO.origin; } /** * A method that returns a string representation of a Timeline Track object * * @return string representing the object */ public String toString() { return this.timelineTrackBO.toString(); } /** * Object corresponding to a parsed Timeline Track structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class TimelineTrackBO extends GenericTrackBO { @MXFProperty(size=0) private final CompoundDataTypes.Rational edit_rate = null; @MXFProperty(size=8) private final Long origin = null; //Position type /** * Instantiates a new parsed TimelineTrack object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public TimelineTrackBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header, imfErrorLogger); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); postPopulateCheck(); if (this.edit_rate == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, TimelineTrack.ERROR_DESCRIPTION_PREFIX + "edit_rate is null"); } } /** * A method that returns a string representation of a Timeline Track object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); sb.append("================== EditRate ======================\n"); sb.append(this.edit_rate.toString()); sb.append(String.format("origin = %d%n", this.origin)); return sb.toString(); } } }
5,141
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/SoundFieldGroupLabelSubDescriptor.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.utils.ByteProvider; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to SoundFieldGroupLabelSubDescriptor structural metadata set defined in st377-4:2012 */ @Immutable public final class SoundFieldGroupLabelSubDescriptor extends SubDescriptor { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + SoundFieldGroupLabelSubDescriptor.class.getSimpleName() + " : "; private final SoundFieldGroupLabelSubDescriptorBO soundFieldGroupLabelSubDescriptorBO; /** * Constructor for a SoundFieldGroupLabelSubDescriptor object * @param soundFieldGroupLabelSubDescriptorBO the parsed SoundFieldGroupLabelSubDescriptor object */ public SoundFieldGroupLabelSubDescriptor(SoundFieldGroupLabelSubDescriptorBO soundFieldGroupLabelSubDescriptorBO) { this.soundFieldGroupLabelSubDescriptorBO = soundFieldGroupLabelSubDescriptorBO; } /** * Getter for the MCALabelDictionary ID referred by this SoundFieldGroupLabelSubDescriptor object * @return the MCALabelDictionary ID referred by this SoundFieldGroupLabelSubDescriptor object */ public MXFUID getMCALabelDictionaryId() { return this.soundFieldGroupLabelSubDescriptorBO.mca_label_dictionary_id.getULAsMXFUid(); } /** * Getter for the MCALink Id that links the instances of the MCALabelSubDescriptors * @return the MCALink Id that links the instances of the MCALabelSubDescriptors */ public MXFUID getMCALinkId() { if(this.soundFieldGroupLabelSubDescriptorBO.mca_link_id == null) { return null; } return new MXFUID(this.soundFieldGroupLabelSubDescriptorBO.mca_link_id); } /** * A getter for the spoken language in this SubDescriptor * @return string representing the spoken language as defined in RFC-5646 */ public String getRFC5646SpokenLanguage(){ return this.soundFieldGroupLabelSubDescriptorBO.rfc_5646_spoken_language; } /** * A getter for the audio content kind * @return string representing the audio content kind */ public String getAudioContentKind(){ return this.soundFieldGroupLabelSubDescriptorBO.getMCAAudioContentKind(); } /** * A method that returns a string representation of a SoundFieldGroupLabelSubDescriptor object * * @return string representing the object */ public String toString() { return this.soundFieldGroupLabelSubDescriptorBO.toString(); } /** * Object corresponding to a parsed SoundFieldGroupLabelSubDescriptor structural metadata set defined in st377-4:2012 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class SoundFieldGroupLabelSubDescriptorBO extends MCALabelSubDescriptor.MCALabelSubDescriptorBO { //@MXFProperty(size=0, charset="UTF-16") protected final String group_of_soundfield_groups_linkID = null; /** * Instantiates a new parsed SoundFieldGroupLabelSubDescriptor object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public SoundFieldGroupLabelSubDescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, SoundFieldGroupLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.mca_label_dictionary_id == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, SoundFieldGroupLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "mca_label_dictionary_id is null"); } if (this.mca_link_id == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, SoundFieldGroupLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "mca_link_id is null"); } if (this.mca_tag_symbol == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, SoundFieldGroupLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "mca_tag_symbol is null"); } } } }
5,142
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/JPEG2000PictureComponent.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.header; import com.netflix.imflibrary.annotations.MXFProperty; import javax.annotation.concurrent.Immutable; import java.io.IOException; /** * Object model corresponding to JPEG2000PictureComponent as defined in ISO/IEC 15444-1 Annex A.5.1 */ @Immutable public final class JPEG2000PictureComponent { private final JPEG2000PictureComponentBO componentBO; /** * Constructor for a JPEG2000PictureComponent object * @param componentBO the parse JPEG2000PictureComponent object */ public JPEG2000PictureComponent(JPEG2000PictureComponentBO componentBO){ this.componentBO = componentBO; } /** * Object corresponding to a parsed JPEG2000PictureComponent as defined in ISO/IEC 15444-1 Annex A.5.1 */ @Immutable public static final class JPEG2000PictureComponentBO{ @MXFProperty(size=1) protected final Short sSiz; @MXFProperty(size=1) protected final Short xrSiz; @MXFProperty(size=1) protected final Short yrSiz; /** * Instantiates a new parsed JPEG2000PictureComponent object * * @param bytes the byte array corresponding to the 3 fields * @throws IOException - any I/O related error will be exposed through an IOException */ public JPEG2000PictureComponentBO(byte[] bytes) throws IOException { sSiz = (short)((int)bytes[0] & 0xFF); xrSiz = (short)((int)bytes[1] & 0xFF); yrSiz = (short)((int)bytes[2] & 0xFF); } } }
5,143
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/ACESPictureSubDescriptor.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.st0377.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.st0377.CompoundDataTypes; import com.netflix.imflibrary.utils.ByteProvider; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to ACESPictureSubDescriptor as defined in st429-4:2006 */ @Immutable public final class ACESPictureSubDescriptor extends SubDescriptor { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + ACESPictureSubDescriptor.class.getSimpleName() + " : "; private final ACESPictureSubDescriptorBO subDescriptorBO; /** * Constructor for a ACESPictureSubDescriptor object * @param subDescriptorBO the parsed ACESPictureSubDescriptor object */ public ACESPictureSubDescriptor(ACESPictureSubDescriptorBO subDescriptorBO){ this.subDescriptorBO = subDescriptorBO; } /** * A method that returns a string representation of a ACESPictureSubDescriptor object * * @return string representing the object */ public String toString() { return this.subDescriptorBO.toString(); } /** * Object corresponding to a parsed ACESPictureSubDescriptor as defined in st2067-50 */ @Immutable public static final class ACESPictureSubDescriptorBO extends SubDescriptorBO{ @MXFProperty(size=0, charset="UTF-16") private final String aces_authoring_information = null; @MXFProperty(size=12) private final byte[] aces_mastering_display_primaries = null; @MXFProperty(size=4) private final byte[] aces_mastering_white = null; @MXFProperty(size=4) private final Integer aces_max_luminance = null; @MXFProperty(size=4) private final Integer aces_min_luminance = null; /** * Instantiates a new ACESPictureSubDescriptor ByteObject. * * @param header the header * @param byteProvider the mxf byte provider * @param localTagToUIDMap the local tag to uID map * @param imfErrorLogger the imf error logger * @throws IOException - any I/O related error will be exposed through an IOException */ public ACESPictureSubDescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, ACESPictureSubDescriptor.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } } /** * A method that returns a string representation of a ACESPictureSubDescriptorB0 object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== ACESPictureSubDescriptor ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("aces_authoring_information = %s", this.aces_authoring_information)); String aces_mastering_display_primariesString = ""; if (aces_mastering_display_primaries != null) { for(byte b: aces_mastering_display_primaries){ aces_mastering_display_primariesString = aces_mastering_display_primariesString.concat(String.format("%02x", b)); } } sb.append(String.format("aces_mastering_display_primaries = %s", aces_mastering_display_primariesString)); String aces_mastering_whiteString = ""; if (aces_mastering_white != null) { for(byte b: aces_mastering_white){ aces_mastering_whiteString = aces_mastering_whiteString.concat(String.format("%02x", b)); } } sb.append(String.format("aces_mastering_whiteString = %s", aces_mastering_whiteString)); sb.append(String.format("aces_max_luminance = %d", this.aces_max_luminance)); sb.append(String.format("aces_min_luminance = %d", this.aces_min_luminance)); return sb.toString(); } } }
5,144
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/JPEG2000PictureSubDescriptor.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.st0377.CompoundDataTypes; import com.netflix.imflibrary.utils.ByteProvider; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to JPEG2000PictureSubDescriptor as defined in st429-4:2006 */ @Immutable public final class JPEG2000PictureSubDescriptor extends SubDescriptor { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + JPEG2000PictureSubDescriptor.class.getSimpleName() + " : "; private final JPEG2000PictureSubDescriptorBO subDescriptorBO; /** * Constructor for a JPEG2000PictureSubDescriptor object * @param subDescriptorBO the parsed JPEG2000PictureSubDescriptor object */ public JPEG2000PictureSubDescriptor(JPEG2000PictureSubDescriptorBO subDescriptorBO){ this.subDescriptorBO = subDescriptorBO; } /** * A method that returns a string representation of a JPEG2000PictureSubDescriptor object * * @return string representing the object */ public String toString() { return this.subDescriptorBO.toString(); } /** * Object corresponding to a parsed JPEG2000PictureSubDescriptor as defined in st429-4-2006 */ @Immutable public static final class JPEG2000PictureSubDescriptorBO extends SubDescriptorBO{ @MXFProperty(size=16) protected final byte[] generation_uid = null; @MXFProperty(size=2) protected final Short rSiz = null; @MXFProperty(size=4) protected final Integer xSiz = null; @MXFProperty(size=4) protected final Integer ySiz = null; @MXFProperty(size=4) protected final Integer xoSiz = null; @MXFProperty(size=4) protected final Integer yoSiz = null; @MXFProperty(size=4) protected final Integer xtSiz = null; @MXFProperty(size=4) protected final Integer ytSiz = null; @MXFProperty(size=4) protected final Integer xtoSiz = null; @MXFProperty(size=4) protected final Integer ytoSiz = null; @MXFProperty(size=2) protected final Short cSiz = null; @MXFProperty(size=0, depends=true) private final CompoundDataTypes.MXFCollections.MXFCollection<JPEG2000PictureComponent.JPEG2000PictureComponentBO> picture_component_sizing = null; @MXFProperty(size=0, depends=false) private final byte[] coding_style_default = null; @MXFProperty(size=0, depends=false) private final byte[] quantisation_default = null; /** * Instantiates a new JPEG2000 picture sub descriptor ByteObject. * * @param header the header * @param byteProvider the mxf byte provider * @param localTagToUIDMap the local tag to uID map * @param imfErrorLogger the imf error logger * @throws IOException - any I/O related error will be exposed through an IOException */ public JPEG2000PictureSubDescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, JPEG2000PictureSubDescriptor.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } } /** * A method that returns a string representation of a JPEG2000PictureSubDescriptorBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== JPEG2000PictureSubDescriptor ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("rSiz = %d", this.rSiz)); sb.append(String.format("xSiz = %d", this.xSiz)); sb.append(String.format("ySiz = %d", this.ySiz)); sb.append(String.format("xoSiz = %d", this.xoSiz)); sb.append(String.format("yoSiz = %d", this.yoSiz)); sb.append(String.format("xtSiz = %d", this.xtSiz)); sb.append(String.format("ytSiz = %d", this.ytSiz)); sb.append(String.format("xtoSiz = %d", this.xtoSiz)); sb.append(String.format("ytoSiz = %d", this.ytoSiz)); sb.append(String.format("cSiz = %d", this.cSiz)); sb.append(this.picture_component_sizing.toString()); String codingStyleDefaultString = ""; for(byte b: coding_style_default){ codingStyleDefaultString = codingStyleDefaultString.concat(String.format("%02x", b)); } sb.append(String.format("coding_style_default = %s", codingStyleDefaultString)); String quantisationDefaultString = ""; for(byte b: coding_style_default){ quantisationDefaultString = quantisationDefaultString.concat(String.format("%02x", b)); } sb.append(String.format("quantisation_default = %s", quantisationDefaultString)); return sb.toString(); } } }
5,145
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/Preface.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.st0377.CompoundDataTypes; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to Preface structural metadata set defined in st377-1:2011 */ @Immutable public final class Preface extends InterchangeObject { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + Preface.class.getSimpleName() + " : "; private final PrefaceBO prefaceBO; private final GenericPackage primaryPackage; private final ContentStorage contentStorage; /** * Instantiates a new Preface. * * @param prefaceBO the parsed Preface object * @param primaryPackage the primary package referred by this Preface object * @param contentStorage the ContentStorage object referred by this Preface object */ public Preface(PrefaceBO prefaceBO, GenericPackage primaryPackage, ContentStorage contentStorage) { this.prefaceBO = prefaceBO; this.primaryPackage = primaryPackage; this.contentStorage = contentStorage; } /** * Getter for the PrimaryPackage object referred by this Preface object in the MXF file * @return the PrimaryPackage object referred by this Preface object in the MXF file */ public GenericPackage getPrimaryPackage() { return this.primaryPackage; } /** * Getter for the ContentStorage object referred by this Preface object in the MXF file * @return the ContentStorage object referred by this Preface object in the MXF file */ public ContentStorage getContentStorage() { return this.contentStorage; } /** * Getter for the OperationalPattern that this MXF file complies to * @return the OperationalPattern that this MXF file complies to */ public UL getOperationalPattern() { return this.prefaceBO.operational_pattern; } /** * Getter for a list of labels of EssenceContainers used in or referenced by this MXF file * @return list of labels of EssenceContainers used in or referenced by this MXF file */ public int getNumberOfEssenceContainerULs() { return this.prefaceBO.essencecontainers.size(); } /** * Getter for a list of UL of Specifications to which this MXF file complies * @return list of UL of Specifications to which this MXF file complies */ public CompoundDataTypes.MXFCollections.MXFCollection<UL> getConformstoSpecificationsULs() { return this.prefaceBO.conforms_to_specifications; } /** * A method that returns a string representation of a Preface object * @return string representing the object */ public String toString() { return this.prefaceBO.toString(); } /** * Object corresponding to a parsed Preface structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class PrefaceBO extends InterchangeObjectBO { @MXFProperty(size=8) private final byte[] last_modified_date = null; @MXFProperty(size=2) private final byte[] version = null; @MXFProperty(size=16, depends=true) private final byte[] primary_package = null; //In-file Weak Ref @MXFProperty(size=16, depends=true) private final StrongRef content_storage = null; @MXFProperty(size=16) private final UL operational_pattern = null; @MXFProperty(size=0) private final CompoundDataTypes.MXFCollections.MXFCollection<UL> essencecontainers = null; @MXFProperty(size=0) private final CompoundDataTypes.MXFCollections.MXFCollection<UL> dm_schemes = null; @MXFProperty(size=0) private final CompoundDataTypes.MXFCollections.MXFCollection<UL> conforms_to_specifications = null; /** * Instantiates a new parsed Preface object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public PrefaceBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, Preface.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.content_storage == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, Preface.ERROR_DESCRIPTION_PREFIX + "content_storage is null"); } if (this.operational_pattern == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, Preface.ERROR_DESCRIPTION_PREFIX + "operational_pattern is null"); } if (this.essencecontainers == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, Preface.ERROR_DESCRIPTION_PREFIX + "essencecontainers is null"); } } /** * Getter for the PrimaryPackage structural metadata set instance UID in this MXF file * @return the PrimaryPackage structural metadata set instance UID in this MXF file */ public @Nullable MXFUID getPrimaryPackageInstanceUID() { if (this.primary_package != null) { return new MXFUID(this.primary_package); } return null; } /** * Getter for the ContentStorage structural metadata set instance UID in this MXF file * @return the ContentStorage structural metadata set instance UID in this MXF file */ public @Nullable MXFUID getContentStorageInstanceUID() { if (this.content_storage != null) { return this.content_storage.getInstanceUID(); } return null; } /** * A method that returns a string representation of a PrefaceBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== Preface ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("last_modified_date = 0x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.last_modified_date[0], this.last_modified_date[1], this.last_modified_date[2], this.last_modified_date[3], this.last_modified_date[4], this.last_modified_date[5], this.last_modified_date[6], this.last_modified_date[7])); sb.append(String.format("version = 0x%02x%02x%n", this.version[0], this.version[1])); sb.append(String.format("content_storage = %s%n", this.content_storage.toString())); sb.append(String.format("operational_pattern = %s%n", this.operational_pattern.toString())); sb.append(this.essencecontainers.toString()); sb.append(this.dm_schemes.toString()); if (this.conforms_to_specifications != null) sb.append(this.conforms_to_specifications.toString()); return sb.toString(); } } }
5,146
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/GenericTrack.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.annotations.MXFProperty; /** * Object model corresponding to GenericTrack structural metadata set defined in st377-1:2011 */ public abstract class GenericTrack extends InterchangeObject { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + GenericTrack.class.getSimpleName() + " : "; private final Sequence sequence; private final GenericTrackBO genericTrackBO; public GenericTrack(GenericTrackBO genericTrackBO, Sequence sequence) { this.sequence = sequence; this.genericTrackBO = genericTrackBO; } /** * Getter for the instance UID of this TimelineTrack * @return the instance UID of this TimelineTrack */ public MXFUID getInstanceUID() { return new MXFUID(this.genericTrackBO.instance_uid); } /** * Getter for the UID of the sequence descriptive metadata set referred by this Timeline Track * @return the UID of the sequence descriptive metadata set referred by this Timeline Track */ public MXFUID getSequenceUID() { return this.genericTrackBO.sequence.getInstanceUID(); } /** * Getter for the Sequence descriptive metadata set referred by this Timeline Track * @return the Sequence descriptive metadata set referred by this Timeline Track */ public Sequence getSequence() { return this.sequence; } @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public abstract static class GenericTrackBO extends InterchangeObjectBO { /** * The Track _ id. */ @MXFProperty(size=4) protected final Long track_id = null; /** * The Track _ number. */ @MXFProperty(size=4) protected final Long track_number = null; /** * The Sequence. */ @MXFProperty(size=16, depends=true) protected final StrongRef sequence = null; private final IMFErrorLogger imfErrorLogger; /** * Instantiates a new Generic track ByteObject. * * @param header the header */ GenericTrackBO(KLVPacket.Header header, IMFErrorLogger imfErrorLogger) { super(header); this.imfErrorLogger = imfErrorLogger; } /** * Getter for the UID of the sequence descriptive metadata set referred by this Track * @return the UID of the sequence descriptive metadata set referred by this Track */ public MXFUID getSequenceUID() { return this.sequence.getInstanceUID(); } public void postPopulateCheck() { if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.sequence == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, ERROR_DESCRIPTION_PREFIX + "sequence is null"); } } /** * A method that returns a string representation of a Generic Track object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== GenericTrack ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("track_id = 0x%08x(%d)%n", this.track_id, this.track_id)); sb.append(String.format("track_number = 0x%08x(%d)%n", this.track_number, this.track_number)); sb.append(String.format("sequence = %s%n", this.sequence.toString())); return sb.toString(); } } }
5,147
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/GenericSoundEssenceDescriptor.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.exceptions.MXFException; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.st0377.CompoundDataTypes; /** * Object model corresponding to GenericSoundEssenceDescriptor structural metadata set defined in st377-1:2011 */ public abstract class GenericSoundEssenceDescriptor extends FileDescriptor{ public enum ElectroSpatialFormulation { TWO_CHANNEL_MODE_DEFAULT(0), TWO_CHANNEL_MODE(1), SINGLE_CHANNEL_MODE(2), PRIMARY_SECONDARY_MODE(3), STEREOPHONIC_MODE(4), SINGLE_CHANNEL_DOUBLE_FREQUENCY_MODE(7), STEREO_LEFT_CHANNEL_DOUBLE_FREQUENCY_MODE(8), STEREO_RIGHT_CHANNEL_DOUBLE_FREQUENCY_MODE(9), MULTI_CHANNEL_MODE(15); private final Short mode; ElectroSpatialFormulation(int mode) { this.mode = (short)mode; } public Short value() { return mode; } } private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + GenericSoundEssenceDescriptor.class.getSimpleName() + " : "; protected GenericSoundEssenceDescriptorBO genericSoundEssenceDescriptorBO; /** * Getter for the audio sampling rate numerator of this WaveAudioEssenceDescriptor * * @return audio sampling rate numerator in the inclusive range [1, Integer.MAX_VALUE] * @throws MXFException when audio sampling rate numerator is out of range */ public int getAudioSamplingRateNumerator() throws MXFException { long value = this.genericSoundEssenceDescriptorBO.audio_sampling_rate.getNumerator(); if ((value <=0) || (value > Integer.MAX_VALUE)) { throw new MXFException(String.format("Observed audio sampling rate numerator = %d, which is not supported at this time", value)); } return (int)value; } /** * Getter for the audio sampling rate denominator of this WaveAudioEssenceDescriptor * * @return audio sampling rate denominator in the inclusive range [1, Integer.MAX_VALUE] * @throws MXFException when audio sampling rate denominator is out of range */ public int getAudioSamplingRateDenominator() throws MXFException { long value = this.genericSoundEssenceDescriptorBO.audio_sampling_rate.getDenominator(); if ((value <=0) || (value > Integer.MAX_VALUE)) { throw new MXFException(String.format("Observed audio sampling rate denominator = %d, which is not supported at this time", value)); } return (int)value; } /** * Getter for the channel count of this WaveAudioEssenceDescriptor * * @return channel count in the inclusive range [1, Integer.MAX_VALUE] * @throws MXFException when channel count is out of range */ public int getChannelCount() throws MXFException { long value = this.genericSoundEssenceDescriptorBO.channelcount; if ((value <0) || (value > Integer.MAX_VALUE)) { throw new MXFException(String.format("Observed channel count = %d, which is not supported at this time", value)); } return (int)value; } /** * Getter for the quantization bits of this WaveAudioEssenceDescriptor * * @return quantization bits in the inclusive range [1, Integer.MAX_VALUE] * @throws MXFException when quantization bits is out of range */ public int getQuantizationBits() throws MXFException { long value = this.genericSoundEssenceDescriptorBO.quantization_bits; if ((value <=0) || (value > Integer.MAX_VALUE)) { throw new MXFException(String.format("Observed quantization bits = %d, which is not supported at this time", value)); } return (int)value; } /** * Getter for Codec UL (can be null) * @return Codec UL (can be null) */ public UL getCodec() { return this.genericSoundEssenceDescriptorBO.getCodecUL(); } /** * Getter for Sound Essence Coding UL (can be null) * @return Sound Essence Coding UL (can be null) */ public UL getSoundEssenceCoding() { return this.genericSoundEssenceDescriptorBO.getSoundEssenceCodingUL(); } /** * Getter for Electro-Spatial Formulation (can be null) * @return Electro-Spatial Formulation (can be null) */ public ElectroSpatialFormulation getElectroSpatialFormulation() { return this.genericSoundEssenceDescriptorBO.getElectroSpatialFormulation(); } /** * Getter for Reference Audio Alignment Level (can be null) * @return Reference Audio Alignment Level (can be null) */ public Short getReferenceAudioAlignmentLevel() { return this.genericSoundEssenceDescriptorBO.getReferenceAudioAlignmentLevel(); } /** * Getter for the Reference Image Edit Rate (can be null) * @return Rational for Reference Image Edit Rate (can be null) */ public CompoundDataTypes.Rational getReferenceImageEditRate() { return this.genericSoundEssenceDescriptorBO.getReferenceImageEditRate(); } /** * Getter for the Essence Container UL of this FileDescriptor * @return a UL representing the Essence Container */ public UL getEssenceContainerUL(){ return this.genericSoundEssenceDescriptorBO.getEssenceContainerUL(); } public static abstract class GenericSoundEssenceDescriptorBO extends FileDescriptorBO{ @MXFProperty(size=0) protected final CompoundDataTypes.Rational audio_sampling_rate = null; @MXFProperty(size=4) protected final Long channelcount = null; @MXFProperty(size=4) protected final Long quantization_bits = null; @MXFProperty(size=16) protected final UL sound_essence_coding = null; @MXFProperty(size=8) protected final CompoundDataTypes.Rational reference_image_edit_rate = null; @MXFProperty(size=1) protected final Short reference_audio_alignment_level = null; @MXFProperty(size=1) protected final ElectroSpatialFormulation electro_spatial_formulation = null; private final IMFErrorLogger imfErrorLogger; /** * Constructor for a File descriptor ByteObject. * * @param header the MXF KLV header (Key and Length field) * @param imfErrorLogger logger for recording any parsing errors */ public GenericSoundEssenceDescriptorBO(final KLVPacket.Header header, IMFErrorLogger imfErrorLogger) { super(header); this.imfErrorLogger = imfErrorLogger; } public void postPopulateCheck() { if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, GenericSoundEssenceDescriptor.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.audio_sampling_rate == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, GenericSoundEssenceDescriptor.ERROR_DESCRIPTION_PREFIX + "audio_sampling_rate is null"); } if (this.channelcount == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, GenericSoundEssenceDescriptor.ERROR_DESCRIPTION_PREFIX + "channelcount is null"); } if (this.quantization_bits == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, GenericSoundEssenceDescriptor.ERROR_DESCRIPTION_PREFIX + "quantization_bits is null"); } } /** * Accessor for the Essence Container UL of this FileDescriptor * @return a UL representing the Essence Container */ public UL getSoundEssenceCodingUL(){ return this.sound_essence_coding; } /** * Accessor for the Essence Container UL of this FileDescriptor * @return a UL representing the Essence Container */ public ElectroSpatialFormulation getElectroSpatialFormulation(){ return this.electro_spatial_formulation; } /** * Accessor for the Reference Audio Alignment Level of this Generic Sound Essence Descriptor * @return a Short representing the Reference Audio Alignment Level of this Generic Sound Essence Descriptor */ public Short getReferenceAudioAlignmentLevel(){ return this.reference_audio_alignment_level; } /** * Accessor for the Reference Image Edit Rate for this Generic Sound Essence Descriptor * @return a Rational representing the Reference Image Edit Rate for this Generic Sound Essence Descriptor */ public CompoundDataTypes.Rational getReferenceImageEditRate(){ return this.reference_image_edit_rate; } /** * A method that compares this GenericSoundEssenceDescriptorBO with the object that was passed in and returns true/false depending on whether the objects * match field for field. * Note: If the object passed in is not an instance of a GenericSoundEssenceDescriptorBO this method would return * false. * @param other the object that this parsed GenericSoundEssenceDescriptorBO should be compared with * @return result of comparing this parsed GenericSoundEssenceDescriptorBO with the object that was passed in */ public boolean equals(Object other) { if(!(other instanceof GenericSoundEssenceDescriptorBO)) { return false; } GenericSoundEssenceDescriptorBO otherObject = (GenericSoundEssenceDescriptorBO)other; if ((this.audio_sampling_rate == null) || (!this.audio_sampling_rate.equals(otherObject.audio_sampling_rate))) { return false; } if ((this.channelcount== null) || (!this.channelcount.equals(otherObject.channelcount))) { return false; } if ((this.quantization_bits == null) || (!this.quantization_bits.equals(otherObject.quantization_bits))) { return false; } return true; } /** * Getter for the sum of hash codes of AudioSamplingRate, Channel Count, Quantization Bits * of this GenericSoundEssenceDescriptor * @return the sum of hash codes of AudioSamplingRate, Channel Count, Quantization Bits and Block Align fields * of this WaveAudioEssenceDescriptor */ public int hashCode() { return this.audio_sampling_rate.hashCode() + this.channelcount.hashCode() + this.quantization_bits.hashCode(); } /** * A method that returns a string representation of a GenericSoundEssenceDescriptorBO object * for use by derived classes * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("================== %s ======================%n", GenericSoundEssenceDescriptor.class.getSimpleName())); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append("================== SampleRate ======================\n"); sb.append(this.sample_rate.toString()); sb.append(String.format("essence_container = %s%n", this.essence_container.toString())); sb.append("================== AudioSamplingRate ======================\n"); sb.append(this.audio_sampling_rate.toString()); sb.append(String.format("channelcount = %d%n", this.channelcount)); sb.append(String.format("quantization_bits = %d%n", this.quantization_bits)); if (this.sound_essence_coding != null) { sb.append(String.format("sound_essence_coding = %s%n", this.sound_essence_coding.toString())); } if (this.electro_spatial_formulation != null) { sb.append(String.format("electro_spatial_formulation = %s%n", this.electro_spatial_formulation.toString())); } return sb.toString(); } } }
5,148
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/UL.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.exceptions.IMFException; import java.util.Arrays; /** * Object model corresponding to a Universal Label defined in st377-1:2011 */ public class UL { private static final String UL_as_a_URN_PREFIX = "urn:smpte:ul:"; private final byte[] ul; /** * Constructor for a UL * @param ul byte array corresponding to the Universal Label bytes */ public UL(byte[] ul){ this.ul = Arrays.copyOf(ul, ul.length); } /** * MXFUid representation of a UL * @return The UL represented as a MXFUId */ public MXFUID getULAsMXFUid(){ return new MXFUID(this.ul); } /** * Getter for the ul byte[] representing this UL * @return byte[] representation of a UL */ public byte[] getULAsBytes(){ return Arrays.copyOf(this.ul, this.ul.length); } /** * Returns the value of a byte of the UL * @param index Index of a byte within the UL, with 0 corresponding to the first byte * @return byte `index` of the UL */ public byte getByte(int index){ return this.ul[index]; } /** * Getter for UL length * @return length of the UL in bytes */ public int getLength(){ return this.ul.length; } /** * toString() method * @return string representation of the UL object */ public String toString(){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(String.format("0x")); for(byte b : this.ul) { stringBuilder.append(String.format("%02x", b)); } return stringBuilder.toString(); } /** * toStringBytes() method * @return string representation of the UL object with a "." separation between bytes */ public String toStringBytes(){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(String.format("%02x", this.ul[0])); for(int i = 1; i < this.ul.length; i++) { stringBuilder.append(String.format(".%02x", this.ul[i])); } return stringBuilder.toString(); } /** * A helper method to return the UUID without the "urn:uuid:" prefix * @param ULasURN a urn:uuid type * @return a UL without the "urn:smpte:ul:" prefix */ public static UL fromULAsURNStringToUL(String ULasURN) { if (!ULasURN.startsWith(UL.UL_as_a_URN_PREFIX)) { IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl(); imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.UUID_ERROR, IMFErrorLogger.IMFErrors .ErrorLevels.NON_FATAL, String.format("Input UUID %s " + "does not start with %s", ULasURN, UL .UL_as_a_URN_PREFIX)); throw new IMFException(String.format("Input UUID %s does not start with %s", ULasURN, UL .UL_as_a_URN_PREFIX), imfErrorLogger); } String ulValue = ULasURN.split(UL.UL_as_a_URN_PREFIX)[1].replace(".", ""); byte[] bytes = new byte[16]; for( int i =0; i < 16; i++) { bytes[i] = (byte)Integer.parseInt(ulValue.substring(i*2, i*2+2), 16); } return new UL(bytes); } /** * Compares this UL to another UL, ignoring specific bytes based on a mask * * @param ul Other UL to compare * @param byteMask 16-bit mask, where octet[n] of the UL is ignored if bit[15 - n] is 0 * @return true if the ULs are equal */ public boolean equalsWithMask(UL ul, int byteMask) { for (int i = 0; i < 16; i++) { if ((byteMask & 0x8000) != 0 && this.ul[i] != ul.ul[i]) return false; byteMask = byteMask << 1; } return true; } /** * A Java compliant implementation of the hashCode() method * * @return integer containing the hash code corresponding to this object */ @Override public int hashCode() { return Arrays.hashCode(ul); } /** * Compares this object to the specified object * * @param other the object to be compared * * @return true if the objects are the same; false otherwise */ public boolean equals(Object other) { if ((null == other) || (other.getClass() != this.getClass())) return false; UL id = (UL)other; return Arrays.equals(this.ul, id.getULAsBytes()); } }
5,149
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/AudioChannelLabelSubDescriptor.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to AudioChannelLabelSubDescriptor structural metadata set defined in st377-4:2012 */ @Immutable public final class AudioChannelLabelSubDescriptor extends GenericDescriptor { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + AudioChannelLabelSubDescriptor.class.getSimpleName() + " : "; private final AudioChannelLabelSubDescriptorBO audioChannelLabelSubDescriptorBO; /** * Constructor for an AudioChannelLabelSubDescriptor object * @param audioChannelLabelSubDescriptorBO the parsed Audio channel label sub-descriptor object */ public AudioChannelLabelSubDescriptor(AudioChannelLabelSubDescriptorBO audioChannelLabelSubDescriptorBO) { this.audioChannelLabelSubDescriptorBO = audioChannelLabelSubDescriptorBO; } /** * Getter for the MCALabelDictionaryId of an AudioChannelLabelSubDescriptor object. * @return MCALabelDictionaryId of the AudioChannelLabelSubDescriptor object */ public MXFUID getMCALabelDictionaryId() { return this.audioChannelLabelSubDescriptorBO.mca_label_dictionary_id.getULAsMXFUid(); } public MXFUID getSoundfieldGroupLinkId() { if(this.audioChannelLabelSubDescriptorBO.soundfield_group_link_id == null) { return null; } return new MXFUID(this.audioChannelLabelSubDescriptorBO.soundfield_group_link_id); } /** * Getter for the MCALinkId field of an AudioChannelLabelSubDescriptor object. * @return MCALinkId of the AudioChannelLabelSubDescriptor object */ public MXFUID getMCALinkId() { if(this.audioChannelLabelSubDescriptorBO.mca_link_id == null) { return null; } return new MXFUID(this.audioChannelLabelSubDescriptorBO.mca_link_id); } /** * Getter for the MCAChannelId field of an AudioChannelLabelSubDescriptor object. * @return MCAChannelId of the AudioChannelLabelSubDescriptor object */ public Long getMCAChannelId() { return this.audioChannelLabelSubDescriptorBO.getMCAChannelID(); } /** * A method that returns a string representation of an AudioChannelLabelSubDescriptor object. * * @return string representing the object */ public String toString() { return this.audioChannelLabelSubDescriptorBO.toString(); } /** * A getter for the spoken language in this SubDescriptor * @return string representing the spoken language as defined in RFC-5646 */ public String getRFC5646SpokenLanguage(){ return this.audioChannelLabelSubDescriptorBO.rfc_5646_spoken_language; } /** * Object corresponding to a parsed AudioChannelLabelSubDescriptor structural metadata set defined in st377-4:2012 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class AudioChannelLabelSubDescriptorBO extends MCALabelSubDescriptor.MCALabelSubDescriptorBO { @MXFProperty(size=16) private final byte[] soundfield_group_link_id = null; //UUID /** * Instantiates a new parsed AudioChannelLabelSubDescriptor object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public AudioChannelLabelSubDescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, AudioChannelLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.mca_label_dictionary_id == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, AudioChannelLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "mca_label_dictionary_id is null"); } if (this.mca_link_id == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, AudioChannelLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "mca_link_id is null"); } if (this.mca_tag_symbol == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, AudioChannelLabelSubDescriptor.ERROR_DESCRIPTION_PREFIX + "mca_tag_symbol is null"); } } /** * A method that returns a string representation of the object. * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); if (this.soundfield_group_link_id != null) { sb.append(String.format("soundfield_group_link_id = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.soundfield_group_link_id[0], this.soundfield_group_link_id[1], this.soundfield_group_link_id[2], this.soundfield_group_link_id[3], this.soundfield_group_link_id[4], this.soundfield_group_link_id[5], this.soundfield_group_link_id[6], this.soundfield_group_link_id[7], this.soundfield_group_link_id[8], this.soundfield_group_link_id[9], this.soundfield_group_link_id[10], this.soundfield_group_link_id[11], this.soundfield_group_link_id[12], this.soundfield_group_link_id[13], this.soundfield_group_link_id[14], this.soundfield_group_link_id[15])); } return sb.toString(); } } }
5,150
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/CDCIPictureEssenceDescriptor.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to CDCIPictureEssenceDescriptor structural metadata set defined in st377-1:2011 */ @Immutable public final class CDCIPictureEssenceDescriptor extends GenericPictureEssenceDescriptor { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + CDCIPictureEssenceDescriptor.class.getSimpleName() + " : "; private final CDCIPictureEssenceDescriptorBO cdciPictureEssenceDescriptorBO; /** * Constructor for a CDCIPictureEssenceDescriptor object * @param cdciPictureEssenceDescriptorBO the parsed CDCI picture essence descriptor object */ public CDCIPictureEssenceDescriptor(CDCIPictureEssenceDescriptorBO cdciPictureEssenceDescriptorBO) { this.cdciPictureEssenceDescriptorBO = cdciPictureEssenceDescriptorBO; } /** * Getter for the Essence Container UL of this FileDescriptor * @return a UL representing the Essence Container */ public UL getEssenceContainerUL(){ return this.cdciPictureEssenceDescriptorBO.getEssenceContainerUL(); } /** * A method that returns a string representation of a CDCIPictureEssenceDescriptor object * * @return string representing the object */ public String toString() { return this.cdciPictureEssenceDescriptorBO.toString(); } /** * Object corresponding to a parsed CDCIPictureEssenceDescriptor structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class CDCIPictureEssenceDescriptorBO extends GenericPictureEssenceDescriptor.GenericPictureEssenceDescriptorBO { @MXFProperty(size=4) private final Long component_depth = null; @MXFProperty(size=4) private final Long horizontal_subsampling = null; @MXFProperty(size=4) private final Long vertical_subsampling = null; @MXFProperty(size=4) protected final Long black_ref_level = null; @MXFProperty(size=4) protected final Long white_ref_level = null; /** * Instantiates a new parsed CDCIPictureEssenceDescriptor object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public CDCIPictureEssenceDescriptorBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, CDCIPictureEssenceDescriptor.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } } /** * Accessor for the horizontal sampling * @return a long integer representing the horizontal sampling */ public Long getHorizontal_subsampling() { return horizontal_subsampling; } /** * Accessor for the vertical sampling * @return a long integer representing the vertical sampling */ public Long getVertical_subsampling() { return vertical_subsampling; } /** * Accessor for the BlackRefLevel UL * @return a long integer representing the luminance value for black */ public Long getBlackRefLevel(){ return this.black_ref_level; } /** * Accessor for the WhiteRefLevel UL * @return a long integer representing the luminance value for white */ public Long getWhiteRefLevel(){ return this.white_ref_level; } /** * A method that returns a string representation of a CDCIPictureEssenceDescriptorBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== CDCIPictureEssenceDescriptor ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append("================== SampleRate ======================\n"); sb.append(this.sample_rate.toString()); sb.append(String.format("essence_container = %s%n", this.essence_container.toString())); sb.append(String.format("frame_layout = %d%n", this.frame_layout)); sb.append(String.format("stored_width = %d%n", this.stored_width)); sb.append(String.format("stored_height = %d%n", this.stored_height)); sb.append("================== AspectRatio ======================\n"); sb.append(this.aspect_ratio.toString()); if (this.video_line_map != null) { sb.append(this.video_line_map.toString()); } sb.append(String.format("picture_essence_coding = %s%n", this.picture_essence_coding.toString())); sb.append(String.format("component_depth = %d%n", this.component_depth)); sb.append(String.format("horizontal_subsampling = %d%n", this.horizontal_subsampling)); sb.append(String.format("vertical_subsampling = %d%n", this.vertical_subsampling)); return sb.toString(); } } }
5,151
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/GenericPictureEssenceDescriptor.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.header; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.st0377.CompoundDataTypes; /** * Object model corresponding to GenericPictureEssenceDescriptor structural metadata set defined in st377-1:2011 */ public abstract class GenericPictureEssenceDescriptor extends FileDescriptor { public static final String rgbaDescriptorUL = "urn:smpte:ul:060e2b34.027f0101.0d010101.01012900"; public static final String cdciDescriptorUL = "urn:smpte:ul:060e2b34.027f0101.0d010101.01012800"; public static final String frameLayoutUL = "urn:smpte:ul:060e2b34.01010101.04010301.04000000"; public static final String frameLayoutTypeUL= "urn:smpte:ul:060e2b34.01040101.02010108.00000000"; public static final String storedWidthUL = "urn:smpte:ul:060e2b34.01010101.04010502.02000000"; public static final String storedHeightUL = "urn:smpte:ul:060e2b34.01010101.04010502.01000000"; public static final String sampleRateUL = "urn:smpte:ul:060e2b34.01010101.04060101.00000000"; public static final String storedF2OffsetUL = "urn:smpte:ul:060e2b34.01010105.04010302.08000000"; public static final String sampledWidthUL = "urn:smpte:ul:060e2b34.01010101.04010501.08000000"; public static final String sampledHeightUL = "urn:smpte:ul:060e2b34.01010101.04010501.07000000"; public static final String subdescriptorsUL = "urn:smpte:ul:060e2b34.01010109.06010104.06100000"; public static final String jpeg2000SubDescriptorUL = "urn:smpte:ul:060e2b34.027f0101.0d010101.01015a00"; public static final String j2cLayoutUL = "urn:smpte:ul:060e2b34.0101010e.04010603.0e000000"; public static final String rgbaComponentUL = "urn:smpte:ul:060e2b34.01040101.03010400.00000000"; public static final String componentSizeUL = "urn:smpte:ul:060e2b34.01040101.01010100.00000000"; public static final String codeUL = "urn:smpte:ul:060e2b34.01040101.0201010e.00000000"; public static final String rgbaComponentKindUL = "urn:smpte:ul:060e2b34.01040101.0201010e.00000000"; public static final String colorPrimariesUL = "urn:smpte:ul:060e2b34.01010109.04010201.01060100"; public static final String transferCharacteristicUL = "urn:smpte:ul:060e2b34.01010102.04010201.01010200"; public static final String codingEquationsUL = "urn:smpte:ul:060e2b34.01010102.04010201.01030100"; public static final String componentMinRefUL = "urn:smpte:ul:060e2b34.01010105.04010503.0c000000"; public static final String componentMaxRefUL = "urn:smpte:ul:060e2b34.01010105.04010503.0b000000"; public static final String blackRefLevelUL = "urn:smpte:ul:060e2b34.01010101.04010503.03000000"; public static final String whiteRefLevelUL = "urn:smpte:ul:060e2b34.01010101.04010503.04000000"; public static final String componentDepthUL = "urn:smpte:ul:060e2b34.01010102.04010503.0a000000"; public static final String horizontalSubSamplingUL = "urn:smpte:ul:060e2b34.01010101.04010501.05000000"; public static final String verticalSubSamplingUL = "urn:smpte:ul:060e2b34.01010102.04010501.10000000"; public static final String containerFormatUL = "urn:smpte:ul:060e2b34.01010102.06010104.01020000"; public static final String pictureEssenceCodingUL = "urn:smpte:ul:060e2b34.01010102.04010601.00000000"; //begin items constrained in 2065-5 or 2067-50 //Generic Picture Essence Descriptor constraints public static final String signalStandardUL = "urn:smpte:ul:060e2b34.01010105.04050113.00000000"; public static final String sampledXOffsetUL = "urn:smpte:ul:060e2b34.01010101.04010501.09000000"; public static final String sampledYOffsetUL = "urn:smpte:ul:060e2b34.01010101.04010501.0a000000"; public static final String displayWidthUL = "urn:smpte:ul:060e2b34.01010101.04010501.0c000000"; public static final String displayHeightUL = "urn:smpte:ul:060e2b34.01010101.04010501.0b000000"; public static final String displayXOffsetUL = "urn:smpte:ul:060e2b34.01010101.04010501.0d000000"; public static final String displayYOffsetUL = "urn:smpte:ul:060e2b34.01010101.04010501.0e000000"; public static final String displayF2OffsetUL = "urn:smpte:ul:060e2b34.01010105.04010302.07000000"; public static final String imageAspectRatioUL = "urn:smpte:ul:060e2b34.01010101.04010101.01000000"; public static final String activeFormatDescriptorUL = "urn:smpte:ul:060e2b34.01010105.04010302.09000000"; public static final String videoLineMapUL = "urn:smpte:ul:060e2b34.01010102.04010302.05000000"; public static final String alphaTransparencyUL = "urn:smpte:ul:060e2b34.01010102.05200102.00000000"; public static final String imageAlignmentOffsetUL = "urn:smpte:ul:060e2b34.01010102.04180101.00000000"; //The symbol is named ImageAlignmentFactor in ST0377-1:2011 public static final String imageStartOffsetUL = "urn:smpte:ul:060e2b34.01010102.04180102.00000000"; public static final String imageEndOffsetUL = "urn:smpte:ul:060e2b34.01010102.04180103.00000000"; public static final String fieldDominanceUL = "urn:smpte:ul:060e2b34.01010102.04010301.06000000"; //RGBA Picture Essence Descriptor constraints public static final String alphaMinRefUL = "urn:smpte:ul:060e2b34.01010105.04010503.0e000000"; public static final String alphaMaxRefUL = "urn:smpte:ul:060e2b34.01010105.04010503.0d000000"; public static final String scanningDirectionUL = "urn:smpte:ul:060e2b34.01010105.04010404.01000000"; public static final String pixelLayoutUL = "urn:smpte:ul:060e2b34.01010102.04010503.06000000"; public static final String paletteUL = "urn:smpte:ul:060e2b34.01010102.04010503.08000000"; public static final String paletteLayoutUL = "urn:smpte:ul:060e2b34.01010102.04010503.09000000"; //end items constrained in 2065-5 or 2067-50 //begin items defined in 2067-50 public static final String acesPictureSubDescriptorUL = "urn:smpte:ul:060e2b34.027f0101.0d010101.01017900"; public static final String acesAuthoringInformationUL = "urn:smpte:ul:060e2b34.0101010e.0401060a.01000000"; public static final String acesMasteringDisplayPrimariesUL = "urn:smpte:ul:060e2b34.0101010e.0401060a.02000000"; public static final String acesMasteringDisplayWhitePointChromaticityUL = "urn:smpte:ul:060e2b34.0101010e.0401060a.03000000"; public static final String acesMasteringDisplayDisplayMaximumLuminanceUL = "urn:smpte:ul:060e2b34.0101010e.0401060a.04000000"; public static final String acesMasteringDisplayDisplayMinimumLuminanceUL = "urn:smpte:ul:060e2b34.0101010e.0401060a.05000000"; public static final String targetFrameSubDescriptorUL = "urn:smpte:ul:060e2b34.027f0101.0d010101.01017a00"; public static final String targetFrameAncillaryResourceIDUL = "urn:smpte:ul:060e2b34.0101010e.04010609.01000000"; public static final String mediaTypeUL = "urn:smpte:ul:060e2b34.0101010e.04010609.02000000"; public static final String targetFrameIndexUL = "urn:smpte:ul:060e2b34.0101010e.04010609.03000000"; public static final String targetFrameTransferCharacteristicUL = "urn:smpte:ul:060e2b34.0101010e.04010609.04000000"; public static final String targetFrameColorPrimariesUL = "urn:smpte:ul:060e2b34.0101010e.04010609.05000000"; public static final String targetFrameComponentMaxRefUL = "urn:smpte:ul:060e2b34.0101010e.04010609.06000000"; public static final String targetFrameComponentMinRefUL = "urn:smpte:ul:060e2b34.0101010e.04010609.07000000"; public static final String targetFrameEssenceStreamIDUL = "urn:smpte:ul:060e2b34.0101010e.04010609.08000000"; public static final String acesPictureSubDescriptorInstanceIDUL = "urn:smpte:ul:060e2b34.0101010e.04010609.09000000"; public static final String targetFrameViewingEnvironmentUL = "urn:smpte:ul:060e2b34.0101010e.04010609.0a000000"; public static final String instanceID = "urn:smpte:ul:060e2b34.01010101.01011502.00000000"; //end items defined in 2067-50 //begin items defined in 379-2 public static final String containerConstraintsSubDescriptorUL = "urn:smpte:ul:060e2b34.027f0101.0d010101.01016700"; //begin items defined in 379-2 public static abstract class GenericPictureEssenceDescriptorBO extends FileDescriptorBO { @MXFProperty(size=1) protected final Short frame_layout = null; @MXFProperty(size=4) protected final Long stored_width = null; @MXFProperty(size=4) protected final Long stored_height = null; @MXFProperty(size=0) protected final CompoundDataTypes.Rational aspect_ratio = null; @MXFProperty(size=0) protected final CompoundDataTypes.MXFCollections.MXFCollection<Integer> video_line_map = null; @MXFProperty(size=16) protected final UL picture_essence_coding = null; @MXFProperty(size=16) protected final UL color_primaries = null; @MXFProperty(size=16) protected final UL coding_equations = null; @MXFProperty(size=16) protected final UL transfer_characteristic = null; /** * Constructor for a File descriptor ByteObject. * * @param header the MXF KLV header (Key and Length field) */ GenericPictureEssenceDescriptorBO(final KLVPacket.Header header) { super(header); } /** * Accessor for the ColorPrimaries UL * @return a UL representing the ColorPrimaries */ public UL getColorPrimariesUL(){ return this.color_primaries; } /** * Accessor for the CodingEquations UL * @return a UL representing the CodingEquations */ public UL getCodingEquationsUL(){ return this.coding_equations; } /** * Accessor for the TransferCharacteristic UL * @return a UL representing the TransferCharacteristic */ public UL getTransferCharacteristicUL(){ return this.transfer_characteristic; } } public static enum RGBAComponentType { Null(0), Red(0x52), Green(0x47), Blue(0x42), Luma(0x59), ChromaU(0x55), ChromaV(0x56), Alpha(0x41), Unknown(-1); private final Integer code; RGBAComponentType(Integer code) { this.code = code; } public static RGBAComponentType valueOf(Integer code) { for(RGBAComponentType cur : RGBAComponentType.values()) { if(cur.getCode().equals(code)) { return cur; } } return Unknown; } public Integer getCode() { return this.code;} } public static enum FrameLayoutType { FullFrame(0), SeparateFields(1), SingleField(2), MixedFields(3), SegmentedFrame(4), Unknown(-1); private final Integer value; FrameLayoutType(Integer value) { this.value = value; } public Integer getValue() { return this.value;} public static FrameLayoutType valueOf(Integer value) { for(FrameLayoutType frameLayout: FrameLayoutType.values()) { if(frameLayout.getValue().equals(value)) { return frameLayout; } } return Unknown; } } }
5,152
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/TimecodeComponent.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to TimecodeComponent structural metadata set defined in st377-1:2011 */ @Immutable public final class TimecodeComponent extends StructuralComponent { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + TimecodeComponent.class.getSimpleName() + " : "; private final TimecodeComponentBO timecodeComponentBO; /** * Constructor for a TimecodeComponent structural metadata set * @param timecodeComponentBO the parsed TimeCode Component object */ public TimecodeComponent(TimecodeComponentBO timecodeComponentBO) { this.timecodeComponentBO = timecodeComponentBO; } /** * Getter for the instance UID for this TimecodeComponent structural metadata set * @return the instance UID for this TimecodeComponent structural metadata set */ public MXFUID getInstanceUID() { return new MXFUID(this.timecodeComponentBO.instance_uid); } /** * A method that returns a string representation of a TimecodeComponent object * * @return string representing the object */ public String toString() { return this.timecodeComponentBO.toString(); } /** * Object corresponding to parsed TimecodeComponent structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class TimecodeComponentBO extends StructuralComponentBO { /** * Instantiates a new parsed TimecodeComponent object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public TimecodeComponentBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, TimecodeComponent.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } } /** * A method that returns a string representation of a TimecodeComponentBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== TimecodeComponent ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("data_definition = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.data_definition[0], this.data_definition[1], this.data_definition[2], this.data_definition[3], this.data_definition[4], this.data_definition[5], this.data_definition[6], this.data_definition[7], this.data_definition[8], this.data_definition[9], this.data_definition[10], this.data_definition[11], this.data_definition[12], this.data_definition[13], this.data_definition[14], this.data_definition[15])); sb.append(String.format("duration = %d%n", this.duration)); return sb.toString(); } } }
5,153
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/StructuralComponent.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.header; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.annotations.MXFProperty; /** * Object model corresponding to Structural Component structural metadata set defined in st377-1:2011 */ public abstract class StructuralComponent extends InterchangeObject { /** * Object corresponding to a parsed SourcePackage structural metadata set defined in st377-1:2011 */ @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public abstract static class StructuralComponentBO extends InterchangeObjectBO { /** * The Data _ definition. */ @MXFProperty(size=16) protected final byte[] data_definition = null; /** * The Duration. */ @MXFProperty(size=8) protected final Long duration = null; /** * Instantiates a new Structural component ByteObject. * * @param header the header */ StructuralComponentBO(KLVPacket.Header header) { super(header); } /** * Accessor for the duration * @return the duration of this structural component */ public Long getDuration(){ return this.duration; } } }
5,154
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/ContentStorage.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.MXFUID; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.st0377.CompoundDataTypes; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * Object model corresponding to ContentStorage structural metadata set defined in st377-1:2011 */ @Immutable public final class ContentStorage extends InterchangeObject { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + ContentStorage.class.getSimpleName() + " : "; private final ContentStorageBO contentStorageBO; private final List<GenericPackage> genericPackageList; private final List<EssenceContainerData> essenceContainerDataList; /** * Instantiates a new ContentStorage object * * @param contentStorageBO the parsed ContentStorage object * @param genericPackageList the list of generic packages referred by this ContentStorage object * @param essenceContainerDataList the list of essence container data sets referred by this ContentStorage object */ public ContentStorage(ContentStorageBO contentStorageBO, List<GenericPackage> genericPackageList, List<EssenceContainerData> essenceContainerDataList) { this.contentStorageBO = contentStorageBO; this.genericPackageList = Collections.unmodifiableList(genericPackageList); this.essenceContainerDataList = Collections.unmodifiableList(essenceContainerDataList); } /** * Getter for the GenericPackageList * @return a List of GenericPackages */ public List<GenericPackage> getGenericPackageList() { return this.genericPackageList; } public List<SourcePackage> getSourcePackageList() { List<SourcePackage> sourcePackages = new ArrayList<>(); for (GenericPackage genericPackage : this.genericPackageList) { if (genericPackage instanceof SourcePackage) { sourcePackages.add((SourcePackage)genericPackage); } } return sourcePackages; } /** * Getter for the EssenceContainerDataList * @return a List of references to EssenceContainerData sets used in the MXF file */ public List<EssenceContainerData> getEssenceContainerDataList() { return this.essenceContainerDataList; } /** * Getter for the PackageInstanceUIDs * @return a List of UID references to all the packages used in the MXF file */ public List<MXFUID> getPackageInstanceUIDs() { List<MXFUID> packageInstanceUIDs = new ArrayList<MXFUID>(); for (InterchangeObjectBO.StrongRef strongRef : this.contentStorageBO.packages.getEntries()) { packageInstanceUIDs.add(strongRef.getInstanceUID()); } return packageInstanceUIDs; } /** * Getter for the number of EssenceContainerData sets used in the MXF file * @return an integer representing the number of EssenceContainerData sets used in the MXF file */ public int getNumberOfEssenceContainerDataSets() { return this.contentStorageBO.essencecontainer_data.size(); } public String toString() { return this.contentStorageBO.toString(); } /** * Object corresponding to parsed ContentStorage structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class ContentStorageBO extends InterchangeObjectBO { @MXFProperty(size=0, depends=true) private final CompoundDataTypes.MXFCollections.MXFCollection<StrongRef> packages = null; @MXFProperty(size=0, depends=true) private final CompoundDataTypes.MXFCollections.MXFCollection<StrongRef> essencecontainer_data = null; private final List<MXFUID> packageInstanceUIDs = new ArrayList<>(); private final List<MXFUID> essenceContainerDataInstanceUIDs = new ArrayList<>(); /** * Instantiates a new parsed ContentStorage object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public ContentStorageBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, ContentStorage.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.packages == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, ContentStorage.ERROR_DESCRIPTION_PREFIX + "packages is null"); } else { for (StrongRef strongRef : this.packages.getEntries()) { this.packageInstanceUIDs.add(strongRef.getInstanceUID()); } } if (this.essencecontainer_data == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, ContentStorage.ERROR_DESCRIPTION_PREFIX + "essencecontainer_data is null"); } else { for (StrongRef strongRef : this.essencecontainer_data.getEntries()) { this.essenceContainerDataInstanceUIDs.add(strongRef.getInstanceUID()); } } } /** * Getter for the PackageInstanceUIDs * @return a cloned List of UID references to all the packages used in the MXF file */ public List<MXFUID> getPackageInstanceUIDs() { return Collections.unmodifiableList(this.packageInstanceUIDs); } /** * Getter for the PackageInstanceUIDs * @return a cloned List of UID references to all the EssenceContainerData sets used in the MXF file */ public List<MXFUID> getEssenceContainerDataInstanceUIDs() { return Collections.unmodifiableList(this.essenceContainerDataInstanceUIDs); } /** * A method that returns a string representation of a ContentStorageBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== ContentStorage ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(this.packages.toString()); sb.append(this.essencecontainer_data.toString()); return sb.toString(); } } }
5,155
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/package-info.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. * */ /** * Classes in this package correspond to object model for respective Structural Metadata sets defined * in st377-1:2011. All concrete classes in this package have a static nested class. Objects of the * respective static nested classes store literal values encountered in the MXF file bitstream. Objects * of the nesting classes realize the object model as well as relationships between different Structural * Metadata sets defined in st377-1:2011. * * For example, the "Preface" Structural Metadata set in the MXF file refers to a "ContentStorage" * Structural Metadata set by storing the value of the instance UID associated with the latter. * Correspondingly, {@link com.netflix.imflibrary.st0377.header.Preface.PrefaceBO} contains * {@code com.netflix.imflibrary.st0377.header.Preface.PrefaceBO.content_storage} field that holds the * same value as {@code com.netflix.imflibrary.st0377.header.ContentStorage.ContentStorageBO.instance_uid}. * The corresponding nesting {@link com.netflix.imflibrary.st0377.header.Preface} object then holds a * reference to the corresponding {@link com.netflix.imflibrary.st0377.header.ContentStorage} object * */ package com.netflix.imflibrary.st0377.header;
5,156
0
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0377/header/SourcePackage.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.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Object model corresponding to SourcePackage structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.SingularField", "PMD.UnusedPrivateField"}) public final class SourcePackage extends GenericPackage { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + SourcePackage.class.getSimpleName() + " : "; private final SourcePackageBO sourcePackageBO; private final List<GenericTrack> genericTracks; private final GenericDescriptor genericDescriptor; /** * Instantiates a new Source package. * * @param sourcePackageBO the parsed SourcePackage object * @param genericTracks the list of generic tracks referred by this SourcePackage object * @param genericDescriptor the generic descriptor referred by this SourcePackage object */ public SourcePackage(SourcePackageBO sourcePackageBO, List<GenericTrack> genericTracks, GenericDescriptor genericDescriptor) { super(sourcePackageBO); this.sourcePackageBO = sourcePackageBO; this.genericTracks = genericTracks; this.genericDescriptor = genericDescriptor; } /** * Getter for the instance UID for this Source Package * @return the instance UID for this Source Package represented as a MXFUid object */ public MXFUID getInstanceUID() { return new MXFUID(this.sourcePackageBO.instance_uid); } /** * Getter for the GenericDescriptor referred by this Source Package * @return the GenericDescriptor referred by this Source Package */ public GenericDescriptor getGenericDescriptor() { return this.genericDescriptor; } /** * Getter for the list of tracks referred by this Source Package * @return the list of tracks referred by this Source Package represented as MXFUid objects */ public List<MXFUID> getTrackInstanceUIDs() { List<MXFUID> trackInstanceUIDs = new ArrayList<MXFUID>(); for (InterchangeObjectBO.StrongRef strongRef : this.sourcePackageBO.tracks.getEntries()) { trackInstanceUIDs.add(strongRef.getInstanceUID()); } return trackInstanceUIDs; } /** * Getter for subset of generic tracks that are of type TimelineTrack * * @return the timeline tracks */ public List<TimelineTrack> getTimelineTracks() { List<TimelineTrack> timelineTracks = new ArrayList<>(); for (GenericTrack genericTrack : this.genericTracks) { if (genericTrack instanceof TimelineTrack) { timelineTracks.add((TimelineTrack)genericTrack); } } return timelineTracks; } /** * Getter for subset of generic tracks that are of type StaticTrack * * @return the timeline tracks */ public List<StaticTrack> getStaticTracks() { List<StaticTrack> staticTracks = new ArrayList<>(); for (GenericTrack genericTrack : this.genericTracks) { if (genericTrack instanceof StaticTrack) { staticTracks.add((StaticTrack)genericTrack); } } return staticTracks; } /** * A method that returns a string representation of a Source Package object * * @return string representing the object */ public String toString() { return this.sourcePackageBO.toString(); } /** * Object corresponding to parsed MaterialPackage structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class SourcePackageBO extends GenericPackageBO { @MXFProperty(size=16, depends=true) private final StrongRef descriptor = null; /** * Instantiates a new parsed SourcePackage object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public SourcePackageBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, SourcePackage.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.package_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, SourcePackage.ERROR_DESCRIPTION_PREFIX + "package_uid is null"); } if (this.tracks == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, SourcePackage.ERROR_DESCRIPTION_PREFIX + "tracks is null"); } else { for (StrongRef strongRef : this.tracks.getEntries()) { this.genericTrackInstanceUIDs.add(strongRef.getInstanceUID()); } } } /** * Getter for the descriptor UID referred by this Source Package * @return the descriptor UID referred by this Source Package */ public MXFUID getDescriptorUID() { return this.descriptor.getInstanceUID(); } /** * A method that returns a string representation of a parsed Source Package object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== SourcePackage ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("package_uid = 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%n", this.package_uid[0], this.package_uid[1], this.package_uid[2], this.package_uid[3], this.package_uid[4], this.package_uid[5], this.package_uid[6], this.package_uid[7], this.package_uid[8], this.package_uid[9], this.package_uid[10], this.package_uid[11], this.package_uid[12], this.package_uid[13], this.package_uid[14], this.package_uid[15], this.package_uid[16], this.package_uid[17], this.package_uid[18], this.package_uid[19], this.package_uid[20], this.package_uid[21], this.package_uid[22], this.package_uid[23], this.package_uid[24], this.package_uid[25], this.package_uid[26], this.package_uid[27], this.package_uid[28], this.package_uid[29], this.package_uid[30], this.package_uid[31])); sb.append("================== PackageCreationDate ======================\n"); sb.append(this.package_creation_date.toString()); sb.append("================== PackageModifiedDate ======================\n"); sb.append(this.package_modified_date.toString()); sb.append(this.tracks.toString()); sb.append(String.format("descriptor = %s%n", this.descriptor.toString())); return sb.toString(); } } }
5,157
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/annotations/MXFProperty.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.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation is used to describe various properties of field members in the object model for an MXF file. Different * field members in different classes of the object model correspond to syntax elements defined in st377-1:2011 */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface MXFProperty { /** * Describes the size in bytes of a syntax element. Equals 0 when size is obtained from the MXF file bitstream * @return Size in bytes of a syntax element */ int size() default 0; /** * Describes the charset encoding used for String syntax element * @return Charset encoding used for String syntax element */ String charset() default "US-ASCII"; /** * Describes whether the value associated with a syntax element corresponds to a reference * @return Indicates whether the value associated with a syntax element corresponds to a reference */ boolean depends() default false; }
5,158
0
Create_ds/photon/src/main/java/com/netflix/imflibrary
Create_ds/photon/src/main/java/com/netflix/imflibrary/st0422/JP2KContentKind.java
package com.netflix.imflibrary.st0422; public enum JP2KContentKind { FU((byte)0x01, "Frame-based wrapping – \"FU\" Undefined"), Cn((byte)0x02, "\"Cn\" Clip-based wrapping"), I1((byte)0x03, "\"I1\" Interlaced Frame Wrapping, 1 field per KLV Element"), I2((byte)0x04, "\"I2\" Interlaced Frame Wrapping, 2 fields per KLV Element"), F1((byte)0x05, "\"F1\" Field Wrapping, 1 field per KLV Element"), P1((byte)0x06, "Frame-based wrapping – \"P1\" Progressive"), Unknown((byte)0, "Unknown wrapping"); private final byte contentKind; private final String description; JP2KContentKind (byte contentKind, String description){ this.contentKind = contentKind; this.description = description; } public byte getContentKind() { return contentKind; } public static JP2KContentKind valueOf(byte value) { for (JP2KContentKind kind: JP2KContentKind.values()) { if (kind.getContentKind() == value) { return kind; } } return Unknown; } @Override public String toString() { return this.description; } }
5,159
0
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/org/apache/tinkerpop/gremlin
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/org/apache/tinkerpop/gremlin/driver/SigV4WebSocketChannelizer.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tinkerpop.gremlin.driver; import com.amazon.neptune.gremlin.driver.sigv4.AwsSigV4ClientHandshaker; import com.amazon.neptune.gremlin.driver.sigv4.ChainedSigV4PropertiesProvider; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import io.netty.channel.Channel; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.http.EmptyHttpHeaders; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketVersion; import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler; import org.apache.tinkerpop.gremlin.driver.Channelizer.AbstractChannelizer; import org.apache.tinkerpop.gremlin.driver.exception.ConnectionException; import org.apache.tinkerpop.gremlin.driver.handler.WebSocketClientHandler; import org.apache.tinkerpop.gremlin.driver.handler.WebSocketGremlinRequestEncoder; import org.apache.tinkerpop.gremlin.driver.handler.WebSocketGremlinResponseDecoder; import java.util.concurrent.TimeoutException; /** * An {@link AbstractChannelizer}, with most of the code from {@link WebSocketChannelizer}. Except it uses a * different WebSocketClientHandshaker which uses SIGV4 auth. This class should be used as a Channelizer when SIGV4 * auth is enabled. * * @see <a href="https://github.com/apache/tinkerpop/blob/master/gremlin-driver/src/main/java/org/apache/tinkerpop/gremlin/driver/Channelizer.java"> * https://github.com/apache/tinkerpop/blob/master/gremlin-driver/src/main/java/org/apache/tinkerpop/gremlin/driver/Channelizer.java</a> */ public class SigV4WebSocketChannelizer extends AbstractChannelizer { /** * Constant to denote the websocket protocol. */ private static final String WEB_SOCKET = "ws"; /** * Constant to denote the websocket secure protocol. */ private static final String WEB_SOCKET_SECURE = "wss"; /** * Name of the HttpCodec handler. */ private static final String HTTP_CODEC = "http-codec"; /** * Name of the HttpAggregator handler. */ private static final String AGGREGATOR = "aggregator"; /** * Name of the WebSocket handler. */ private static final String WEB_SOCKET_HANDLER = "ws-handler"; /** * Name of the GremlinEncoder handler. */ private static final String GREMLIN_ENCODER = "gremlin-encoder"; /** * Name of the GremlinDecoder handler. */ private static final String GRELIN_DECODER = "gremlin-decoder"; /** * Name of the WebSocket compression handler. */ public static final String WEBSOCKET_COMPRESSION_HANDLER = "web-socket-compression-handler"; /** * The handler to process websocket messages from the server. */ private WebSocketClientHandler handler; /** * Encoder to encode websocket requests. */ private WebSocketGremlinRequestEncoder webSocketGremlinRequestEncoder; /** * Decoder to decode websocket requests. */ private WebSocketGremlinResponseDecoder webSocketGremlinResponseDecoder; /** * Initializes the channelizer. * @param connection the {@link Connection} object. */ @Override public void init(final Connection connection) { super.init(connection); webSocketGremlinRequestEncoder = new WebSocketGremlinRequestEncoder(true, cluster.getSerializer()); webSocketGremlinResponseDecoder = new WebSocketGremlinResponseDecoder(cluster.getSerializer()); } /** * Keep-alive is supported through the ping/pong websocket protocol. * @see <a href=https://tools.ietf.org/html/rfc6455#section-5.5.2>IETF RFC 6455</a> */ @Override public boolean supportsKeepAlive() { return true; } @Override public Object createKeepAliveMessage() { return new PingWebSocketFrame(); } /** * Sends a {@code CloseWebSocketFrame} to the server for the specified channel. */ @Override public void close(final Channel channel) { if (channel.isOpen()) { channel.writeAndFlush(new CloseWebSocketFrame()); } } @Override public boolean supportsSsl() { final String scheme = connection.getUri().getScheme(); return "wss".equalsIgnoreCase(scheme); } @Override public void configure(final ChannelPipeline pipeline) { final String scheme = connection.getUri().getScheme(); if (!WEB_SOCKET.equalsIgnoreCase(scheme) && !WEB_SOCKET_SECURE.equalsIgnoreCase(scheme)) { throw new IllegalStateException(String.format("Unsupported scheme (only %s: or %s: supported): %s", WEB_SOCKET, WEB_SOCKET_SECURE, scheme)); } if (!supportsSsl() && WEB_SOCKET_SECURE.equalsIgnoreCase(scheme)) { throw new IllegalStateException(String.format("To use %s scheme ensure that enableSsl is set to true in " + "configuration", WEB_SOCKET_SECURE)); } final int maxContentLength = cluster.connectionPoolSettings().maxContentLength; handler = createHandler(); pipeline.addLast(HTTP_CODEC, new HttpClientCodec()); pipeline.addLast(AGGREGATOR, new HttpObjectAggregator(maxContentLength)); // Add compression extension for WebSocket defined in https://tools.ietf.org/html/rfc7692 pipeline.addLast(WEBSOCKET_COMPRESSION_HANDLER, WebSocketClientCompressionHandler.INSTANCE); pipeline.addLast(WEB_SOCKET_HANDLER, handler); pipeline.addLast(GREMLIN_ENCODER, webSocketGremlinRequestEncoder); pipeline.addLast(GRELIN_DECODER, webSocketGremlinResponseDecoder); } @Override public void connected() { try { // Block until the handshake is complete either successfully or with an error. The handshake future // will complete with a timeout exception after some time so it is guaranteed that this future will // complete. The timeout for the handshake is configured by cluster.getConnectionSetupTimeout(). // // If future completed with an exception more than likely, SSL is enabled on the server, but the client // forgot to enable it or perhaps the server is not configured for websockets. handler.handshakeFuture().sync(); } catch (Exception ex) { final String errMsg; if (ex instanceof TimeoutException) { // Note that we are not using catch(TimeoutException ex) because the compiler throws an error for // catching a checked exception which is not thrown from the code inside try. However, the compiler // check is incorrect since Netty bypasses the compiler check and sync() is able to rethrow underlying // exception even if it is a check exception. // More information about how Netty bypasses compiler check at https://github.com/netty/netty/blob/d371b1bbaa3b98f957f6b025673098ad3adb5131/common/src/main/java/io/netty/util/internal/PlatformDependent.java#L418 errMsg = "Timed out while waiting to complete the connection setup. Consider increasing the " + "WebSocket handshake timeout duration."; } else { errMsg = "Could not complete connection setup to the server. Ensure that SSL is correctly " + "configured at both the client and the server. Ensure that client WebSocket handshake " + "protocol matches the server. Ensure that the server is still reachable."; } throw new ConnectionException(connection.getUri(), errMsg, ex); } } /** * This protected method provides a way for customizing the channelize through inheritance * to override credentials used to establish sign requests * * @return credentials provider that will be used to generate SigV4 signatures */ protected AWSCredentialsProvider getCredentialsProvider() { return new DefaultAWSCredentialsProviderChain(); } /** * Creates an instance of {@link WebSocketClientHandler} with {@link AwsSigV4ClientHandshaker} as the handshaker * for SigV4 auth. * @return the instance of clientHandler. */ private WebSocketClientHandler createHandler() { WebSocketClientHandshaker handshaker = new AwsSigV4ClientHandshaker( connection.getUri(), WebSocketVersion.V13, null, true, // allow extensions to support WebSocket compression EmptyHttpHeaders.INSTANCE, cluster.getMaxContentLength(), new ChainedSigV4PropertiesProvider(), getCredentialsProvider()); return new WebSocketClientHandler(handshaker, cluster.getConnectionSetupTimeout()); } }
5,160
0
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/org/apache/tinkerpop/gremlin
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/org/apache/tinkerpop/gremlin/driver/package-info.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Package to provide custom channelizers. Channelizers that extend * {@link org.apache.tinkerpop.gremlin.driver.Channelizer.AbstractChannelizer} should be in this package. */ package org.apache.tinkerpop.gremlin.driver;
5,161
0
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver/sigv4/ChainedSigV4PropertiesProvider.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazon.neptune.gremlin.driver.sigv4; import com.amazon.neptune.gremlin.driver.exception.SigV4PropertiesNotFoundException; import java.util.function.Supplier; import org.apache.commons.lang3.StringUtils; import lombok.extern.slf4j.Slf4j; /** * A chained Sig4Properties provider. * It tries to get the properties from environment variables and if not found looks in Java system properties. */ @Slf4j public class ChainedSigV4PropertiesProvider { /** * The chain of provider lambdas that can read properties required for SigV4 signing. */ private final Supplier<SigV4Properties>[] providers; /** * Creates an instance with default suppliers. */ public ChainedSigV4PropertiesProvider() { this.providers = new Supplier[]{this::getSigV4PropertiesFromEnv, this::getSigV4PropertiesFromSystem}; } /** * Creates an instance with the supplied chain of {@link SigV4Properties} providers. * @param providers the chain of sigv4 properties provider. */ public ChainedSigV4PropertiesProvider(final Supplier<SigV4Properties>[] providers) { this.providers = new Supplier[providers.length]; System.arraycopy(providers, 0, this.providers, 0, providers.length); } /** * Gets the {@link SigV4Properties} from the chain of lambdas. * @return the {@link SigV4Properties}. * @throws SigV4PropertiesNotFoundException when SigV4 properties are not set. */ public SigV4Properties getSigV4Properties() throws SigV4PropertiesNotFoundException { SigV4Properties properties; for (Supplier<SigV4Properties> provider : providers) { try { properties = provider.get(); log.info("Successfully loaded SigV4 properties from provider: {}", provider.getClass()); return properties; } catch (SigV4PropertiesNotFoundException e) { log.info("Unable to load SigV4 properties from provider: {}", provider.getClass()); } } final String message = "Unable to load SigV4 properties from any of the providers"; log.warn(message); throw new SigV4PropertiesNotFoundException(message); } /** * Reads the SigV4 properties from the environment properties and constructs the {@link SigV4Properties} object. * @return the {@link SigV4Properties} constructed from system properties. * @throws SigV4PropertiesNotFoundException when properties are not found in the environment variables. */ public SigV4Properties getSigV4PropertiesFromEnv() throws SigV4PropertiesNotFoundException { final String serviceRegion = StringUtils.trim(System.getenv(SigV4Properties.SERVICE_REGION)); if (StringUtils.isBlank(serviceRegion)) { final String msg = "SigV4 properties not found as a environment variable"; log.info(msg); throw new SigV4PropertiesNotFoundException(msg); } return new SigV4Properties(serviceRegion); } /** * Reads the SigV4 properties from the system properties and constructs the {@link SigV4Properties} object. * @return the {@link SigV4Properties} constructed from system properties. * @throws SigV4PropertiesNotFoundException when the properties are not found in the system properties. */ public SigV4Properties getSigV4PropertiesFromSystem() { final String serviceRegion = StringUtils.trim(System.getProperty(SigV4Properties.SERVICE_REGION)); if (StringUtils.isBlank(serviceRegion)) { final String msg = "SigV4 properties not found in system properties"; log.info(msg); throw new SigV4PropertiesNotFoundException(msg); } return new SigV4Properties(serviceRegion); } }
5,162
0
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver/sigv4/AwsSigV4ClientHandshaker.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazon.neptune.gremlin.driver.sigv4; import java.net.URI; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.neptune.auth.NeptuneNettyHttpSigV4Signer; import com.amazonaws.neptune.auth.NeptuneSigV4SignerException; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker13; import io.netty.handler.codec.http.websocketx.WebSocketVersion; /** * Extends the functionality of {@link WebSocketClientHandshaker13} by adding SIGV4 authentication headers to the * request. */ public class AwsSigV4ClientHandshaker extends WebSocketClientHandshaker13 { /** * Instance of the properties provider to get properties for SIGV4 signing. */ private final ChainedSigV4PropertiesProvider sigV4PropertiesProvider; /** * SigV4 properties required to perform the signing. */ private final SigV4Properties sigV4Properties; /** * Credentials provider to use to generate signature */ private final AWSCredentialsProvider awsCredentialsProvider; /** * Creates a new instance with default credentials provider (for backward compatibility). * @param webSocketURL - URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket * frames will be sent to this URL. * @param version - Version of web socket specification to use to connect to the server * @param subprotocol - Sub protocol request sent to the server. * @param allowExtensions - Allow extensions to be used in the reserved bits of the web socket frame * @param customHeaders - Map of custom headers to add to the client request * @param maxFramePayloadLength - Maximum length of a frame's payload * @param sigV4PropertiesProvider - a properties provider to get sigV4 auth related properties */ @Deprecated public AwsSigV4ClientHandshaker(final URI webSocketURL, final WebSocketVersion version, final String subprotocol, final boolean allowExtensions, final HttpHeaders customHeaders, final int maxFramePayloadLength, final ChainedSigV4PropertiesProvider sigV4PropertiesProvider) { this( webSocketURL, version, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength, sigV4PropertiesProvider, new DefaultAWSCredentialsProviderChain() ); } /** * Creates a new instance. * @param webSocketURL - URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket * frames will be sent to this URL. * @param version - Version of web socket specification to use to connect to the server * @param subprotocol - Sub protocol request sent to the server. * @param allowExtensions - Allow extensions to be used in the reserved bits of the web socket frame * @param customHeaders - Map of custom headers to add to the client request * @param maxFramePayloadLength - Maximum length of a frame's payload * @param sigV4PropertiesProvider - a properties provider to get sigV4 auth related properties * @param awsCredentialsProvider - an AWS credentials provider to use to generate signature */ public AwsSigV4ClientHandshaker(final URI webSocketURL, final WebSocketVersion version, final String subprotocol, final boolean allowExtensions, final HttpHeaders customHeaders, final int maxFramePayloadLength, final ChainedSigV4PropertiesProvider sigV4PropertiesProvider, final AWSCredentialsProvider awsCredentialsProvider ) { super(webSocketURL, version, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength); this.awsCredentialsProvider = awsCredentialsProvider; this.sigV4PropertiesProvider = sigV4PropertiesProvider; this.sigV4Properties = loadProperties(); } /** * Gets the request as generated by {@link WebSocketClientHandshaker13} and adds additional headers and a SIGV4 * signature required for SigV4Auth. * Sends the opening request to the server: * GET /chat HTTP/1.1 * Host: server.example.com * Upgrade: websocket * Connection: Upgrade * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== * Sec-WebSocket-Origin: http://example.com * Sec-WebSocket-Protocol: chat, superchat * Sec-WebSocket-Version: 13 * x-amz-date: 20180214T002049Z * Authorization: [SIGV4AuthHeader] * @return SIGV4 signed {@link FullHttpRequest}. */ @Override protected FullHttpRequest newHandshakeRequest() { final FullHttpRequest request = super.newHandshakeRequest(); final NeptuneNettyHttpSigV4Signer sigV4Signer; try { sigV4Signer = new NeptuneNettyHttpSigV4Signer(this.sigV4Properties.getServiceRegion(), awsCredentialsProvider); sigV4Signer.signRequest(request); } catch (NeptuneSigV4SignerException e) { throw new RuntimeException("Exception occurred while signing the request", e); } return request; } /** * Calls the {@link ChainedSigV4PropertiesProvider} to get the properties required for SigV4 signing. * @return an instance of {@link SigV4Properties}. */ private SigV4Properties loadProperties() { return sigV4PropertiesProvider.getSigV4Properties(); } }
5,163
0
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver/sigv4/SigV4Properties.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazon.neptune.gremlin.driver.sigv4; /** * Holds the properties required to perform SIGV4 auth. */ public class SigV4Properties { /** * The service region property name. */ public static final String SERVICE_REGION = "SERVICE_REGION"; /** * The region of the service. E.g. us-east-1. */ private final String serviceRegion; /** * @param serviceRegion the region name for the service. */ public SigV4Properties(final String serviceRegion) { this.serviceRegion = serviceRegion; } /** * @return the serviceRegion. */ public String getServiceRegion() { return serviceRegion; } }
5,164
0
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver/sigv4/package-info.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Authorization related code for Amazon Neptune, e.g. * WebSocketHandshake handler and auth related code to handle gremlin calls with SigV4 authentication. */ package com.amazon.neptune.gremlin.driver.sigv4;
5,165
0
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver/example/NeptuneGremlinSigV4Example.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazon.neptune.gremlin.driver.example; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.tinkerpop.gremlin.driver.Client; import org.apache.tinkerpop.gremlin.driver.Cluster; import org.apache.tinkerpop.gremlin.driver.Result; import org.apache.tinkerpop.gremlin.driver.ResultSet; import org.apache.tinkerpop.gremlin.driver.SigV4WebSocketChannelizer; /** * An example client code to demonstrate the process of making auth enabled Gremlin calls to Neptune Server. * If auth is enabled on the server side then the neptune db region should be set either as a system property of as * an environment variable. * For instance, set the region as system property: <code>-DSERVICE_REGION=us-east-1</code> * <p> * The request signing logic requires IAM credentials to sign the requests. Two of the methods to provide the IAM * credentials: * <ol> * <li>Setting environment variables AWS_ACCESS_KEY_ID=[your-access-key-id] and AWS_SECRET_KEY=[your-access-secret].</li> * <li>Passing as JVM arg: -Daws.accessKeyId=[your-access-key-id] and -Daws.secretKey=[your-access-secret].</li> * </ol> * * @see <a href="https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/auth/DefaultAWSCredentialsProviderChain.html"> * DefaultAWSCredentialsProviderChain"</a> for more information and additional methods for providing IAM credentials. */ public final class NeptuneGremlinSigV4Example { /** * Command line option name for the db cluster/instance endpoint. */ private static final String ENDPOINT = "endpoint"; /** * Command line option name for the db cluster/instance port. */ private static final String PORT = "port"; /** * Command line option name for the whether to use ssl connection. */ private static final String SSL = "ssl"; /** * The gremlin query to test. */ private static final String SAMPLE_QUERY = "g.V().count()"; /** * Default private constructor. */ private NeptuneGremlinSigV4Example() { } /** * Test code to make gremlin java calls. * @param args program args. */ public static void main(final String[] args) { final Options options = setupCliOptions(); final CommandLine cli = parseArgs(args, options); final Cluster.Builder builder = Cluster.build(); builder.addContactPoint(cli.getOptionValue(ENDPOINT)); builder.port(Integer.parseInt(cli.getOptionValue(PORT))); //If the neptune db is auth enabled then add use the following channelizer. Otherwise omit the below line. builder.channelizer(SigV4WebSocketChannelizer.class); builder.enableSsl(Boolean.parseBoolean(cli.getOptionValue(SSL, "false"))); final Cluster cluster = builder.create(); try { final Client client = cluster.connect(); final ResultSet rs = client.submit(SAMPLE_QUERY); for (Result r : rs) { System.out.println(r); } } finally { cluster.close(); } } /** * Parses the command line args and returns a {@link CommandLine} with the properties. * @param args the command line args. * @param options the options object containing the args that can be passed. * @return a {@link CommandLine} instance with the option properties set. */ private static CommandLine parseArgs(final String[] args, final Options options) { final CommandLineParser parser = new BasicParser(); final HelpFormatter formatter = new HelpFormatter(); try { return parser.parse(options, args); } catch (ParseException e) { formatter.printHelp(NeptuneGremlinSigV4Example.class.getSimpleName(), options); throw new RuntimeException("Invalid command line args"); } } /** * Private utility to set the CLI options required to run the program. * @return {@link Options} that can be accepted by the program. */ private static Options setupCliOptions() { final Options options = new Options(); final Option endpoint = new Option("e", ENDPOINT, true, "The db cluster/instance endpoint"); endpoint.setRequired(true); options.addOption(endpoint); final Option port = new Option("p", PORT, true, "The db cluster/instance port"); port.setRequired(true); options.addOption(port); final Option ssl = new Option("s", SSL, true, "Whether to enable ssl on the connection"); ssl.setRequired(false); ssl.setType(Boolean.class); options.addOption(ssl); return options; } }
5,166
0
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver/example/package-info.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Examples demonstrating making gremlin calls to neptune when SigV4 auth is enabled. */ package com.amazon.neptune.gremlin.driver.example;
5,167
0
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver/exception/SigV4PropertiesNotFoundException.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazon.neptune.gremlin.driver.exception; /** * Denotes an exception when trying to extract properties required for SigV4 signing. */ public class SigV4PropertiesNotFoundException extends RuntimeException { /** * @param message the error message. */ public SigV4PropertiesNotFoundException(final String message) { super(message); } /** * @param message the error message. * @param cause the root cause exception. */ public SigV4PropertiesNotFoundException(final String message, final Throwable cause) { super(message, cause); } }
5,168
0
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver
Create_ds/amazon-neptune-gremlin-java-sigv4/src/main/java/com/amazon/neptune/gremlin/driver/exception/package-info.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Exceptions related to gremlin driver code. */ package com.amazon.neptune.gremlin.driver.exception;
5,169
0
Create_ds/aws-iot-device-sdk-java-v2/samples/FleetProvisioning/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/FleetProvisioning/src/main/java/fleetprovisioning/Mqtt5FleetProvisioningSample.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package fleetprovisioning; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import software.amazon.awssdk.iot.iotidentity.IotIdentityClient; import software.amazon.awssdk.iot.iotidentity.model.CreateCertificateFromCsrRequest; import software.amazon.awssdk.iot.iotidentity.model.CreateCertificateFromCsrResponse; import software.amazon.awssdk.iot.iotidentity.model.CreateCertificateFromCsrSubscriptionRequest; import software.amazon.awssdk.iot.iotidentity.model.CreateKeysAndCertificateRequest; import software.amazon.awssdk.iot.iotidentity.model.CreateKeysAndCertificateResponse; import software.amazon.awssdk.iot.iotidentity.model.CreateKeysAndCertificateSubscriptionRequest; import software.amazon.awssdk.iot.iotidentity.model.ErrorResponse; import software.amazon.awssdk.iot.iotidentity.model.RegisterThingRequest; import software.amazon.awssdk.iot.iotidentity.model.RegisterThingResponse; import software.amazon.awssdk.iot.iotidentity.model.RegisterThingSubscriptionRequest; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import com.google.gson.Gson; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import utils.commandlineutils.CommandLineUtils; public class Mqtt5FleetProvisioningSample { // When run normally, we want to exit nicely even if something goes wrong. // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code. static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CompletableFuture<Void> gotResponse; static IotIdentityClient iotIdentityClient; static CreateKeysAndCertificateResponse createKeysAndCertificateResponse = null; static CreateCertificateFromCsrResponse createCertificateFromCsrResponse = null; static RegisterThingResponse registerThingResponse = null; static long responseWaitTimeMs = 5000L; // 5 seconds static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the * exec:java task * When called otherwise, print what went wrong (if anything) and just continue * (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("BasicConnect execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } static void onRejectedKeys(ErrorResponse response) { System.out.println("CreateKeysAndCertificate Request rejected, errorCode: " + response.errorCode + ", errorMessage: " + response.errorMessage + ", statusCode: " + response.statusCode); gotResponse.complete(null); } static void onRejectedCsr(ErrorResponse response) { System.out.println("CreateCertificateFromCsr Request rejected, errorCode: " + response.errorCode + ", errorMessage: " + response.errorMessage + ", statusCode: " + response.statusCode); gotResponse.complete(null); } static void onRejectedRegister(ErrorResponse response) { System.out.println("RegisterThing Request rejected, errorCode: " + response.errorCode + ", errorMessage: " + response.errorMessage + ", statusCode: " + response.statusCode); gotResponse.complete(null); } static void onCreateKeysAndCertificateAccepted(CreateKeysAndCertificateResponse response) { if (response != null) { System.out.println("CreateKeysAndCertificate response certificateId: " + response.certificateId); if (createKeysAndCertificateResponse == null) { createKeysAndCertificateResponse = response; } else { System.out .println("CreateKeysAndCertificate response received after having already gotten a response!"); } } else { System.out.println("CreateKeysAndCertificate response is null"); } gotResponse.complete(null); } static void onCreateCertificateFromCsrResponseAccepted(CreateCertificateFromCsrResponse response) { if (response != null) { System.out.println("CreateCertificateFromCsr response certificateId: " + response.certificateId); if (createCertificateFromCsrResponse == null) { createCertificateFromCsrResponse = response; } else { System.out .println("CreateCertificateFromCsr response received after having already gotten a response!"); } } else { System.out.println("CreateCertificateFromCsr response is null"); } gotResponse.complete(null); } static void onRegisterThingAccepted(RegisterThingResponse response) { if (response != null) { System.out.println("RegisterThing response thingName: " + response.thingName); if (registerThingResponse == null) { registerThingResponse = response; } else { System.out.println("RegisterThing response received after having already gotten a response!"); } } else { System.out.println("RegisterThing response is null"); } gotResponse.complete(null); } static void onException(Exception e) { e.printStackTrace(); System.out.println("Exception occurred " + e); } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single * struct for * use in this sample. This handles all of the command line parsing, validating, * etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils .getInputForIoTSample("FleetProvisioningSample", args); MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; MqttClientConnection connection = null; boolean exitWithError = false; try { /** * Create the MQTT connection from the builder */ AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(cmdData.input_cert, cmdData.input_key); if (cmdData.input_ca != "") { builder.withCertificateAuthorityFromPath(null, cmdData.input_ca); } builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withPort((short) cmdData.input_port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); connection = builder.build(); builder.close(); /** * Verify the connection was created */ if (connection == null) { onApplicationFailure(new RuntimeException("MQTT connection creation failed!")); } // Create the identity client (Identity = Fleet Provisioning) iotIdentityClient = new IotIdentityClient(connection); // Connect CompletableFuture<Boolean> connected = connection.connect(); boolean sessionPresent = connected.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!"); // Fleet Provision based on whether there is a CSR file path or not if (cmdData.input_csrPath == null) { createKeysAndCertificateWorkflow(cmdData.input_templateName, cmdData.input_templateParameters); } else { createCertificateFromCsrWorkflow(cmdData.input_templateName, cmdData.input_templateParameters, cmdData.input_csrPath); } // Disconnect CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); } catch (Exception ex) { System.out.println("Exception encountered! " + "\n"); ex.printStackTrace(); exitWithError = true; } finally { if (connection != null) { // Close the connection now that we are completely done with it. connection.close(); } } CrtResource.waitForNoResources(); System.out.println("Sample complete!"); if (exitWithError) { System.exit(1); } else { System.exit(0); } } private static void SubscribeToRegisterThing(String input_templateName) throws Exception { RegisterThingSubscriptionRequest registerThingSubscriptionRequest = new RegisterThingSubscriptionRequest(); registerThingSubscriptionRequest.templateName = input_templateName; CompletableFuture<Integer> subscribedRegisterAccepted = iotIdentityClient.SubscribeToRegisterThingAccepted( registerThingSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, Mqtt5FleetProvisioningSample::onRegisterThingAccepted, Mqtt5FleetProvisioningSample::onException); subscribedRegisterAccepted.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Subscribed to SubscribeToRegisterThingAccepted"); CompletableFuture<Integer> subscribedRegisterRejected = iotIdentityClient.SubscribeToRegisterThingRejected( registerThingSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, Mqtt5FleetProvisioningSample::onRejectedRegister, Mqtt5FleetProvisioningSample::onException); subscribedRegisterRejected.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Subscribed to SubscribeToRegisterThingRejected"); } private static void createKeysAndCertificateWorkflow(String input_templateName, String input_templateParameters) throws Exception { CreateKeysAndCertificateSubscriptionRequest createKeysAndCertificateSubscriptionRequest = new CreateKeysAndCertificateSubscriptionRequest(); CompletableFuture<Integer> keysSubscribedAccepted = iotIdentityClient .SubscribeToCreateKeysAndCertificateAccepted( createKeysAndCertificateSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, Mqtt5FleetProvisioningSample::onCreateKeysAndCertificateAccepted); keysSubscribedAccepted.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Subscribed to CreateKeysAndCertificateAccepted"); CompletableFuture<Integer> keysSubscribedRejected = iotIdentityClient .SubscribeToCreateKeysAndCertificateRejected( createKeysAndCertificateSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, Mqtt5FleetProvisioningSample::onRejectedKeys); keysSubscribedRejected.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Subscribed to CreateKeysAndCertificateRejected"); // Subscribes to the register thing accepted and rejected topics SubscribeToRegisterThing(input_templateName); CompletableFuture<Integer> publishKeys = iotIdentityClient.PublishCreateKeysAndCertificate( new CreateKeysAndCertificateRequest(), QualityOfService.AT_LEAST_ONCE); gotResponse = new CompletableFuture<>(); publishKeys.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Published to CreateKeysAndCertificate"); gotResponse.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Got response at CreateKeysAndCertificate"); // Verify the response is good if (createKeysAndCertificateResponse == null) { throw new Exception("Got invalid/error createKeysAndCertificateResponse"); } gotResponse = new CompletableFuture<>(); System.out.println("RegisterThing now...."); RegisterThingRequest registerThingRequest = new RegisterThingRequest(); registerThingRequest.certificateOwnershipToken = createKeysAndCertificateResponse.certificateOwnershipToken; registerThingRequest.templateName = input_templateName; if (input_templateParameters != null && input_templateParameters != "") { registerThingRequest.parameters = new Gson().fromJson(input_templateParameters, HashMap.class); } CompletableFuture<Integer> publishRegister = iotIdentityClient.PublishRegisterThing( registerThingRequest, QualityOfService.AT_LEAST_ONCE); publishRegister.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Published to RegisterThing"); gotResponse.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Got response at RegisterThing"); } private static void createCertificateFromCsrWorkflow(String input_templateName, String input_templateParameters, String input_csrPath) throws Exception { CreateCertificateFromCsrSubscriptionRequest createCertificateFromCsrSubscriptionRequest = new CreateCertificateFromCsrSubscriptionRequest(); CompletableFuture<Integer> csrSubscribedAccepted = iotIdentityClient .SubscribeToCreateCertificateFromCsrAccepted( createCertificateFromCsrSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, Mqtt5FleetProvisioningSample::onCreateCertificateFromCsrResponseAccepted); csrSubscribedAccepted.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Subscribed to CreateCertificateFromCsrAccepted"); CompletableFuture<Integer> csrSubscribedRejected = iotIdentityClient .SubscribeToCreateCertificateFromCsrRejected( createCertificateFromCsrSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, Mqtt5FleetProvisioningSample::onRejectedCsr); csrSubscribedRejected.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Subscribed to CreateCertificateFromCsrRejected"); // Subscribes to the register thing accepted and rejected topics SubscribeToRegisterThing(input_templateName); String csrContents = new String(Files.readAllBytes(Paths.get(input_csrPath))); CreateCertificateFromCsrRequest createCertificateFromCsrRequest = new CreateCertificateFromCsrRequest(); createCertificateFromCsrRequest.certificateSigningRequest = csrContents; CompletableFuture<Integer> publishCsr = iotIdentityClient.PublishCreateCertificateFromCsr( createCertificateFromCsrRequest, QualityOfService.AT_LEAST_ONCE); gotResponse = new CompletableFuture<>(); publishCsr.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Published to CreateCertificateFromCsr"); gotResponse.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Got response at CreateCertificateFromCsr"); // Verify the response is good if (createCertificateFromCsrResponse == null) { throw new Exception("Got invalid/error createCertificateFromCsrResponse"); } gotResponse = new CompletableFuture<>(); System.out.println("RegisterThing now...."); RegisterThingRequest registerThingRequest = new RegisterThingRequest(); registerThingRequest.certificateOwnershipToken = createCertificateFromCsrResponse.certificateOwnershipToken; registerThingRequest.templateName = input_templateName; registerThingRequest.parameters = new Gson().fromJson(input_templateParameters, HashMap.class); CompletableFuture<Integer> publishRegister = iotIdentityClient.PublishRegisterThing( registerThingRequest, QualityOfService.AT_LEAST_ONCE); publishRegister.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Published to RegisterThing"); gotResponse.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Got response at RegisterThing"); } }
5,170
0
Create_ds/aws-iot-device-sdk-java-v2/samples/FleetProvisioning/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/FleetProvisioning/src/main/java/fleetprovisioning/FleetProvisioningSample.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package fleetprovisioning; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import software.amazon.awssdk.iot.iotidentity.IotIdentityClient; import software.amazon.awssdk.iot.iotidentity.model.CreateCertificateFromCsrRequest; import software.amazon.awssdk.iot.iotidentity.model.CreateCertificateFromCsrResponse; import software.amazon.awssdk.iot.iotidentity.model.CreateCertificateFromCsrSubscriptionRequest; import software.amazon.awssdk.iot.iotidentity.model.CreateKeysAndCertificateRequest; import software.amazon.awssdk.iot.iotidentity.model.CreateKeysAndCertificateResponse; import software.amazon.awssdk.iot.iotidentity.model.CreateKeysAndCertificateSubscriptionRequest; import software.amazon.awssdk.iot.iotidentity.model.ErrorResponse; import software.amazon.awssdk.iot.iotidentity.model.RegisterThingRequest; import software.amazon.awssdk.iot.iotidentity.model.RegisterThingResponse; import software.amazon.awssdk.iot.iotidentity.model.RegisterThingSubscriptionRequest; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import com.google.gson.Gson; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import utils.commandlineutils.CommandLineUtils; public class FleetProvisioningSample { // When run normally, we want to exit nicely even if something goes wrong. // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code. static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CompletableFuture<Void> gotResponse; static IotIdentityClient iotIdentityClient; static CreateKeysAndCertificateResponse createKeysAndCertificateResponse = null; static CreateCertificateFromCsrResponse createCertificateFromCsrResponse = null; static RegisterThingResponse registerThingResponse = null; static long responseWaitTimeMs = 5000L; // 5 seconds static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("BasicConnect execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } static void onRejectedKeys(ErrorResponse response) { System.out.println("CreateKeysAndCertificate Request rejected, errorCode: " + response.errorCode + ", errorMessage: " + response.errorMessage + ", statusCode: " + response.statusCode); gotResponse.complete(null); } static void onRejectedCsr(ErrorResponse response) { System.out.println("CreateCertificateFromCsr Request rejected, errorCode: " + response.errorCode + ", errorMessage: " + response.errorMessage + ", statusCode: " + response.statusCode); gotResponse.complete(null); } static void onRejectedRegister(ErrorResponse response) { System.out.println("RegisterThing Request rejected, errorCode: " + response.errorCode + ", errorMessage: " + response.errorMessage + ", statusCode: " + response.statusCode); gotResponse.complete(null); } static void onCreateKeysAndCertificateAccepted(CreateKeysAndCertificateResponse response) { if (response != null) { System.out.println("CreateKeysAndCertificate response certificateId: " + response.certificateId); if (createKeysAndCertificateResponse == null) { createKeysAndCertificateResponse = response; } else { System.out.println("CreateKeysAndCertificate response received after having already gotten a response!"); } } else { System.out.println("CreateKeysAndCertificate response is null"); } gotResponse.complete(null); } static void onCreateCertificateFromCsrResponseAccepted(CreateCertificateFromCsrResponse response) { if (response != null) { System.out.println("CreateCertificateFromCsr response certificateId: " + response.certificateId); if (createCertificateFromCsrResponse == null) { createCertificateFromCsrResponse = response; } else { System.out.println("CreateCertificateFromCsr response received after having already gotten a response!"); } } else { System.out.println("CreateCertificateFromCsr response is null"); } gotResponse.complete(null); } static void onRegisterThingAccepted(RegisterThingResponse response) { if (response != null) { System.out.println("RegisterThing response thingName: " + response.thingName); if (registerThingResponse == null) { registerThingResponse = response; } else { System.out.println("RegisterThing response received after having already gotten a response!"); } } else { System.out.println("RegisterThing response is null"); } gotResponse.complete(null); } static void onException(Exception e) { e.printStackTrace(); System.out.println("Exception occurred " + e); } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("FleetProvisioningSample", args); MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; MqttClientConnection connection = null; boolean exitWithError = false; try { /** * Create the MQTT connection from the builder */ AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(cmdData.input_cert, cmdData.input_key); if (cmdData.input_ca != "") { builder.withCertificateAuthorityFromPath(null, cmdData.input_ca); } builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withPort((short)cmdData.input_port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); connection = builder.build(); builder.close(); /** * Verify the connection was created */ if (connection == null) { onApplicationFailure(new RuntimeException("MQTT connection creation failed!")); } // Create the identity client (Identity = Fleet Provisioning) iotIdentityClient = new IotIdentityClient(connection); // Connect CompletableFuture<Boolean> connected = connection.connect(); boolean sessionPresent = connected.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!"); // Fleet Provision based on whether there is a CSR file path or not if (cmdData.input_csrPath == null) { createKeysAndCertificateWorkflow(cmdData.input_templateName, cmdData.input_templateParameters); } else { createCertificateFromCsrWorkflow(cmdData.input_templateName, cmdData.input_templateParameters, cmdData.input_csrPath); } // Disconnect CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); } catch (Exception ex) { System.out.println("Exception encountered! " + "\n"); ex.printStackTrace(); exitWithError = true; } finally { if (connection != null) { // Close the connection now that we are completely done with it. connection.close(); } } CrtResource.waitForNoResources(); System.out.println("Sample complete!"); if (exitWithError) { System.exit(1); } else { System.exit(0); } } private static void SubscribeToRegisterThing(String input_templateName) throws Exception { RegisterThingSubscriptionRequest registerThingSubscriptionRequest = new RegisterThingSubscriptionRequest(); registerThingSubscriptionRequest.templateName = input_templateName; CompletableFuture<Integer> subscribedRegisterAccepted = iotIdentityClient.SubscribeToRegisterThingAccepted( registerThingSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, FleetProvisioningSample::onRegisterThingAccepted, FleetProvisioningSample::onException); subscribedRegisterAccepted.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Subscribed to SubscribeToRegisterThingAccepted"); CompletableFuture<Integer> subscribedRegisterRejected = iotIdentityClient.SubscribeToRegisterThingRejected( registerThingSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, FleetProvisioningSample::onRejectedRegister, FleetProvisioningSample::onException); subscribedRegisterRejected.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Subscribed to SubscribeToRegisterThingRejected"); } private static void createKeysAndCertificateWorkflow(String input_templateName, String input_templateParameters) throws Exception { CreateKeysAndCertificateSubscriptionRequest createKeysAndCertificateSubscriptionRequest = new CreateKeysAndCertificateSubscriptionRequest(); CompletableFuture<Integer> keysSubscribedAccepted = iotIdentityClient.SubscribeToCreateKeysAndCertificateAccepted( createKeysAndCertificateSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, FleetProvisioningSample::onCreateKeysAndCertificateAccepted); keysSubscribedAccepted.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Subscribed to CreateKeysAndCertificateAccepted"); CompletableFuture<Integer> keysSubscribedRejected = iotIdentityClient.SubscribeToCreateKeysAndCertificateRejected( createKeysAndCertificateSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, FleetProvisioningSample::onRejectedKeys); keysSubscribedRejected.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Subscribed to CreateKeysAndCertificateRejected"); // Subscribes to the register thing accepted and rejected topics SubscribeToRegisterThing(input_templateName); CompletableFuture<Integer> publishKeys = iotIdentityClient.PublishCreateKeysAndCertificate( new CreateKeysAndCertificateRequest(), QualityOfService.AT_LEAST_ONCE); gotResponse = new CompletableFuture<>(); publishKeys.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Published to CreateKeysAndCertificate"); gotResponse.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Got response at CreateKeysAndCertificate"); // Verify the response is good if (createKeysAndCertificateResponse == null) { throw new Exception("Got invalid/error createKeysAndCertificateResponse"); } gotResponse = new CompletableFuture<>(); System.out.println("RegisterThing now...."); RegisterThingRequest registerThingRequest = new RegisterThingRequest(); registerThingRequest.certificateOwnershipToken = createKeysAndCertificateResponse.certificateOwnershipToken; registerThingRequest.templateName = input_templateName; if (input_templateParameters != null && input_templateParameters != "") { registerThingRequest.parameters = new Gson().fromJson(input_templateParameters, HashMap.class); } CompletableFuture<Integer> publishRegister = iotIdentityClient.PublishRegisterThing( registerThingRequest, QualityOfService.AT_LEAST_ONCE); publishRegister.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Published to RegisterThing"); gotResponse.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Got response at RegisterThing"); } private static void createCertificateFromCsrWorkflow(String input_templateName, String input_templateParameters, String input_csrPath) throws Exception { CreateCertificateFromCsrSubscriptionRequest createCertificateFromCsrSubscriptionRequest = new CreateCertificateFromCsrSubscriptionRequest(); CompletableFuture<Integer> csrSubscribedAccepted = iotIdentityClient.SubscribeToCreateCertificateFromCsrAccepted( createCertificateFromCsrSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, FleetProvisioningSample::onCreateCertificateFromCsrResponseAccepted); csrSubscribedAccepted.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Subscribed to CreateCertificateFromCsrAccepted"); CompletableFuture<Integer> csrSubscribedRejected = iotIdentityClient.SubscribeToCreateCertificateFromCsrRejected( createCertificateFromCsrSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, FleetProvisioningSample::onRejectedCsr); csrSubscribedRejected.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Subscribed to CreateCertificateFromCsrRejected"); // Subscribes to the register thing accepted and rejected topics SubscribeToRegisterThing(input_templateName); String csrContents = new String(Files.readAllBytes(Paths.get(input_csrPath))); CreateCertificateFromCsrRequest createCertificateFromCsrRequest = new CreateCertificateFromCsrRequest(); createCertificateFromCsrRequest.certificateSigningRequest = csrContents; CompletableFuture<Integer> publishCsr = iotIdentityClient.PublishCreateCertificateFromCsr( createCertificateFromCsrRequest, QualityOfService.AT_LEAST_ONCE); gotResponse = new CompletableFuture<>(); publishCsr.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Published to CreateCertificateFromCsr"); gotResponse.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Got response at CreateCertificateFromCsr"); // Verify the response is good if (createCertificateFromCsrResponse == null) { throw new Exception("Got invalid/error createCertificateFromCsrResponse"); } gotResponse = new CompletableFuture<>(); System.out.println("RegisterThing now...."); RegisterThingRequest registerThingRequest = new RegisterThingRequest(); registerThingRequest.certificateOwnershipToken = createCertificateFromCsrResponse.certificateOwnershipToken; registerThingRequest.templateName = input_templateName; registerThingRequest.parameters = new Gson().fromJson(input_templateParameters, HashMap.class); CompletableFuture<Integer> publishRegister = iotIdentityClient.PublishRegisterThing( registerThingRequest, QualityOfService.AT_LEAST_ONCE); publishRegister.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Published to RegisterThing"); gotResponse.get(responseWaitTimeMs, TimeUnit.MILLISECONDS); System.out.println("Got response at RegisterThing"); } }
5,171
0
Create_ds/aws-iot-device-sdk-java-v2/samples/CustomKeyOpsConnect/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/CustomKeyOpsConnect/src/main/java/customkeyopsconnect/CustomKeyOpsConnect.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package customkeyopsconnect; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.io.*; import software.amazon.awssdk.crt.mqtt.*; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.FileReader; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.Signature; import java.security.interfaces.RSAPrivateKey; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Base64; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import utils.commandlineutils.CommandLineUtils; public class CustomKeyOpsConnect { // When run normally, we want to exit nicely even if something goes wrong // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("CustomKeyOpsPubSub execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } static class MyKeyOperationHandler implements TlsKeyOperationHandler { RSAPrivateKey key; MyKeyOperationHandler(String keyPath) { key = loadPrivateKey(keyPath); } public void performOperation(TlsKeyOperation operation) { try { System.out.println("MyKeyOperationHandler.performOperation" + operation.getType().name()); if (operation.getType() != TlsKeyOperation.Type.SIGN) { throw new RuntimeException("Simple sample only handles SIGN operations"); } if (operation.getSignatureAlgorithm() != TlsSignatureAlgorithm.RSA) { throw new RuntimeException("Simple sample only handles RSA keys"); } if (operation.getDigestAlgorithm() != TlsHashAlgorithm.SHA256) { throw new RuntimeException("Simple sample only handles SHA256 digests"); } // A SIGN operation's inputData is the 32bytes of the SHA-256 digest. // Before doing the RSA signature, we need to construct a PKCS1 v1.5 DigestInfo. // See https://datatracker.ietf.org/doc/html/rfc3447#section-9.2 byte[] digest = operation.getInput(); // These are the appropriate bytes for the SHA-256 AlgorithmIdentifier: // https://tools.ietf.org/html/rfc3447#page-43 byte[] sha256DigestAlgorithm = { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, (byte)0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 }; ByteArrayOutputStream digestInfoStream = new ByteArrayOutputStream(); digestInfoStream.write(sha256DigestAlgorithm); digestInfoStream.write(digest); byte[] digestInfo = digestInfoStream.toByteArray(); // Sign the DigestInfo Signature rsaSign = Signature.getInstance("NONEwithRSA"); rsaSign.initSign(key); rsaSign.update(digestInfo); byte[] signatureBytes = rsaSign.sign(); operation.complete(signatureBytes); } catch (Exception ex) { System.out.println("Error during key operation:" + ex); operation.completeExceptionally(ex); } } RSAPrivateKey loadPrivateKey(String filepath) { /* Adapted from: https://stackoverflow.com/a/27621696 * You probably need to convert your private key file from PKCS#1 * to PKCS#8 to get it working with this sample: * * $ openssl pkcs8 -topk8 -in my-private.pem.key -out my-private-pk8.pem.key -nocrypt * * IoT Core vends keys as PKCS#1 by default, * but Java only seems to have this PKCS8EncodedKeySpec class */ try { /* Read the BASE64-encoded contents of the private key file */ StringBuilder pemBase64 = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader(filepath))) { String line; while ((line = reader.readLine()) != null) { // Strip off PEM header and footer if (line.startsWith("---")) { if (line.contains("RSA")) { throw new RuntimeException("private key must be converted from PKCS#1 to PKCS#8"); } continue; } pemBase64.append(line); } } String pemBase64String = pemBase64.toString(); byte[] der = Base64.getDecoder().decode(pemBase64String); /* Create PrivateKey instance */ PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(der); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); return (RSAPrivateKey)privateKey; } catch (Exception ex) { throw new RuntimeException(ex); } } } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("CustomKeyOpsConnect", args); MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; MyKeyOperationHandler myKeyOperationHandler = new MyKeyOperationHandler(cmdData.input_key); TlsContextCustomKeyOperationOptions keyOperationOptions = new TlsContextCustomKeyOperationOptions(myKeyOperationHandler) .withCertificateFilePath(cmdData.input_cert); try { /** * Create the MQTT connection from the builder */ AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsCustomKeyOperationsBuilder(keyOperationOptions); if (cmdData.input_ca != "") { builder.withCertificateAuthorityFromPath(null, cmdData.input_ca); } builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withPort((short)cmdData.input_port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); if (cmdData.input_proxyHost != "" && cmdData.input_proxyPort > 0) { HttpProxyOptions proxyOptions = new HttpProxyOptions(); proxyOptions.setHost(cmdData.input_proxyHost); proxyOptions.setPort(cmdData.input_proxyPort); builder.withHttpProxyOptions(proxyOptions); } MqttClientConnection connection = builder.build(); builder.close(); /** * Verify the connection was created */ if (connection == null) { onApplicationFailure(new RuntimeException("MQTT connection creation failed!")); } /** * Connect and disconnect */ CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!"); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } System.out.println("Disconnecting..."); CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); System.out.println("Disconnected."); /** * Close the connection now that it is complete */ connection.close(); } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { onApplicationFailure(ex); } CrtResource.waitForNoResources(); System.out.println("Complete!"); } }
5,172
0
Create_ds/aws-iot-device-sdk-java-v2/samples/Shadow/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/Shadow/src/main/java/shadow/Mqtt5ShadowSample.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package shadow; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.crt.mqtt5.packets.*; import software.amazon.awssdk.crt.mqtt5.*; import software.amazon.awssdk.crt.mqtt5.Mqtt5ClientOptions; import software.amazon.awssdk.crt.mqtt5.Mqtt5Client; import software.amazon.awssdk.iot.AwsIotMqtt5ClientBuilder; import software.amazon.awssdk.iot.iotshadow.IotShadowClient; import software.amazon.awssdk.iot.iotshadow.model.ErrorResponse; import software.amazon.awssdk.iot.iotshadow.model.GetShadowRequest; import software.amazon.awssdk.iot.iotshadow.model.GetShadowResponse; import software.amazon.awssdk.iot.iotshadow.model.GetShadowSubscriptionRequest; import software.amazon.awssdk.iot.iotshadow.model.ShadowDeltaUpdatedEvent; import software.amazon.awssdk.iot.iotshadow.model.ShadowDeltaUpdatedSubscriptionRequest; import software.amazon.awssdk.iot.iotshadow.model.ShadowState; import software.amazon.awssdk.iot.iotshadow.model.UpdateShadowRequest; import software.amazon.awssdk.iot.iotshadow.model.UpdateShadowResponse; import software.amazon.awssdk.iot.iotshadow.model.UpdateShadowSubscriptionRequest; import java.util.HashMap; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.ExecutionException; import java.util.Scanner; import utils.commandlineutils.CommandLineUtils; public class Mqtt5ShadowSample { static final class SampleLifecycleEvents implements Mqtt5ClientOptions.LifecycleEvents { CompletableFuture<Void> connectedFuture = new CompletableFuture<>(); CompletableFuture<Void> stoppedFuture = new CompletableFuture<>(); @Override public void onAttemptingConnect(Mqtt5Client client, OnAttemptingConnectReturn onAttemptingConnectReturn) { System.out.println("Mqtt5 Client: Attempting connection..."); } @Override public void onConnectionSuccess(Mqtt5Client client, OnConnectionSuccessReturn onConnectionSuccessReturn) { System.out.println("Mqtt5 Client: Connection success, client ID: " + onConnectionSuccessReturn.getNegotiatedSettings().getAssignedClientID()); connectedFuture.complete(null); } @Override public void onConnectionFailure(Mqtt5Client client, OnConnectionFailureReturn onConnectionFailureReturn) { String errorString = CRT.awsErrorString(onConnectionFailureReturn.getErrorCode()); System.out.println("Mqtt5 Client: Connection failed with error: " + errorString); connectedFuture.completeExceptionally(new Exception("Could not connect: " + errorString)); } @Override public void onDisconnection(Mqtt5Client client, OnDisconnectionReturn onDisconnectionReturn) { System.out.println("Mqtt5 Client: Disconnected"); DisconnectPacket disconnectPacket = onDisconnectionReturn.getDisconnectPacket(); if (disconnectPacket != null) { System.out.println("\tDisconnection packet code: " + disconnectPacket.getReasonCode()); System.out.println("\tDisconnection packet reason: " + disconnectPacket.getReasonString()); } } @Override public void onStopped(Mqtt5Client client, OnStoppedReturn onStoppedReturn) { System.out.println("Mqtt5 Client: Stopped"); stoppedFuture.complete(null); } } // When run normally, we want to get input from the console // When run from CI, we want to automatically make changes to the shadow // document static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static String input_thingName; final static String SHADOW_PROPERTY = "color"; final static String SHADOW_VALUE_DEFAULT = "off"; static IotShadowClient shadow; static String localValue = null; static CompletableFuture<Void> gotResponse; static CommandLineUtils cmdUtils; static void onGetShadowAccepted(GetShadowResponse response) { System.out.println("Received initial shadow state"); if (response.state != null && localValue == null) { gotResponse.complete(null); if (response.state.delta != null) { String value = response.state.delta.get(SHADOW_PROPERTY).toString(); System.out.println(" Shadow delta value: " + value); return; } if (response.state.reported != null) { String value = response.state.reported.get(SHADOW_PROPERTY).toString(); System.out.println(" Shadow reported value: " + value); // Initialize local value to match the reported shadow value localValue = value; return; } } System.out.println(" Shadow document has no value for " + SHADOW_PROPERTY + ". Setting default..."); changeShadowValue(SHADOW_VALUE_DEFAULT); } static void onGetShadowRejected(ErrorResponse response) { if (response.code == 404) { System.out.println("Thing has no shadow document. Creating with defaults..."); changeShadowValue(SHADOW_VALUE_DEFAULT); return; } gotResponse.complete(null); System.out.println("GetShadow request was rejected: code: " + response.code + " message: " + response.message); System.exit(1); } static void onShadowDeltaUpdated(ShadowDeltaUpdatedEvent response) { System.out.println("Shadow delta updated"); if (response.state != null && response.state.containsKey(SHADOW_PROPERTY)) { String value = response.state.get(SHADOW_PROPERTY).toString(); System.out.println(" Delta wants to change value to '" + value + "'. Changing local value..."); if (!response.clientToken.isEmpty()) { System.out.print(" ClientToken: " + response.clientToken + "\n"); } changeShadowValue(value); } else { System.out.println(" Delta did not report a change in " + SHADOW_PROPERTY); } } static void onUpdateShadowAccepted(UpdateShadowResponse response) { if (response.state.reported != null) { if (response.state.reported.containsKey(SHADOW_PROPERTY)) { String value = response.state.reported.get(SHADOW_PROPERTY).toString(); System.out.println("Shadow updated, value is " + value); } else { System.out.println("Shadow updated, value is Null"); } } else { if (response.state.reportedIsNullable == true) { System.out.println("Shadow updated, reported and desired is null"); } else { System.out.println("Shadow update, data cleared"); } } gotResponse.complete(null); } static void onUpdateShadowRejected(ErrorResponse response) { System.out.println("Shadow update was rejected: code: " + response.code + " message: " + response.message); System.exit(2); } static CompletableFuture<Void> changeShadowValue(String value) { if (localValue != null) { if (localValue.equals(value)) { System.out.println("Local value is already " + value); CompletableFuture<Void> result = new CompletableFuture<>(); result.complete(null); return result; } } System.out.println("Changed local value to " + value); localValue = value; System.out.println("Updating shadow value to " + value); // build a request to let the service know our current value and desired value, // and that we only want // to update if the version matches the version we know about UpdateShadowRequest request = new UpdateShadowRequest(); request.thingName = input_thingName; request.state = new ShadowState(); if (value.compareToIgnoreCase("clear_shadow") == 0) { request.state.desiredIsNullable = true; request.state.reportedIsNullable = true; request.state.desired = null; request.state.reported = null; } else if (value.compareToIgnoreCase("null") == 0) { // A bit of a hack - we have to set reportedNullIsValid OR desiredNullIsValid // so the JSON formatter will allow null , otherwise null will always be // be converted to "null" // As long as we're passing a Hashmap that is NOT assigned to null, it will not // clear the data - so we pass an empty HashMap to avoid clearing data we want // to keep request.state.desiredIsNullable = true; request.state.reportedIsNullable = false; // We will only clear desired, so we need to pass an empty HashMap for reported request.state.reported = new HashMap<String, Object>() { { } }; request.state.desired = new HashMap<String, Object>() { { put(SHADOW_PROPERTY, null); } }; } else { request.state.reported = new HashMap<String, Object>() { { put(SHADOW_PROPERTY, value); } }; request.state.desired = new HashMap<String, Object>() { { put(SHADOW_PROPERTY, value); } }; } // Publish the request return shadow.PublishUpdateShadow(request, QualityOfService.AT_LEAST_ONCE).thenRun(() -> { System.out.println("Update request published"); }).exceptionally((ex) -> { System.out.println("Update request failed: " + ex.getMessage()); System.exit(3); return null; }); } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single * struct for * use in this sample. This handles all of the command line parsing, validating, * etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("Shadow", args); input_thingName = cmdData.input_thingName; try { /** * Create the MQTT5 client from the builder */ SampleLifecycleEvents lifecycleEvents = new SampleLifecycleEvents(); AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newDirectMqttBuilderWithMtlsFromPath( cmdData.input_endpoint, cmdData.input_cert, cmdData.input_key); ConnectPacket.ConnectPacketBuilder connectProperties = new ConnectPacket.ConnectPacketBuilder(); connectProperties.withClientId(cmdData.input_clientId); builder.withConnectProperties(connectProperties); builder.withLifeCycleEvents(lifecycleEvents); Mqtt5Client client = builder.build(); builder.close(); MqttClientConnection connection = new MqttClientConnection(client, null); // Create the shadow client, IotShadowClient throws MqttException shadow = new IotShadowClient(connection); // Connect client.start(); try { lifecycleEvents.connectedFuture.get(60, TimeUnit.SECONDS); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } /** * Subscribe to shadow topics */ System.out.println("Subscribing to shadow delta events..."); ShadowDeltaUpdatedSubscriptionRequest requestShadowDeltaUpdated = new ShadowDeltaUpdatedSubscriptionRequest(); requestShadowDeltaUpdated.thingName = input_thingName; CompletableFuture<Integer> subscribedToDeltas = shadow.SubscribeToShadowDeltaUpdatedEvents( requestShadowDeltaUpdated, QualityOfService.AT_LEAST_ONCE, Mqtt5ShadowSample::onShadowDeltaUpdated); subscribedToDeltas.get(); System.out.println("Subscribing to update responses..."); UpdateShadowSubscriptionRequest requestUpdateShadow = new UpdateShadowSubscriptionRequest(); requestUpdateShadow.thingName = input_thingName; CompletableFuture<Integer> subscribedToUpdateAccepted = shadow.SubscribeToUpdateShadowAccepted( requestUpdateShadow, QualityOfService.AT_LEAST_ONCE, Mqtt5ShadowSample::onUpdateShadowAccepted); CompletableFuture<Integer> subscribedToUpdateRejected = shadow.SubscribeToUpdateShadowRejected( requestUpdateShadow, QualityOfService.AT_LEAST_ONCE, Mqtt5ShadowSample::onUpdateShadowRejected); subscribedToUpdateAccepted.get(); subscribedToUpdateRejected.get(); System.out.println("Subscribing to get responses..."); GetShadowSubscriptionRequest requestGetShadow = new GetShadowSubscriptionRequest(); requestGetShadow.thingName = input_thingName; CompletableFuture<Integer> subscribedToGetShadowAccepted = shadow.SubscribeToGetShadowAccepted( requestGetShadow, QualityOfService.AT_LEAST_ONCE, Mqtt5ShadowSample::onGetShadowAccepted); CompletableFuture<Integer> subscribedToGetShadowRejected = shadow.SubscribeToGetShadowRejected( requestGetShadow, QualityOfService.AT_LEAST_ONCE, Mqtt5ShadowSample::onGetShadowRejected); subscribedToGetShadowAccepted.get(); subscribedToGetShadowRejected.get(); gotResponse = new CompletableFuture<>(); System.out.println("Requesting current shadow state..."); GetShadowRequest getShadowRequest = new GetShadowRequest(); getShadowRequest.thingName = input_thingName; CompletableFuture<Integer> publishedGetShadow = shadow.PublishGetShadow( getShadowRequest, QualityOfService.AT_LEAST_ONCE); publishedGetShadow.get(); gotResponse.get(); // If this is not running in CI, then take input from the console if (isCI == false) { String newValue = ""; Scanner scanner = new Scanner(System.in); while (true) { System.out.print(SHADOW_PROPERTY + "> "); System.out.flush(); newValue = scanner.next(); if (newValue.compareToIgnoreCase("quit") == 0) { break; } gotResponse = new CompletableFuture<>(); changeShadowValue(newValue).get(); gotResponse.get(); } scanner.close(); } // If this is in running in CI, then automatically update the shadow else { int messages_sent = 0; String message_string = ""; while (messages_sent < 5) { gotResponse = new CompletableFuture<>(); message_string = "Shadow_Value_" + String.valueOf(messages_sent); changeShadowValue(message_string).get(); gotResponse.get(); messages_sent += 1; } } // Disconnect client.stop(null); try { lifecycleEvents.stoppedFuture.get(60, TimeUnit.SECONDS); } catch (Exception ex) { System.out.println("Exception encountered: " + ex.toString()); System.exit(1); } /* Close the client to free memory */ connection.close(); client.close(); } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { System.out.println("Exception encountered: " + ex.toString()); System.exit(1); } System.out.println("Complete!"); CrtResource.waitForNoResources(); } }
5,173
0
Create_ds/aws-iot-device-sdk-java-v2/samples/Shadow/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/Shadow/src/main/java/shadow/ShadowSample.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package shadow; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import software.amazon.awssdk.iot.iotshadow.IotShadowClient; import software.amazon.awssdk.iot.iotshadow.model.ErrorResponse; import software.amazon.awssdk.iot.iotshadow.model.GetShadowRequest; import software.amazon.awssdk.iot.iotshadow.model.GetShadowResponse; import software.amazon.awssdk.iot.iotshadow.model.GetShadowSubscriptionRequest; import software.amazon.awssdk.iot.iotshadow.model.ShadowDeltaUpdatedEvent; import software.amazon.awssdk.iot.iotshadow.model.ShadowDeltaUpdatedSubscriptionRequest; import software.amazon.awssdk.iot.iotshadow.model.ShadowState; import software.amazon.awssdk.iot.iotshadow.model.UpdateShadowRequest; import software.amazon.awssdk.iot.iotshadow.model.UpdateShadowResponse; import software.amazon.awssdk.iot.iotshadow.model.UpdateShadowSubscriptionRequest; import java.util.HashMap; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.Scanner; import utils.commandlineutils.CommandLineUtils; public class ShadowSample { // When run normally, we want to get input from the console // When run from CI, we want to automatically make changes to the shadow document static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static String input_thingName; final static String SHADOW_PROPERTY = "color"; final static String SHADOW_VALUE_DEFAULT = "off"; static MqttClientConnection connection; static IotShadowClient shadow; static String localValue = null; static CompletableFuture<Void> gotResponse; static CommandLineUtils cmdUtils; static void onGetShadowAccepted(GetShadowResponse response) { System.out.println("Received initial shadow state"); if (response.state != null && localValue == null) { gotResponse.complete(null); if (response.state.delta != null) { String value = response.state.delta.get(SHADOW_PROPERTY).toString(); System.out.println(" Shadow delta value: " + value); return; } if (response.state.reported != null) { String value = response.state.reported.get(SHADOW_PROPERTY).toString(); System.out.println(" Shadow reported value: " + value); // Initialize local value to match the reported shadow value localValue = value; return; } } System.out.println(" Shadow document has no value for " + SHADOW_PROPERTY + ". Setting default..."); changeShadowValue(SHADOW_VALUE_DEFAULT); } static void onGetShadowRejected(ErrorResponse response) { if (response.code == 404) { System.out.println("Thing has no shadow document. Creating with defaults..."); changeShadowValue(SHADOW_VALUE_DEFAULT); return; } gotResponse.complete(null); System.out.println("GetShadow request was rejected: code: " + response.code + " message: " + response.message); System.exit(1); } static void onShadowDeltaUpdated(ShadowDeltaUpdatedEvent response) { System.out.println("Shadow delta updated"); if (response.state != null && response.state.containsKey(SHADOW_PROPERTY)) { String value = response.state.get(SHADOW_PROPERTY).toString(); System.out.println(" Delta wants to change value to '" + value + "'. Changing local value..."); if (!response.clientToken.isEmpty()) { System.out.print(" ClientToken: " + response.clientToken + "\n"); } changeShadowValue(value); } else { System.out.println(" Delta did not report a change in " + SHADOW_PROPERTY); } } static void onUpdateShadowAccepted(UpdateShadowResponse response) { if (response.state.reported != null) { if (response.state.reported.containsKey(SHADOW_PROPERTY)) { String value = response.state.reported.get(SHADOW_PROPERTY).toString(); System.out.println("Shadow updated, value is " + value); } else { System.out.println("Shadow updated, value is Null"); } } else { if (response.state.reportedIsNullable == true) { System.out.println("Shadow updated, reported and desired is null"); } else { System.out.println("Shadow update, data cleared"); } } gotResponse.complete(null); } static void onUpdateShadowRejected(ErrorResponse response) { System.out.println("Shadow update was rejected: code: " + response.code + " message: " + response.message); System.exit(2); } static CompletableFuture<Void> changeShadowValue(String value) { if (localValue != null) { if (localValue.equals(value)) { System.out.println("Local value is already " + value); CompletableFuture<Void> result = new CompletableFuture<>(); result.complete(null); return result; } } System.out.println("Changed local value to " + value); localValue = value; System.out.println("Updating shadow value to " + value); // build a request to let the service know our current value and desired value, and that we only want // to update if the version matches the version we know about UpdateShadowRequest request = new UpdateShadowRequest(); request.thingName = input_thingName; request.state = new ShadowState(); if (value.compareToIgnoreCase("clear_shadow") == 0) { request.state.desiredIsNullable = true; request.state.reportedIsNullable = true; request.state.desired = null; request.state.reported = null; } else if (value.compareToIgnoreCase("null") == 0) { // A bit of a hack - we have to set reportedNullIsValid OR desiredNullIsValid // so the JSON formatter will allow null , otherwise null will always be // be converted to "null" // As long as we're passing a Hashmap that is NOT assigned to null, it will not // clear the data - so we pass an empty HashMap to avoid clearing data we want to keep request.state.desiredIsNullable = true; request.state.reportedIsNullable = false; // We will only clear desired, so we need to pass an empty HashMap for reported request.state.reported = new HashMap<String, Object>() {{}}; request.state.desired = new HashMap<String, Object>() {{ put(SHADOW_PROPERTY, null); }}; } else { request.state.reported = new HashMap<String, Object>() {{ put(SHADOW_PROPERTY, value); }}; request.state.desired = new HashMap<String, Object>() {{ put(SHADOW_PROPERTY, value); }}; } // Publish the request return shadow.PublishUpdateShadow(request, QualityOfService.AT_LEAST_ONCE).thenRun(() -> { System.out.println("Update request published"); }).exceptionally((ex) -> { System.out.println("Update request failed: " + ex.getMessage()); System.exit(3); return null; }); } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("Shadow", args); input_thingName = cmdData.input_thingName; MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; try { /** * Create the MQTT connection from the builder */ AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(cmdData.input_cert, cmdData.input_key); if (cmdData.input_ca != "") { builder.withCertificateAuthorityFromPath(null, cmdData.input_ca); } builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withPort((short)cmdData.input_port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); MqttClientConnection connection = builder.build(); builder.close(); // Create the shadow client shadow = new IotShadowClient(connection); // Connect CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); System.out.println("Connected to " + (!sessionPresent ? "clean" : "existing") + " session!"); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } /** * Subscribe to shadow topics */ System.out.println("Subscribing to shadow delta events..."); ShadowDeltaUpdatedSubscriptionRequest requestShadowDeltaUpdated = new ShadowDeltaUpdatedSubscriptionRequest(); requestShadowDeltaUpdated.thingName = input_thingName; CompletableFuture<Integer> subscribedToDeltas = shadow.SubscribeToShadowDeltaUpdatedEvents( requestShadowDeltaUpdated, QualityOfService.AT_LEAST_ONCE, ShadowSample::onShadowDeltaUpdated); subscribedToDeltas.get(); System.out.println("Subscribing to update responses..."); UpdateShadowSubscriptionRequest requestUpdateShadow = new UpdateShadowSubscriptionRequest(); requestUpdateShadow.thingName = input_thingName; CompletableFuture<Integer> subscribedToUpdateAccepted = shadow.SubscribeToUpdateShadowAccepted( requestUpdateShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onUpdateShadowAccepted); CompletableFuture<Integer> subscribedToUpdateRejected = shadow.SubscribeToUpdateShadowRejected( requestUpdateShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onUpdateShadowRejected); subscribedToUpdateAccepted.get(); subscribedToUpdateRejected.get(); System.out.println("Subscribing to get responses..."); GetShadowSubscriptionRequest requestGetShadow = new GetShadowSubscriptionRequest(); requestGetShadow.thingName = input_thingName; CompletableFuture<Integer> subscribedToGetShadowAccepted = shadow.SubscribeToGetShadowAccepted( requestGetShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onGetShadowAccepted); CompletableFuture<Integer> subscribedToGetShadowRejected = shadow.SubscribeToGetShadowRejected( requestGetShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onGetShadowRejected); subscribedToGetShadowAccepted.get(); subscribedToGetShadowRejected.get(); gotResponse = new CompletableFuture<>(); System.out.println("Requesting current shadow state..."); GetShadowRequest getShadowRequest = new GetShadowRequest(); getShadowRequest.thingName = input_thingName; CompletableFuture<Integer> publishedGetShadow = shadow.PublishGetShadow( getShadowRequest, QualityOfService.AT_LEAST_ONCE); publishedGetShadow.get(); gotResponse.get(); // If this is not running in CI, then take input from the console if (isCI == false) { String newValue = ""; Scanner scanner = new Scanner(System.in); while (true) { System.out.print(SHADOW_PROPERTY + "> "); System.out.flush(); newValue = scanner.next(); if (newValue.compareToIgnoreCase("quit") == 0) { break; } gotResponse = new CompletableFuture<>(); changeShadowValue(newValue).get(); gotResponse.get(); } scanner.close(); } // If this is in running in CI, then automatically update the shadow else { int messages_sent = 0; String message_string = ""; while (messages_sent < 5) { gotResponse = new CompletableFuture<>(); message_string = "Shadow_Value_" + String.valueOf(messages_sent); changeShadowValue(message_string).get(); gotResponse.get(); messages_sent += 1; } } // Disconnect CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); // Close the connection now that we are completely done with it. connection.close(); } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { System.out.println("Exception encountered: " + ex.toString()); System.exit(1); } System.out.println("Complete!"); CrtResource.waitForNoResources(); } }
5,174
0
Create_ds/aws-iot-device-sdk-java-v2/samples/CustomAuthorizerConnect/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/CustomAuthorizerConnect/src/main/java/customauthorizerconnect/CustomAuthorizerConnect.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package customauthorizerconnect; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.io.UnsupportedEncodingException; import utils.commandlineutils.CommandLineUtils; public class CustomAuthorizerConnect { // When run normally, we want to exit nicely even if something goes wrong // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("CustomAuthorizerConnect execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("CustomAuthorizerConnect", args); MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; try { /** * Create the MQTT connection from the builder */ AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newDefaultBuilder(); builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); builder.withCustomAuthorizer( cmdData.input_customAuthUsername, cmdData.input_customAuthorizerName, cmdData.input_customAuthorizerSignature, cmdData.input_customAuthPassword, cmdData.input_customAuthorizerTokenKeyName, cmdData.input_customAuthorizerTokenValue); MqttClientConnection connection = builder.build(); builder.close(); /** * Verify the connection was created */ if (connection == null) { onApplicationFailure(new RuntimeException("MQTT connection creation (through custom authorizer) failed!")); } /** * Connect and disconnect */ CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!"); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } System.out.println("Disconnecting..."); CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); System.out.println("Disconnected."); // Close the connection now that we are completely done with it. connection.close(); } catch (CrtRuntimeException | UnsupportedEncodingException | InterruptedException | ExecutionException ex) { onApplicationFailure(ex); } CrtResource.waitForNoResources(); System.out.println("Complete!"); } }
5,175
0
Create_ds/aws-iot-device-sdk-java-v2/samples/X509CredentialsProviderConnect/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/X509CredentialsProviderConnect/src/main/java/x509credentialsproviderconnect/X509CredentialsProviderConnect.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package x509credentialsproviderconnect; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.crt.io.TlsContextOptions; import software.amazon.awssdk.crt.io.ClientTlsContext; import software.amazon.awssdk.crt.auth.credentials.X509CredentialsProvider; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import java.util.concurrent.ExecutionException; import java.util.concurrent.CompletableFuture; import utils.commandlineutils.CommandLineUtils; public class X509CredentialsProviderConnect { // When run normally, we want to exit nicely even if something goes wrong // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("BasicConnect execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("x509CredentialsProviderConnect", args); MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; try { /** * Build the MQTT connection using the builder */ // ============================== AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(null, null); if (cmdData.input_ca != "") { builder.withCertificateAuthorityFromPath(null, cmdData.input_ca); } builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withPort((short)cmdData.input_port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); HttpProxyOptions proxyOptions = null; if (cmdData.input_proxyHost != "" && cmdData.input_proxyPort > 0) { proxyOptions = new HttpProxyOptions(); proxyOptions.setHost(cmdData.input_proxyHost); proxyOptions.setPort(cmdData.input_proxyPort); builder.withHttpProxyOptions(proxyOptions); } builder.withWebsockets(true); builder.withWebsocketSigningRegion(cmdData.input_signingRegion); TlsContextOptions x509TlsOptions = TlsContextOptions.createWithMtlsFromPath(cmdData.input_x509Cert, cmdData.input_x509Key); if (cmdData.input_x509Ca != null) { x509TlsOptions.withCertificateAuthorityFromPath(null, cmdData.input_x509Ca); } ClientTlsContext x509TlsContext = new ClientTlsContext(x509TlsOptions); X509CredentialsProvider.X509CredentialsProviderBuilder x509builder = new X509CredentialsProvider.X509CredentialsProviderBuilder() .withTlsContext(x509TlsContext) .withEndpoint(cmdData.input_x509Endpoint) .withRoleAlias(cmdData.input_x509Role) .withThingName(cmdData.input_x509ThingName) .withProxyOptions(proxyOptions); X509CredentialsProvider provider = x509builder.build(); builder.withWebsocketCredentialsProvider(provider); MqttClientConnection connection = builder.build(); builder.close(); provider.close(); if (connection == null) { onApplicationFailure(new RuntimeException("MQTT connection creation failed!")); } // ============================== /** * Connect and disconnect */ CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!"); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } System.out.println("Disconnecting..."); CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); System.out.println("Disconnected."); /** * Close the connection now that it is complete */ connection.close(); } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { onApplicationFailure(ex); } CrtResource.waitForNoResources(); System.out.println("Complete!"); } }
5,176
0
Create_ds/aws-iot-device-sdk-java-v2/samples/BasicConnect/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/BasicConnect/src/main/java/basicconnect/BasicConnect.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package basicconnect; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import java.util.concurrent.ExecutionException; import java.util.concurrent.CompletableFuture; import utils.commandlineutils.CommandLineUtils; public class BasicConnect { // When run normally, we want to exit nicely even if something goes wrong. // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code. static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("BasicConnect execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("BasicConnect", args); MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; try { /** * Create the MQTT connection from the builder */ AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(cmdData.input_cert, cmdData.input_key); if (cmdData.input_ca != "") { builder.withCertificateAuthorityFromPath(null, cmdData.input_ca); } builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withPort((short)cmdData.input_port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); if (cmdData.input_proxyHost != "" && cmdData.input_proxyPort > 0) { HttpProxyOptions proxyOptions = new HttpProxyOptions(); proxyOptions.setHost(cmdData.input_proxyHost); proxyOptions.setPort(cmdData.input_proxyPort); builder.withHttpProxyOptions(proxyOptions); } MqttClientConnection connection = builder.build(); builder.close(); /** * Verify the connection was created */ if (connection == null) { onApplicationFailure(new RuntimeException("MQTT connection creation failed!")); } /** * Connect and disconnect */ CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!"); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } System.out.println("Disconnecting..."); CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); System.out.println("Disconnected."); /** * Close the connection now that it is complete */ connection.close(); } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { onApplicationFailure(ex); } CrtResource.waitForNoResources(); System.out.println("Complete!"); } }
5,177
0
Create_ds/aws-iot-device-sdk-java-v2/samples/GreengrassIPC/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/GreengrassIPC/src/main/java/greengrass/GreengrassIPC.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ /** * This sample uses AWS IoT Greengrass V2 to publish messages from the Greengrass device to the * AWS IoT MQTT broker. * * This sample can be deployed as a Greengrass V2 component and it will publish 10 MQTT messages * over the course of 10 seconds. The IPC integration with Greengrass V2 allows this code to run * without additional IoT certificates or secrets, because it directly communicates with the * Greengrass core running on the device. As such, to run this sample you need Greengrass Core running. * * For more information, see the samples README.md file at: * https://github.com/aws/aws-iot-device-sdk-python-v2/tree/main/samples */ package greengrass; import java.nio.charset.StandardCharsets; import java.time.*; import java.time.format.DateTimeFormatter; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClientV2; import software.amazon.awssdk.aws.greengrass.model.PublishToIoTCoreRequest; import software.amazon.awssdk.aws.greengrass.model.PublishToIoTCoreResponse; import software.amazon.awssdk.aws.greengrass.model.QOS; class GreengrassIPC { // When run normally, we want to exit nicely even if something goes wrong // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); // Some constants for the payload data we send via IPC static double payloadBatteryStateCharge = 42.5; static double payloadLocationLongitude = 48.15743; static double payloadLocationLatitude = 11.57549; // The number of IPC messages to send static int sampleMessageCount = 10; static int sampleMessagesSent = 0; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("BasicPubSub execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } /** * A simple helper function to print a message when running locally (will not print in CI) */ static void logMessage(String message) { if (!isCI) { System.out.println(message); } } /** * A helper function to generate a JSON payload to send via IPC to simplify/separate sample code. */ public static String getIpcPayloadString() { // Get the current time as a formatted string String timestamp = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH:mm:ss").format(LocalDateTime.now()); // Construct a JSON string with the data StringBuilder builder = new StringBuilder(); builder.append("{"); builder.append("\"timestamp\":\"" + timestamp + "\","); builder.append("\"battery_state_of_charge\":" + payloadBatteryStateCharge + ","); builder.append("\"location\": {"); builder.append("\"longitude\":" + payloadLocationLongitude + ","); builder.append("\"latitude\":" + payloadLocationLatitude); builder.append("}"); builder.append("}"); return builder.toString(); } public static void main(String[] args) { logMessage("Greengrass IPC sample start"); // Create the Greengrass IPC client GreengrassCoreIPCClientV2 ipcClient = null; try { ipcClient = GreengrassCoreIPCClientV2.builder().build(); } catch (Exception ex) { logMessage("Failed to create Greengrass IPC client!"); onApplicationFailure(ex); System.exit(-1); } if (ipcClient == null) { logMessage("Failed to create Greengrass IPC client!"); onApplicationFailure(new Throwable("Error - IPC client not initialized!")); System.exit(-1); } // Create the topic name String topicNameFromEnv = System.getenv("AWS_IOT_THING_NAME"); if (topicNameFromEnv == null) { logMessage("Could not get IoT Thing name from AWS_IOT_THING_NAME. Using name 'TestThing'..."); topicNameFromEnv = "TestThing"; } String topicName = String.format("my/iot/%s/telementry", topicNameFromEnv); // Create the IPC request, except the payload. The payload will be created right before sending. PublishToIoTCoreRequest publishRequest = new PublishToIoTCoreRequest(); publishRequest.setQos(QOS.AT_LEAST_ONCE); publishRequest.setTopicName(topicName); try { logMessage("Will attempt to send " + sampleMessageCount + " IPC publishes to IoT Core"); while (sampleMessagesSent < sampleMessageCount) { logMessage("Sending message " + sampleMessagesSent++ + "..."); // Get the new IPC payload publishRequest.withPayload(getIpcPayloadString().getBytes(StandardCharsets.UTF_8)); CompletableFuture<PublishToIoTCoreResponse> publishFuture = ipcClient.publishToIoTCoreAsync(publishRequest); // Try to send the IPC message try { publishFuture.get(60, TimeUnit.SECONDS); logMessage("Successfully published IPC message to IoT Core"); } catch (Exception ex) { logMessage("Failed to publish IPC message to IoT Core"); } // Sleep for a second Thread.sleep(1000); } logMessage("All publishes sent. Finishing sample..."); ipcClient.close(); } catch (Exception ex) { logMessage("Something in Greengrass IPC sample failed by throwing an exception! Shutting down sample..."); onApplicationFailure(ex); try { ipcClient.close(); } catch (Exception closeEx) { onApplicationFailure(closeEx); } logMessage("Greengrass IPC sample finished with error"); System.exit(-1); } logMessage("Greengrass IPC sample finished"); System.exit(0); } }
5,178
0
Create_ds/aws-iot-device-sdk-java-v2/samples/Pkcs12Connect/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/Pkcs12Connect/src/main/java/pkcs12connect/Pkcs12Connect.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package pkcs12connect; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import java.util.concurrent.ExecutionException; import java.util.concurrent.CompletableFuture; import utils.commandlineutils.CommandLineUtils; public class Pkcs12Connect { // When run normally, we want to exit nicely even if something goes wrong. // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code. static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("Pkcs12Connect execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("Pkcs12Connect", args); MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; try { /** * Create the MQTT connection from the builder */ AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsPkcs12Builder(cmdData.input_pkcs12File, cmdData.input_pkcs12Password); if (cmdData.input_ca != "") { builder.withCertificateAuthorityFromPath(null, cmdData.input_ca); } builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withPort((short)cmdData.input_port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); MqttClientConnection connection = builder.build(); builder.close(); /** * Verify the connection was created */ if (connection == null) { onApplicationFailure(new RuntimeException("MQTT connection creation failed!")); } /** * Connect and disconnect */ CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!"); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } System.out.println("Disconnecting..."); CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); System.out.println("Disconnected."); /** * Close the connection now that it is complete */ connection.close(); } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { onApplicationFailure(ex); } CrtResource.waitForNoResources(); System.out.println("Complete!"); } }
5,179
0
Create_ds/aws-iot-device-sdk-java-v2/samples/Utils/CommandLineUtils/utils
Create_ds/aws-iot-device-sdk-java-v2/samples/Utils/CommandLineUtils/utils/commandlineutils/CommandLineUtils.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package utils.commandlineutils; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.CompletableFuture; import java.io.UnsupportedEncodingException; import software.amazon.awssdk.crt.*; import software.amazon.awssdk.crt.io.*; import software.amazon.awssdk.crt.mqtt.*; import software.amazon.awssdk.crt.mqtt5.*; import software.amazon.awssdk.crt.mqtt5.packets.*; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import software.amazon.awssdk.iot.AwsIotMqtt5ClientBuilder; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.crt.auth.credentials.X509CredentialsProvider; import software.amazon.awssdk.crt.auth.credentials.CognitoCredentialsProvider; import software.amazon.awssdk.crt.Log; import software.amazon.awssdk.crt.Log.LogLevel; public class CommandLineUtils { private String programName; private final HashMap<String, CommandLineOption> registeredCommands = new HashMap<>(); private List<String> commandArguments; private boolean isCI; /** * Functions for registering and command line arguments */ public void registerProgramName(String newProgramName) { programName = newProgramName; } public void registerCommand(CommandLineOption option) { if (registeredCommands.containsKey(option.commandName)) { System.out.println("Cannot register command: " + option.commandName + ". Command already registered"); return; } registeredCommands.put(option.commandName, option); } public void registerCommand(String commandName, String exampleInput, String helpOutput) { registerCommand(new CommandLineOption(commandName, exampleInput, helpOutput)); } public void removeCommand(String commandName) { registeredCommands.remove(commandName); } public void updateCommandHelp(String commandName, String newCommandHelp) { if (registeredCommands.containsKey(commandName)) { registeredCommands.get(commandName).helpOutput = newCommandHelp; } } public void sendArguments(String[] arguments) { // Automatically register the help command registerCommand(m_cmd_help, "", "Prints this message"); commandArguments = Arrays.asList(arguments); // Automatically check for help and print if present if (hasCommand(m_cmd_help)) { printHelp(); if (isCI == true) { throw new RuntimeException("Help argument called"); } else { System.exit(-1); } } } public boolean hasCommand(String command) { return commandArguments.contains("--" + command); } public String getCommand(String command) { for (Iterator<String> iter = commandArguments.iterator(); iter.hasNext();) { String value = iter.next(); if (Objects.equals(value,"--" + command)) { if (iter.hasNext()) { return iter.next(); } else { System.out.println("Error - found command but at end of arguments!\n"); return ""; } } } return ""; } public String getCommandOrDefault(String command, String commandDefault) { if (commandArguments.contains("--" + command)) { return getCommand(command); } return commandDefault; } public String getCommandRequired(String command) { if (commandArguments.contains("--" + command)) { return getCommand(command); } printHelp(); System.out.println("Missing required argument: --" + command + "\n"); if (isCI == true) { throw new RuntimeException("Missing required argument"); } else { System.exit(-1); } return ""; } public String getCommandRequired(String command, String commandAlt){ if(commandArguments.contains("--" + commandAlt)){ return getCommand(commandAlt); } return getCommandRequired(command); } public void printHelp() { System.out.println("Usage:"); String messageOne = programName; for (String commandName : registeredCommands.keySet()) { messageOne += " --" + commandName + " " + registeredCommands.get(commandName).exampleInput; } System.out.println(messageOne + "\n"); for (String commandName : registeredCommands.keySet()) { messageOne += " --" + commandName + " " + registeredCommands.get(commandName).exampleInput; System.out.println("* " + commandName + "\t\t" + registeredCommands.get(commandName).helpOutput); } } public void determineIfCI() { String ciPropValue = System.getProperty("aws.crt.ci"); isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); } /** * Helper functions for registering commands */ public void addCommonLoggingCommands() { registerCommand(m_cmd_verbosity, "<str>", "The amount of detail in the logging output of the sample." + " Options: 'Fatal', 'Error', 'Warn', 'Info', 'Debug', 'Trace' or 'None' (optional, default='None')."); registerCommand(m_cmd_log_destination, "<str>", "Where logging should be routed to." + " Options: 'Stdout', 'Stderr', 'File' (optional, default='Stderr')."); registerCommand(m_cmd_log_file_name, "<str>", "File name to save logging to." + " (optional, default='log.txt')."); } public void addClientIdAndPort() { registerCommand(m_cmd_client_id, "<int>", "Client id to use (optional, default='test-*')."); registerCommand(m_cmd_port, "<int>", "Port to connect to on the endpoint (optional, default='8883')."); } public void addCommonMQTTCommands() { registerCommand(m_cmd_endpoint, "<str>", "The endpoint of the mqtt server, not including a port."); registerCommand(m_cmd_ca_file, "<path>", "Path to AmazonRootCA1.pem (optional, system trust store used by default)."); } public void addCommonProxyCommands() { registerCommand(m_cmd_proxy_host, "<str>", "Websocket proxy host to use (optional, required if --proxy_port is set)."); registerCommand(m_cmd_proxy_port, "<int>", "Websocket proxy port to use (optional, default=8080, required if --proxy_host is set)."); } public void addCommonX509Commands() { registerCommand( m_cmd_x509_role, "<str>", "Role alias to use with the x509 credentials provider (required for x509)"); registerCommand(m_cmd_x509_endpoint, "<str>", "The credentials endpoint to fetch x509 credentials from (required for x509)"); registerCommand( m_cmd_x509_thing_name, "<str>", "Thing name to fetch x509 credentials on behalf of (required for x509)"); registerCommand( m_cmd_x509_cert_file, "<path>", "Path to the IoT thing certificate used in fetching x509 credentials (required for x509)"); registerCommand( m_cmd_x509_key_file, "<path>", "Path to the IoT thing private key used in fetching x509 credentials (required for x509)"); registerCommand( m_cmd_x509_ca_file, "<path>", "Path to the root certificate used in fetching x509 credentials (required for x509)"); } public void addCommonTopicMessageCommands() { registerCommand(m_cmd_message, "<str>", "The message to send in the payload (optional, default='Hello world!')"); registerCommand(m_cmd_topic, "<str>", "Topic to publish, subscribe to. (optional, default='test/topic')"); registerCommand(m_cmd_count, "<int>", "Number of messages to publish (optional, default='10')."); } public void addKeyAndCertCommands() { registerCommand(m_cmd_key_file, "<path>", "Path to your key in PEM format."); registerCommand(m_cmd_cert_file, "<path>", "Path to your client certificate in PEM format."); } /** * Helper functions for parsing commands */ private void parseCommonLoggingCommands(SampleCommandLineData returnData){ String verbosity = getCommandOrDefault(m_cmd_verbosity, "None"); String log_destination = getCommandOrDefault(m_cmd_log_destination, "Stderr"); String log_file_name = getCommandOrDefault(m_cmd_log_file_name, "log.txt"); if(verbosity != "None"){ switch (log_destination) { case "Stderr": Log.initLoggingToStderr(LogLevel.valueOf(verbosity)); break; case "Stdout": Log.initLoggingToStdout(LogLevel.valueOf(verbosity)); break; case "File": Log.initLoggingToFile(LogLevel.valueOf(verbosity), log_file_name); break; default: break; } } } private void parseCommonMQTTCommands(SampleCommandLineData returnData) { returnData.input_endpoint = getCommandRequired(m_cmd_endpoint); returnData.input_ca = getCommandOrDefault(m_cmd_ca_file, ""); } private void parseKeyAndCertCommands(SampleCommandLineData returnData) { returnData.input_cert = getCommandRequired(m_cmd_cert_file); returnData.input_key = getCommandRequired(m_cmd_key_file); } private void parseClientIdAndPort(SampleCommandLineData returnData) { returnData.input_clientId = getCommandOrDefault(m_cmd_client_id, "test-" + UUID.randomUUID().toString()); returnData.input_port = Integer.parseInt(getCommandOrDefault(m_cmd_port, "8883")); } private void parseCommonTopicMessageCommands(SampleCommandLineData returnData) { if (isCI == true) { returnData.input_topic = getCommandOrDefault(m_cmd_topic, "test/topic/" + UUID.randomUUID().toString()); returnData.input_message = getCommandOrDefault(m_cmd_message, "Hello World!"); } else { returnData.input_topic = getCommandOrDefault(m_cmd_topic, "test/topic"); returnData.input_message = getCommandOrDefault(m_cmd_message, "Hello World!"); } returnData.input_count = Integer.parseInt(getCommandOrDefault(m_cmd_count, "10")); } private void parseCommonProxyCommands(SampleCommandLineData returnData) { returnData.input_proxyHost = getCommandOrDefault(m_cmd_proxy_host, ""); returnData.input_proxyPort = Integer.parseInt(getCommandOrDefault(m_cmd_proxy_port, "0")); } private void parseCommonX509Commands(SampleCommandLineData returnData) { returnData.input_x509Endpoint = getCommandRequired(m_cmd_x509_endpoint); returnData.input_x509Role = getCommandRequired(m_cmd_x509_role); returnData.input_x509ThingName = getCommandRequired(m_cmd_x509_thing_name); returnData.input_x509Cert = getCommandRequired(m_cmd_x509_cert_file); returnData.input_x509Key = getCommandRequired(m_cmd_x509_key_file); returnData.input_x509Ca = getCommandOrDefault(m_cmd_x509_ca_file, null); } /** * Functions to register commands on a per-sample basis, as well as getting a struct containing all the data */ public class SampleCommandLineData { // General use public String input_endpoint; public String input_cert; public String input_key; public String input_ca; public String input_clientId; public int input_port; // Proxy public String input_proxyHost; public int input_proxyPort; // PubSub public String input_topic; public String input_message; public int input_count; // Websockets public String input_signingRegion; // Cognito public String input_cognitoIdentity; // Custom auth public String input_customAuthUsername; public String input_customAuthorizerName; public String input_customAuthorizerSignature; public String input_customAuthPassword; public String input_customAuthorizerTokenKeyName; public String input_customAuthorizerTokenValue; // Fleet provisioning public String input_templateName; public String input_templateParameters; public String input_csrPath; // Services (Shadow, Jobs, Greengrass, etc) public String input_thingName; public String input_mode; // Java Keystore public String input_keystore; public String input_keystorePassword; public String input_keystoreFormat; public String input_certificateAlias; public String input_certificatePassword; // Shared Subscription public String input_groupIdentifier; // PKCS#11 public String input_pkcs11LibPath; public String input_pkcs11UserPin; public String input_pkcs11TokenLabel; public Long input_pkcs11SlotId; public String input_pkcs11KeyLabel; // Raw Connect public String input_username; public String input_password; public String input_protocolName; public List<String> input_authParams; // X509 public String input_x509Endpoint; public String input_x509Role; public String input_x509ThingName; public String input_x509Cert; public String input_x509Key; public String input_x509Ca; // PKCS12 public String input_pkcs12File; public String input_pkcs12Password; // Greengrass Basic Discovery public Boolean inputPrintDiscoverRespOnly; } public SampleCommandLineData parseSampleInputBasicConnect(String[] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); addCommonProxyCommands(); addKeyAndCertCommands(); addClientIdAndPort(); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); parseCommonProxyCommands(returnData); parseKeyAndCertCommands(returnData); parseClientIdAndPort(returnData); return returnData; } public SampleCommandLineData parseSampleInputPubSub(String [] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); addCommonTopicMessageCommands(); addKeyAndCertCommands(); addCommonProxyCommands(); addClientIdAndPort(); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); parseKeyAndCertCommands(returnData); parseCommonTopicMessageCommands(returnData); parseCommonProxyCommands(returnData); parseClientIdAndPort(returnData); return returnData; } public SampleCommandLineData parseSampleInputCognitoConnect(String [] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); registerCommand(m_cmd_signing_region, "<str>", "AWS IoT service region."); registerCommand(m_cmd_client_id, "<int>", "Client id to use (optional, default='test-*')."); registerCommand(m_cmd_cognito_identity, "<str>", "The Cognito identity ID to use to connect via Cognito"); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); returnData.input_signingRegion = getCommandRequired(m_cmd_signing_region, m_cmd_region); returnData.input_clientId = getCommandOrDefault(m_cmd_client_id, "test-" + UUID.randomUUID().toString()); returnData.input_cognitoIdentity = getCommandRequired(m_cmd_cognito_identity); return returnData; } public SampleCommandLineData parseSampleInputCustomAuthorizerConnect(String [] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); registerCommand(m_cmd_client_id, "<int>", "Client id to use (optional, default='test-*')."); registerCommand(m_cmd_custom_auth_username, "<str>", "Username for connecting to custom authorizer (optional, default=null)."); registerCommand(m_cmd_custom_auth_authorizer_name, "<str>", "Name of custom authorizer (optional, default=null)."); registerCommand(m_cmd_custom_auth_authorizer_signature, "<str>", "Signature passed when connecting to custom authorizer (optional, default=null)."); registerCommand(m_cmd_custom_auth_password, "<str>", "Password for connecting to custom authorizer (optional, default=null)."); registerCommand(m_cmd_custom_auth_token_key_name, "<str>", "Key used to extract the custom authorizer token (optional, default=null)."); registerCommand(m_cmd_custom_auth_token_value, "<str>", "The opaque token value for the custom authorizer (optional, default=null)."); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); returnData.input_clientId = getCommandOrDefault(m_cmd_client_id, "test-" + UUID.randomUUID().toString()); returnData.input_customAuthUsername = getCommandOrDefault(m_cmd_custom_auth_username, null); returnData.input_customAuthorizerName = getCommandOrDefault(m_cmd_custom_auth_authorizer_name, null); returnData.input_customAuthorizerSignature = getCommandOrDefault(m_cmd_custom_auth_authorizer_signature, null); returnData.input_customAuthPassword = getCommandOrDefault(m_cmd_custom_auth_password, null); returnData.input_customAuthorizerTokenKeyName = getCommandOrDefault(m_cmd_custom_auth_token_key_name, null); returnData.input_customAuthorizerTokenValue = getCommandOrDefault(m_cmd_custom_auth_token_value, null); return returnData; } public SampleCommandLineData parseSampleInputCustomKeyOpsConnect(String [] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); addKeyAndCertCommands(); addClientIdAndPort(); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); parseKeyAndCertCommands(returnData); parseClientIdAndPort(returnData); return returnData; } public SampleCommandLineData parseSampleInputFleetProvisioning(String [] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); addKeyAndCertCommands(); addClientIdAndPort(); registerCommand(m_cmd_fleet_template_name, "<str>", "Provisioning template name."); registerCommand(m_cmd_fleet_template_parameters, "<json>", "Provisioning template parameters."); registerCommand(m_cmd_fleet_template_csr, "<path>", "Path to the CSR file (optional)."); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); parseKeyAndCertCommands(returnData); parseClientIdAndPort(returnData); returnData.input_templateName = getCommandRequired(m_cmd_fleet_template_name); returnData.input_templateParameters = getCommandRequired(m_cmd_fleet_template_parameters); returnData.input_csrPath = getCommandOrDefault(m_cmd_fleet_template_csr, null); return returnData; } public SampleCommandLineData parseSampleInputGreengrassDiscovery(String [] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); removeCommand(m_cmd_endpoint); addKeyAndCertCommands(); addCommonProxyCommands(); registerCommand(m_cmd_region, "<str>", "AWS IoT service region (optional, default='us-east-1')."); registerCommand(m_cmd_thing_name, "<str>", "The name of the IoT thing."); registerCommand(m_cmd_topic, "<str>", "Topic to subscribe/publish to (optional, default='test/topic')."); registerCommand(m_cmd_mode, "<str>", "Mode options: 'both', 'publish', or 'subscribe' (optional, default='both')."); registerCommand(m_cmd_print_discover_resp_only, "<str>", "Exists the sample after printing the discovery result (optional, default='False')"); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseKeyAndCertCommands(returnData); returnData.input_ca = getCommandOrDefault(m_cmd_ca_file, null); returnData.input_thingName = getCommandRequired(m_cmd_thing_name); returnData.input_signingRegion = getCommandRequired(m_cmd_region, m_cmd_signing_region); returnData.input_topic = getCommandOrDefault(m_cmd_topic, "test/topic"); returnData.input_mode = getCommandOrDefault(m_cmd_mode, "Hello World!"); returnData.input_proxyHost = getCommandOrDefault(m_cmd_proxy_host, ""); returnData.input_proxyPort = Integer.parseInt(getCommandOrDefault(m_cmd_proxy_port, "0")); returnData.inputPrintDiscoverRespOnly = hasCommand(m_cmd_print_discover_resp_only); return returnData; } public SampleCommandLineData parseSampleInputKeystoreConnect(String [] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); addCommonProxyCommands(); addClientIdAndPort(); registerCommand(m_cmd_javakeystore_path, "<file>", "The path to the Java keystore to use"); registerCommand(m_cmd_javakeystore_password, "<str>", "The password for the Java keystore"); registerCommand(m_cmd_javakeystore_format, "<str>", "The format of the Java keystore (optional, default='PKCS12')"); registerCommand(m_cmd_javakeystore_certificate, "<str>", "The certificate alias to use to access the key and certificate in the Java keystore"); registerCommand(m_cmd_javakeystore_key_password, "<str>", "The password associated with the key and certificate in the Java keystore"); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); parseCommonProxyCommands(returnData); parseClientIdAndPort(returnData); returnData.input_keystore = getCommandRequired(m_cmd_javakeystore_path); returnData.input_keystorePassword = getCommandRequired(m_cmd_javakeystore_password); returnData.input_keystoreFormat = getCommandOrDefault(m_cmd_javakeystore_format, "PKCS12"); returnData.input_certificateAlias = getCommandRequired(m_cmd_javakeystore_certificate); returnData.input_certificatePassword = getCommandRequired(m_cmd_javakeystore_key_password); return returnData; } public SampleCommandLineData parseSampleInputJobs(String[] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); addKeyAndCertCommands(); addClientIdAndPort(); registerCommand(m_cmd_thing_name, "<str>", "The name of the IoT thing."); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); parseKeyAndCertCommands(returnData); parseClientIdAndPort(returnData); returnData.input_thingName = getCommandRequired(m_cmd_thing_name); return returnData; } public SampleCommandLineData parseSampleInputMqtt5PubSub(String [] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); addCommonTopicMessageCommands(); addKeyAndCertCommands(); addCommonProxyCommands(); addClientIdAndPort(); registerCommand(m_cmd_signing_region, "<string>", "Websocket region to use (will use websockets to connect if defined)."); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); parseCommonTopicMessageCommands(returnData); parseKeyAndCertCommands(returnData); parseCommonProxyCommands(returnData); parseClientIdAndPort(returnData); returnData.input_signingRegion = getCommandOrDefault(m_cmd_signing_region, null); return returnData; } public SampleCommandLineData parseSampleInputMqtt5SharedSubscription(String [] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); addCommonTopicMessageCommands(); addKeyAndCertCommands(); addCommonProxyCommands(); addClientIdAndPort(); registerCommand(m_cmd_group_identifier, "<string>", "The group identifier to use in the shared subscription (optional, default='java-sample')"); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); parseCommonTopicMessageCommands(returnData); parseKeyAndCertCommands(returnData); parseCommonProxyCommands(returnData); parseClientIdAndPort(returnData); returnData.input_groupIdentifier = getCommandOrDefault(m_cmd_group_identifier, "java-sample"); return returnData; } public SampleCommandLineData parseSampleInputPkcs11Connect(String [] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); addClientIdAndPort(); registerCommand(m_cmd_cert_file, "<path>", "Path to your client certificate in PEM format."); registerCommand(m_cmd_pkcs11_lib, "<path>", "Path to PKCS#11 library."); registerCommand(m_cmd_pkcs11_pin, "<int>", "User PIN for logging into PKCS#11 token."); registerCommand(m_cmd_pkcs11_token, "<str>", "Label of PKCS#11 token to use (optional)."); registerCommand(m_cmd_pkcs11_slot, "<int>", "Slot ID containing PKCS#11 token to use (optional)."); registerCommand(m_cmd_pkcs11_key, "<str>", "Label of private key on the PKCS#11 token (optional)."); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); parseClientIdAndPort(returnData); returnData.input_cert = getCommandRequired(m_cmd_cert_file); returnData.input_pkcs11LibPath = getCommandRequired(m_cmd_pkcs11_lib); returnData.input_pkcs11UserPin = getCommandRequired(m_cmd_pkcs11_pin); returnData.input_pkcs11TokenLabel = getCommandOrDefault(m_cmd_pkcs11_token, ""); returnData.input_pkcs11SlotId = null; if (hasCommand(m_cmd_pkcs11_slot)) { returnData.input_pkcs11SlotId = Long.parseLong(getCommandOrDefault(m_cmd_pkcs11_slot, "-1")); } returnData.input_pkcs11KeyLabel = getCommandOrDefault(m_cmd_pkcs11_key, ""); return returnData; } public SampleCommandLineData parseSampleInputShadow(String [] args) { // Shadow and Jobs use the same inputs currently return parseSampleInputJobs(args); } public SampleCommandLineData parseSampleInputWebsocketConnect(String [] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); addCommonProxyCommands(); registerCommand(m_cmd_signing_region, "<str>", "AWS IoT service region."); registerCommand(m_cmd_client_id, "<int>", "Client id to use (optional, default='test-*')."); registerCommand(m_cmd_port, "<int>", "Port to connect to on the endpoint (optional, default='443')."); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); parseCommonProxyCommands(returnData); returnData.input_signingRegion = getCommandRequired(m_cmd_signing_region, m_cmd_region); returnData.input_clientId = getCommandOrDefault(m_cmd_client_id, "test-" + UUID.randomUUID().toString()); returnData.input_port = Integer.parseInt(getCommandOrDefault(m_cmd_port, "443")); return returnData; } public SampleCommandLineData parseSampleInputWindowsCertConnect(String [] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); addClientIdAndPort(); registerCommand(m_cmd_cert_file, "<str>", "Path to certificate in Windows cert store. " + "e.g. \"CurrentUser\\MY\\6ac133ac58f0a88b83e9c794eba156a98da39b4c\""); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); parseClientIdAndPort(returnData); returnData.input_cert = getCommandRequired(m_cmd_cert_file); return returnData; } public SampleCommandLineData parseSampleInputX509Connect(String [] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); addCommonProxyCommands(); addCommonX509Commands(); addClientIdAndPort(); registerCommand(m_cmd_signing_region, "<str>", "AWS IoT service region."); sendArguments(args); /** * Gather the input from the command line */ SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); parseCommonProxyCommands(returnData); parseCommonX509Commands(returnData); returnData.input_signingRegion = getCommandRequired(m_cmd_signing_region, m_cmd_region); returnData.input_clientId = getCommandOrDefault(m_cmd_client_id, "test-" + UUID.randomUUID().toString()); returnData.input_port = Integer.parseInt(getCommandOrDefault(m_cmd_port, "443")); return returnData; } public SampleCommandLineData parseSampleInputPkcs12Connect(String[] args) { addCommonLoggingCommands(); addCommonMQTTCommands(); addClientIdAndPort(); registerCommand(m_cmd_pkcs12_file, "<path>", "Path to your client PKCS12 certificate."); registerCommand(m_cmd_pkcs12_password, "<path>", "Path to your client certificate in PEM format."); sendArguments(args); SampleCommandLineData returnData = new SampleCommandLineData(); parseCommonLoggingCommands(returnData); parseCommonMQTTCommands(returnData); parseClientIdAndPort(returnData); returnData.input_pkcs12File = getCommandRequired(m_cmd_pkcs12_file); returnData.input_pkcs12Password = getCommandRequired(m_cmd_pkcs12_password); return returnData; } /** * Based on the sample string: sets up the arguments, parses the arguments, and returns the command line data all in one go */ public static SampleCommandLineData getInputForIoTSample(String sampleName, String[] args) { CommandLineUtils cmdUtils = new CommandLineUtils(); cmdUtils.registerProgramName(sampleName); cmdUtils.determineIfCI(); if (sampleName.equals("BasicConnect")) { return cmdUtils.parseSampleInputBasicConnect(args); } else if (sampleName.equals("PubSub")) { return cmdUtils.parseSampleInputPubSub(args); } else if (sampleName.equals("CognitoConnect")) { return cmdUtils.parseSampleInputCognitoConnect(args); } else if (sampleName.equals("CustomAuthorizerConnect")) { return cmdUtils.parseSampleInputCustomAuthorizerConnect(args); } else if (sampleName.equals("CustomKeyOpsConnect")) { return cmdUtils.parseSampleInputCustomKeyOpsConnect(args); } else if (sampleName.equals("FleetProvisioningSample")) { return cmdUtils.parseSampleInputFleetProvisioning(args); } else if (sampleName.equals("BasicDiscovery")) { return cmdUtils.parseSampleInputGreengrassDiscovery(args); } else if (sampleName.equals("JavaKeystoreConnect")) { return cmdUtils.parseSampleInputKeystoreConnect(args); } else if (sampleName.equals("Jobs")) { return cmdUtils.parseSampleInputJobs(args); } else if (sampleName.equals("Mqtt5PubSub")) { return cmdUtils.parseSampleInputMqtt5PubSub(args); } else if (sampleName.equals("Mqtt5SharedSubscription")) { return cmdUtils.parseSampleInputMqtt5SharedSubscription(args); } else if (sampleName.equals("Pkcs11Connect")) { return cmdUtils.parseSampleInputPkcs11Connect(args); } else if (sampleName.equals("Shadow")) { return cmdUtils.parseSampleInputShadow(args); } else if (sampleName.equals("WebsocketConnect")) { return cmdUtils.parseSampleInputWebsocketConnect(args); } else if (sampleName.equals("WindowsCertConnect")) { return cmdUtils.parseSampleInputWindowsCertConnect(args); } else if (sampleName.equals("x509CredentialsProviderConnect")) { return cmdUtils.parseSampleInputX509Connect(args); } else if (sampleName.equals("Pkcs12Connect")) { return cmdUtils.parseSampleInputPkcs12Connect(args); } else { throw new RuntimeException("Unknown sample name!"); } } /** * Constants for commonly used/needed commands */ private static final String m_cmd_log_destination = "log_destination"; private static final String m_cmd_log_file_name = "log_file_name"; private static final String m_cmd_verbosity = "verbosity"; private static final String m_cmd_endpoint = "endpoint"; private static final String m_cmd_ca_file = "ca_file"; private static final String m_cmd_cert_file = "cert"; private static final String m_cmd_key_file = "key"; private static final String m_cmd_client_id = "client_id"; private static final String m_cmd_port = "port"; private static final String m_cmd_proxy_host = "proxy_host"; private static final String m_cmd_proxy_port = "proxy_port"; private static final String m_cmd_signing_region = "signing_region"; private static final String m_cmd_x509_endpoint = "x509_endpoint"; private static final String m_cmd_x509_role = "x509_role_alias"; private static final String m_cmd_x509_thing_name = "x509_thing_name"; private static final String m_cmd_x509_cert_file = "x509_cert"; private static final String m_cmd_x509_key_file = "x509_key"; private static final String m_cmd_x509_ca_file = "x509_ca_file"; private static final String m_cmd_pkcs11_lib = "pkcs11_lib"; private static final String m_cmd_pkcs11_cert = "cert"; private static final String m_cmd_pkcs11_pin = "pin"; private static final String m_cmd_pkcs11_token = "token_label"; private static final String m_cmd_pkcs11_slot = "slot_id"; private static final String m_cmd_pkcs11_key = "key_label"; private static final String m_cmd_message = "message"; private static final String m_cmd_topic = "topic"; private static final String m_cmd_help = "help"; private static final String m_cmd_custom_auth_username = "custom_auth_username"; private static final String m_cmd_custom_auth_authorizer_name = "custom_auth_authorizer_name"; private static final String m_cmd_custom_auth_authorizer_signature = "custom_auth_authorizer_signature"; private static final String m_cmd_custom_auth_password = "custom_auth_password"; private static final String m_cmd_custom_auth_token_key_name = "custom_auth_token_key_name"; private static final String m_cmd_custom_auth_token_value = "custom_auth_token_value"; private static final String m_cmd_javakeystore_path = "keystore"; private static final String m_cmd_javakeystore_password = "keystore_password"; private static final String m_cmd_javakeystore_format = "keystore_format"; private static final String m_cmd_javakeystore_certificate = "certificate_alias"; private static final String m_cmd_javakeystore_key_password = "certificate_password"; private static final String m_cmd_cognito_identity = "cognito_identity"; private static final String m_cmd_count = "count"; private static final String m_cmd_fleet_template_name = "template_name"; private static final String m_cmd_fleet_template_parameters = "template_parameters"; private static final String m_cmd_fleet_template_csr = "csr"; private static final String m_cmd_thing_name = "thing_name"; private static final String m_cmd_mode = "mode"; private static final String m_cmd_group_identifier = "group_identifier"; private static final String m_cmd_username = "username"; private static final String m_cmd_password = "password"; private static final String m_cmd_protocol = "protocol"; private static final String m_cmd_auth_params = "auth_params"; private static final String m_cmd_pkcs12_file = "pkcs12_file"; private static final String m_cmd_pkcs12_password = "pkcs12_password"; private static final String m_cmd_region = "region"; private static final String m_cmd_print_discover_resp_only = "print_discover_resp_only"; } class CommandLineOption { public String commandName; public String exampleInput; public String helpOutput; CommandLineOption(String name, String example, String help) { commandName = name; exampleInput = example; helpOutput = help; } }
5,180
0
Create_ds/aws-iot-device-sdk-java-v2/samples/BasicPubSub/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/BasicPubSub/src/main/java/pubsub/PubSub.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package pubsub; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.mqtt.MqttMessage; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import java.nio.charset.StandardCharsets; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import utils.commandlineutils.CommandLineUtils; public class PubSub { // When run normally, we want to exit nicely even if something goes wrong // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("BasicPubSub execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("PubSub", args); MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; try { /** * Create the MQTT connection from the builder */ AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(cmdData.input_cert, cmdData.input_key); if (cmdData.input_ca != "") { builder.withCertificateAuthorityFromPath(null, cmdData.input_ca); } builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withPort((short)cmdData.input_port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); if (cmdData.input_proxyHost != "" && cmdData.input_proxyPort > 0) { HttpProxyOptions proxyOptions = new HttpProxyOptions(); proxyOptions.setHost(cmdData.input_proxyHost); proxyOptions.setPort(cmdData.input_proxyPort); builder.withHttpProxyOptions(proxyOptions); } MqttClientConnection connection = builder.build(); builder.close(); // Connect the MQTT client CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!"); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } // Subscribe to the topic CountDownLatch countDownLatch = new CountDownLatch(cmdData.input_count); CompletableFuture<Integer> subscribed = connection.subscribe(cmdData.input_topic, QualityOfService.AT_LEAST_ONCE, (message) -> { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); System.out.println("MESSAGE: " + payload); countDownLatch.countDown(); }); subscribed.get(); // Publish to the topic int count = 0; while (count++ < cmdData.input_count) { CompletableFuture<Integer> published = connection.publish(new MqttMessage(cmdData.input_topic, cmdData.input_message.getBytes(), QualityOfService.AT_LEAST_ONCE, false)); published.get(); Thread.sleep(1000); } countDownLatch.await(); // Disconnect CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); // Close the connection now that we are completely done with it. connection.close(); } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { onApplicationFailure(ex); } CrtResource.waitForNoResources(); System.out.println("Complete!"); } }
5,181
0
Create_ds/aws-iot-device-sdk-java-v2/samples/CognitoConnect/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/CognitoConnect/src/main/java/cognitoconnect/CognitoConnect.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package cognitoconnect; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.crt.auth.credentials.CognitoCredentialsProvider; import software.amazon.awssdk.crt.io.ClientBootstrap; import software.amazon.awssdk.crt.io.TlsContextOptions; import software.amazon.awssdk.crt.io.ClientTlsContext; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import utils.commandlineutils.CommandLineUtils; public class CognitoConnect { // When run normally, we want to exit nicely even if something goes wrong // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("CognitoConnect execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("CognitoConnect", args); MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; try { /** * Creates a connection using Cognito credentials. * * Note: This sample and code assumes that you are using a Cognito identity * in the same region as you pass to "--signing_region". * If not, you may need to adjust the Cognito endpoint in the cmdUtils. * See https://docs.aws.amazon.com/general/latest/gr/cognito_identity.html * for all Cognito endpoints. */ // ================================= AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(null, null); builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); builder.withWebsockets(true); builder.withWebsocketSigningRegion(cmdData.input_signingRegion); CognitoCredentialsProvider.CognitoCredentialsProviderBuilder cognitoBuilder = new CognitoCredentialsProvider.CognitoCredentialsProviderBuilder(); String cognitoEndpoint = "cognito-identity." + cmdData.input_signingRegion + ".amazonaws.com"; cognitoBuilder.withEndpoint(cognitoEndpoint).withIdentity(cmdData.input_cognitoIdentity); cognitoBuilder.withClientBootstrap(ClientBootstrap.getOrCreateStaticDefault()); TlsContextOptions cognitoTlsContextOptions = TlsContextOptions.createDefaultClient(); ClientTlsContext cognitoTlsContext = new ClientTlsContext(cognitoTlsContextOptions); cognitoTlsContextOptions.close(); cognitoBuilder.withTlsContext(cognitoTlsContext); CognitoCredentialsProvider cognitoCredentials = cognitoBuilder.build(); builder.withWebsocketCredentialsProvider(cognitoCredentials); MqttClientConnection connection = builder.build(); builder.close(); cognitoCredentials.close(); cognitoTlsContext.close(); if (connection == null) { onApplicationFailure(new RuntimeException("MQTT connection creation failed!")); } // ================================= /** * Connect and disconnect */ CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!"); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } System.out.println("Disconnecting..."); CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); System.out.println("Disconnected."); /** * Close the connection now that it is complete */ connection.close(); } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { onApplicationFailure(ex); } CrtResource.waitForNoResources(); System.out.println("Complete!"); } }
5,182
0
Create_ds/aws-iot-device-sdk-java-v2/samples/JavaKeystoreConnect/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/JavaKeystoreConnect/src/main/java/javakeystoreconnect/JavaKeystoreConnect.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package javakeystoreconnect; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import java.util.concurrent.ExecutionException; import java.util.concurrent.CompletableFuture; import utils.commandlineutils.CommandLineUtils; public class JavaKeystoreConnect { // When run normally, we want to exit nicely even if something goes wrong // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("JavaKeystoreConnect execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("JavaKeystoreConnect", args); MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; try { /** * Create the MQTT connection from the builder */ java.security.KeyStore keyStore; try { keyStore = java.security.KeyStore.getInstance(cmdData.input_keystoreFormat); } catch (java.security.KeyStoreException ex) { throw new CrtRuntimeException("Could not get instance of Java keystore with format " + cmdData.input_keystoreFormat); } try (java.io.FileInputStream fileInputStream = new java.io.FileInputStream(cmdData.input_keystore)) { keyStore.load(fileInputStream, cmdData.input_keystorePassword.toCharArray()); } catch (java.io.FileNotFoundException ex) { throw new CrtRuntimeException("Could not open Java keystore file"); } catch (java.io.IOException | java.security.NoSuchAlgorithmException | java.security.cert.CertificateException ex) { throw new CrtRuntimeException("Could not load Java keystore"); } AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newJavaKeystoreBuilder( keyStore, cmdData.input_certificateAlias, cmdData.input_certificatePassword); if (cmdData.input_ca != "") { builder.withCertificateAuthorityFromPath(null, cmdData.input_ca); } builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withPort((short)cmdData.input_port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); if (cmdData.input_proxyHost != "" && cmdData.input_proxyPort > 0) { HttpProxyOptions proxyOptions = new HttpProxyOptions(); proxyOptions.setHost(cmdData.input_proxyHost); proxyOptions.setPort(cmdData.input_proxyPort); builder.withHttpProxyOptions(proxyOptions); } MqttClientConnection connection = builder.build(); builder.close(); /** * Verify the connection was created */ if (connection == null) { onApplicationFailure(new RuntimeException("MQTT connection creation failed!")); } /** * Connect and disconnect */ CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!"); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } System.out.println("Disconnecting..."); CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); System.out.println("Disconnected."); /** * Close the connection now that it is complete */ connection.close(); } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { onApplicationFailure(ex); } CrtResource.waitForNoResources(); System.out.println("Complete!"); } }
5,183
0
Create_ds/aws-iot-device-sdk-java-v2/samples/WebsocketConnect/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/WebsocketConnect/src/main/java/websocketconnect/WebsocketConnect.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package websocketconnect; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import java.util.concurrent.ExecutionException; import java.util.concurrent.CompletableFuture; import utils.commandlineutils.CommandLineUtils; public class WebsocketConnect { // When run normally, we want to exit nicely even if something goes wrong // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("WebsocketConnect execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("WebsocketConnect", args); MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; try { /** * Create the MQTT connection from the builder */ AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(null, null); if (cmdData.input_ca != "") { builder.withCertificateAuthorityFromPath(null, cmdData.input_ca); } builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withPort((short)cmdData.input_port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); if (cmdData.input_proxyHost != "" && cmdData.input_proxyPort > 0) { HttpProxyOptions proxyOptions = new HttpProxyOptions(); proxyOptions.setHost(cmdData.input_proxyHost); proxyOptions.setPort(cmdData.input_proxyPort); builder.withHttpProxyOptions(proxyOptions); } builder.withWebsockets(true); builder.withWebsocketSigningRegion(cmdData.input_signingRegion); MqttClientConnection connection = builder.build(); builder.close(); /** * Verify the connection was created */ if (connection == null) { onApplicationFailure(new RuntimeException("MQTT connection creation failed!")); } /** * Connect and disconnect */ CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!"); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } System.out.println("Disconnecting..."); CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); System.out.println("Disconnected."); // Close the connection now that we are completely done with it. connection.close(); } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { onApplicationFailure(ex); } CrtResource.waitForNoResources(); System.out.println("Complete!"); } }
5,184
0
Create_ds/aws-iot-device-sdk-java-v2/samples/WindowsCertConnect/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/WindowsCertConnect/src/main/java/windowscertconnect/WindowsCertConnect.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package windowscertconnect; import software.amazon.awssdk.crt.*; import software.amazon.awssdk.crt.io.*; import software.amazon.awssdk.crt.mqtt.*; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import utils.commandlineutils.CommandLineUtils; public class WindowsCertConnect { // When run normally, we want to exit nicely even if something goes wrong // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the * exec:java task When called otherwise, print what went wrong (if anything) and * just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("WindowsCertConnect", args); MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; try { AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsWindowsCertStorePathBuilder(cmdData.input_cert); if (cmdData.input_ca != "") { builder.withCertificateAuthorityFromPath(null, cmdData.input_ca); } builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withPort((short)cmdData.input_port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); MqttClientConnection connection = builder.build(); builder.close(); /** * Verify the connection was created */ if (connection == null) { onApplicationFailure(new RuntimeException("MQTT connection creation failed!")); } /** * Connect and disconnect */ CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!"); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } System.out.println("Disconnecting..."); CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); System.out.println("Disconnected."); /** * Close the connection now that it is complete */ connection.close(); } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { onApplicationFailure(ex); } CrtResource.waitForNoResources(); System.out.println("Complete!"); } }
5,185
0
Create_ds/aws-iot-device-sdk-java-v2/samples/Pkcs11Connect/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/Pkcs11Connect/src/main/java/pkcs11connect/Pkcs11Connect.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package pkcs11connect; import software.amazon.awssdk.crt.*; import software.amazon.awssdk.crt.io.*; import software.amazon.awssdk.crt.mqtt.*; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import utils.commandlineutils.CommandLineUtils; public class Pkcs11Connect { // When run normally, we want to exit nicely even if something goes wrong // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the * exec:java task When called otherwise, print what went wrong (if anything) and * just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("Pkcs11Connect execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("Pkcs11Connect", args); MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; // Load PKCS#11 library try (Pkcs11Lib pkcs11Lib = new Pkcs11Lib(cmdData.input_pkcs11LibPath); TlsContextPkcs11Options pkcs11Options = new TlsContextPkcs11Options(pkcs11Lib)) { pkcs11Options.withCertificateFilePath(cmdData.input_cert); pkcs11Options.withUserPin(cmdData.input_pkcs11UserPin); // Pass arguments to help find the correct PKCS#11 token, // and the private key on that token. You don't need to pass // any of these arguments if your PKCS#11 device only has one // token, or the token only has one private key. But if there // are multiple tokens, or multiple keys to choose from, you // must narrow down which one should be used. if (cmdData.input_pkcs11TokenLabel != null && cmdData.input_pkcs11TokenLabel != "") { pkcs11Options.withTokenLabel(cmdData.input_pkcs11TokenLabel); } if (cmdData.input_pkcs11SlotId != null) { pkcs11Options.withSlotId(cmdData.input_pkcs11SlotId); } if (cmdData.input_pkcs11KeyLabel != null && cmdData.input_pkcs11KeyLabel != "") { pkcs11Options.withPrivateKeyObjectLabel(cmdData.input_pkcs11KeyLabel); } try (AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder .newMtlsPkcs11Builder(pkcs11Options)) { if (cmdData.input_ca != null && cmdData.input_ca != "") { builder.withCertificateAuthorityFromPath(null, cmdData.input_ca); } builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withPort((short) cmdData.input_port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); try (MqttClientConnection connection = builder.build()) { CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!"); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } System.out.println("Disconnecting..."); CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); System.out.println("Disconnected."); // Close the connection now that we are completely done with it. connection.close(); } } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { onApplicationFailure(ex); } } CrtResource.waitForNoResources(); System.out.println("Complete!"); } }
5,186
0
Create_ds/aws-iot-device-sdk-java-v2/samples/Jobs/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/Jobs/src/main/java/jobs/JobsSample.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package jobs; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import software.amazon.awssdk.iot.iotjobs.IotJobsClient; import software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionRequest; import software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionResponse; import software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsRequest; import software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsResponse; import software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionSummary; import software.amazon.awssdk.iot.iotjobs.model.JobStatus; import software.amazon.awssdk.iot.iotjobs.model.RejectedError; import software.amazon.awssdk.iot.iotjobs.model.StartNextJobExecutionResponse; import software.amazon.awssdk.iot.iotjobs.model.StartNextPendingJobExecutionRequest; import software.amazon.awssdk.iot.iotjobs.model.StartNextPendingJobExecutionSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionRequest; import software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionSubscriptionRequest; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import utils.commandlineutils.CommandLineUtils; public class JobsSample { // When run normally, we want to check for jobs and process them // When run from CI, we want to just check for jobs static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CompletableFuture<Void> gotResponse; static List<String> availableJobs = new LinkedList<>(); static String currentJobId; static long currentExecutionNumber = 0; static int currentVersionNumber = 0; static CommandLineUtils cmdUtils; static void onRejectedError(RejectedError error) { System.out.println("Request rejected: " + error.code.toString() + ": " + error.message); System.exit(1); } static void onGetPendingJobExecutionsAccepted(GetPendingJobExecutionsResponse response) { System.out.println("Pending Jobs: " + (response.queuedJobs.size() + response.inProgressJobs.size() == 0 ? "none" : "")); for (JobExecutionSummary job : response.inProgressJobs) { availableJobs.add(job.jobId); System.out.println(" In Progress: " + job.jobId + " @ " + job.lastUpdatedAt.toString()); } for (JobExecutionSummary job : response.queuedJobs) { availableJobs.add(job.jobId); System.out.println(" " + job.jobId + " @ " + job.lastUpdatedAt.toString()); } gotResponse.complete(null); } static void onDescribeJobExecutionAccepted(DescribeJobExecutionResponse response) { System.out.println("Describe Job: " + response.execution.jobId + " version: " + response.execution.versionNumber); if (response.execution.jobDocument != null) { response.execution.jobDocument.forEach((key, value) -> { System.out.println(" " + key + ": " + value); }); } gotResponse.complete(null); } static void onStartNextPendingJobExecutionAccepted(StartNextJobExecutionResponse response) { System.out.println("Start Job: " + response.execution.jobId); currentJobId = response.execution.jobId; currentExecutionNumber = response.execution.executionNumber; currentVersionNumber = response.execution.versionNumber; gotResponse.complete(null); } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("Jobs", args); MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { if (errorCode != 0) { System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode)); } } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session")); } }; try { /** * Create the MQTT connection from the builder */ AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(cmdData.input_cert, cmdData.input_key); if (cmdData.input_ca != "") { builder.withCertificateAuthorityFromPath(null, cmdData.input_ca); } builder.withConnectionEventCallbacks(callbacks) .withClientId(cmdData.input_clientId) .withEndpoint(cmdData.input_endpoint) .withPort((short)cmdData.input_port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); MqttClientConnection connection = builder.build(); builder.close(); IotJobsClient jobs = new IotJobsClient(connection); CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!"); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } { gotResponse = new CompletableFuture<>(); GetPendingJobExecutionsSubscriptionRequest subscriptionRequest = new GetPendingJobExecutionsSubscriptionRequest(); subscriptionRequest.thingName = cmdData.input_thingName; CompletableFuture<Integer> subscribed = jobs.SubscribeToGetPendingJobExecutionsAccepted( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onGetPendingJobExecutionsAccepted); try { subscribed.get(); System.out.println("Subscribed to GetPendingJobExecutionsAccepted"); } catch (Exception ex) { throw new RuntimeException("Failed to subscribe to GetPendingJobExecutions", ex); } subscribed = jobs.SubscribeToGetPendingJobExecutionsRejected( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onRejectedError); subscribed.get(); System.out.println("Subscribed to GetPendingJobExecutionsRejected"); GetPendingJobExecutionsRequest publishRequest = new GetPendingJobExecutionsRequest(); publishRequest.thingName = cmdData.input_thingName; CompletableFuture<Integer> published = jobs.PublishGetPendingJobExecutions( publishRequest, QualityOfService.AT_LEAST_ONCE); try { published.get(); gotResponse.get(); } catch (Exception ex) { throw new RuntimeException("Exception occurred during publish", ex); } } if (availableJobs.isEmpty()) { System.out.println("No jobs queued, no further work to do"); // If sample is running in CI, there should be at least one job if (isCI == true) { throw new RuntimeException("No jobs queued in CI! At least one job should be queued!"); } } for (String jobId : availableJobs) { gotResponse = new CompletableFuture<>(); DescribeJobExecutionSubscriptionRequest subscriptionRequest = new DescribeJobExecutionSubscriptionRequest(); subscriptionRequest.thingName = cmdData.input_thingName; subscriptionRequest.jobId = jobId; jobs.SubscribeToDescribeJobExecutionAccepted( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onDescribeJobExecutionAccepted); jobs.SubscribeToDescribeJobExecutionRejected( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onRejectedError); DescribeJobExecutionRequest publishRequest = new DescribeJobExecutionRequest(); publishRequest.thingName = cmdData.input_thingName; publishRequest.jobId = jobId; publishRequest.includeJobDocument = true; publishRequest.executionNumber = 1L; jobs.PublishDescribeJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE); gotResponse.get(); } // If sample is not running in CI, then process the available jobs. if (isCI == false) { for (int jobIdx = 0; jobIdx < availableJobs.size(); ++jobIdx) { { gotResponse = new CompletableFuture<>(); // Start the next pending job StartNextPendingJobExecutionSubscriptionRequest subscriptionRequest = new StartNextPendingJobExecutionSubscriptionRequest(); subscriptionRequest.thingName = cmdData.input_thingName; jobs.SubscribeToStartNextPendingJobExecutionAccepted( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onStartNextPendingJobExecutionAccepted); jobs.SubscribeToStartNextPendingJobExecutionRejected( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onRejectedError); StartNextPendingJobExecutionRequest publishRequest = new StartNextPendingJobExecutionRequest(); publishRequest.thingName = cmdData.input_thingName; publishRequest.stepTimeoutInMinutes = 15L; jobs.PublishStartNextPendingJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE); gotResponse.get(); } { // Update the service to let it know we're executing gotResponse = new CompletableFuture<>(); UpdateJobExecutionSubscriptionRequest subscriptionRequest = new UpdateJobExecutionSubscriptionRequest(); subscriptionRequest.thingName = cmdData.input_thingName; subscriptionRequest.jobId = currentJobId; jobs.SubscribeToUpdateJobExecutionAccepted( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, (response) -> { System.out.println("Marked job " + currentJobId + " IN_PROGRESS"); gotResponse.complete(null); }); jobs.SubscribeToUpdateJobExecutionRejected( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onRejectedError); UpdateJobExecutionRequest publishRequest = new UpdateJobExecutionRequest(); publishRequest.thingName = cmdData.input_thingName; publishRequest.jobId = currentJobId; publishRequest.executionNumber = currentExecutionNumber; publishRequest.status = JobStatus.IN_PROGRESS; publishRequest.expectedVersion = currentVersionNumber++; jobs.PublishUpdateJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE); gotResponse.get(); } // Fake doing something Thread.sleep(1000); { // Update the service to let it know we're done gotResponse = new CompletableFuture<>(); UpdateJobExecutionSubscriptionRequest subscriptionRequest = new UpdateJobExecutionSubscriptionRequest(); subscriptionRequest.thingName = cmdData.input_thingName; subscriptionRequest.jobId = currentJobId; jobs.SubscribeToUpdateJobExecutionAccepted( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, (response) -> { System.out.println("Marked job " + currentJobId + " SUCCEEDED"); gotResponse.complete(null); }); jobs.SubscribeToUpdateJobExecutionRejected( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onRejectedError); UpdateJobExecutionRequest publishRequest = new UpdateJobExecutionRequest(); publishRequest.thingName = cmdData.input_thingName; publishRequest.jobId = currentJobId; publishRequest.executionNumber = currentExecutionNumber; publishRequest.status = JobStatus.SUCCEEDED; publishRequest.expectedVersion = currentVersionNumber++; jobs.PublishUpdateJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE); gotResponse.get(); } } } CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); // Close the connection now that we are completely done with it. connection.close(); } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { System.out.println("Exception encountered: " + ex.toString()); } CrtResource.waitForNoResources(); System.out.println("Complete!"); } }
5,187
0
Create_ds/aws-iot-device-sdk-java-v2/samples/Jobs/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/Jobs/src/main/java/jobs/Mqtt5JobsSample.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package jobs; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt5.packets.*; import software.amazon.awssdk.crt.mqtt5.*; import software.amazon.awssdk.crt.mqtt5.Mqtt5ClientOptions; import software.amazon.awssdk.crt.mqtt5.Mqtt5Client; import software.amazon.awssdk.iot.AwsIotMqtt5ClientBuilder; import software.amazon.awssdk.iot.iotjobs.IotJobsClient; import software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionRequest; import software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionResponse; import software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsRequest; import software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsResponse; import software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionSummary; import software.amazon.awssdk.iot.iotjobs.model.JobStatus; import software.amazon.awssdk.iot.iotjobs.model.RejectedError; import software.amazon.awssdk.iot.iotjobs.model.StartNextJobExecutionResponse; import software.amazon.awssdk.iot.iotjobs.model.StartNextPendingJobExecutionRequest; import software.amazon.awssdk.iot.iotjobs.model.StartNextPendingJobExecutionSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionRequest; import software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionSubscriptionRequest; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import utils.commandlineutils.CommandLineUtils; public class Mqtt5JobsSample { // When run normally, we want to check for jobs and process them // When run from CI, we want to just check for jobs static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = true; static CompletableFuture<Void> gotResponse; static List<String> availableJobs = new LinkedList<>(); static String currentJobId; static long currentExecutionNumber = 0; static int currentVersionNumber = 0; static CommandLineUtils cmdUtils; static final class SampleLifecycleEvents implements Mqtt5ClientOptions.LifecycleEvents { CompletableFuture<Void> connectedFuture = new CompletableFuture<>(); CompletableFuture<Void> stoppedFuture = new CompletableFuture<>(); @Override public void onAttemptingConnect(Mqtt5Client client, OnAttemptingConnectReturn onAttemptingConnectReturn) { System.out.println("Mqtt5 Client: Attempting connection..."); } @Override public void onConnectionSuccess(Mqtt5Client client, OnConnectionSuccessReturn onConnectionSuccessReturn) { System.out.println("Mqtt5 Client: Connection success, client ID: " + onConnectionSuccessReturn.getNegotiatedSettings().getAssignedClientID()); System.out.println("Connected to " + (!onConnectionSuccessReturn.getConnAckPacket().getSessionPresent() ? "new" : "existing") + " session!"); connectedFuture.complete(null); } @Override public void onConnectionFailure(Mqtt5Client client, OnConnectionFailureReturn onConnectionFailureReturn) { String errorString = CRT.awsErrorString(onConnectionFailureReturn.getErrorCode()); System.out.println("Mqtt5 Client: Connection failed with error: " + errorString); connectedFuture.completeExceptionally(new Exception("Could not connect: " + errorString)); } @Override public void onDisconnection(Mqtt5Client client, OnDisconnectionReturn onDisconnectionReturn) { System.out.println("Mqtt5 Client: Disconnected"); DisconnectPacket disconnectPacket = onDisconnectionReturn.getDisconnectPacket(); if (disconnectPacket != null) { System.out.println("\tDisconnection packet code: " + disconnectPacket.getReasonCode()); System.out.println("\tDisconnection packet reason: " + disconnectPacket.getReasonString()); } } @Override public void onStopped(Mqtt5Client client, OnStoppedReturn onStoppedReturn) { System.out.println("Mqtt5 Client: Stopped"); stoppedFuture.complete(null); } } static void onRejectedError(RejectedError error) { System.out.println("Request rejected: " + error.code.toString() + ": " + error.message); System.exit(1); } static void onGetPendingJobExecutionsAccepted(GetPendingJobExecutionsResponse response) { System.out.println( "Pending Jobs: " + (response.queuedJobs.size() + response.inProgressJobs.size() == 0 ? "none" : "")); for (JobExecutionSummary job : response.inProgressJobs) { availableJobs.add(job.jobId); System.out.println(" In Progress: " + job.jobId + " @ " + job.lastUpdatedAt.toString()); } for (JobExecutionSummary job : response.queuedJobs) { availableJobs.add(job.jobId); System.out.println(" " + job.jobId + " @ " + job.lastUpdatedAt.toString()); } gotResponse.complete(null); } static void onDescribeJobExecutionAccepted(DescribeJobExecutionResponse response) { System.out .println("Describe Job: " + response.execution.jobId + " version: " + response.execution.versionNumber); if (response.execution.jobDocument != null) { response.execution.jobDocument.forEach((key, value) -> { System.out.println(" " + key + ": " + value); }); } gotResponse.complete(null); } static void onStartNextPendingJobExecutionAccepted(StartNextJobExecutionResponse response) { System.out.println("Start Job: " + response.execution.jobId); currentJobId = response.execution.jobId; currentExecutionNumber = response.execution.executionNumber; currentVersionNumber = response.execution.versionNumber; gotResponse.complete(null); } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single * struct for * use in this sample. This handles all of the command line parsing, validating, * etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("Jobs", args); try { /** * Create the MQTT5 client from the builder */ SampleLifecycleEvents lifecycleEvents = new SampleLifecycleEvents(); AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newDirectMqttBuilderWithMtlsFromPath( cmdData.input_endpoint, cmdData.input_cert, cmdData.input_key); ConnectPacket.ConnectPacketBuilder connectProperties = new ConnectPacket.ConnectPacketBuilder(); connectProperties.withClientId(cmdData.input_clientId); builder.withConnectProperties(connectProperties); builder.withLifeCycleEvents(lifecycleEvents); Mqtt5Client client = builder.build(); builder.close(); MqttClientConnection connection = new MqttClientConnection(client, null); // Create the job client, IotJobsClient throws MqttException IotJobsClient jobs = new IotJobsClient(connection); // Connect client.start(); try { lifecycleEvents.connectedFuture.get(60, TimeUnit.SECONDS); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } { gotResponse = new CompletableFuture<>(); GetPendingJobExecutionsSubscriptionRequest subscriptionRequest = new GetPendingJobExecutionsSubscriptionRequest(); subscriptionRequest.thingName = cmdData.input_thingName; CompletableFuture<Integer> subscribed = jobs.SubscribeToGetPendingJobExecutionsAccepted( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, Mqtt5JobsSample::onGetPendingJobExecutionsAccepted); try { subscribed.get(); System.out.println("Subscribed to GetPendingJobExecutionsAccepted"); } catch (Exception ex) { throw new RuntimeException("Failed to subscribe to GetPendingJobExecutions", ex); } subscribed = jobs.SubscribeToGetPendingJobExecutionsRejected( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, Mqtt5JobsSample::onRejectedError); subscribed.get(); System.out.println("Subscribed to GetPendingJobExecutionsRejected"); GetPendingJobExecutionsRequest publishRequest = new GetPendingJobExecutionsRequest(); publishRequest.thingName = cmdData.input_thingName; CompletableFuture<Integer> published = jobs.PublishGetPendingJobExecutions( publishRequest, QualityOfService.AT_LEAST_ONCE); try { published.get(); gotResponse.get(); } catch (Exception ex) { throw new RuntimeException("Exception occurred during publish", ex); } } if (availableJobs.isEmpty()) { System.out.println("No jobs queued, no further work to do"); // If sample is running in CI, there should be at least one job if (isCI == true) { throw new RuntimeException("No jobs queued in CI! At least one job should be queued!"); } } for (String jobId : availableJobs) { gotResponse = new CompletableFuture<>(); DescribeJobExecutionSubscriptionRequest subscriptionRequest = new DescribeJobExecutionSubscriptionRequest(); subscriptionRequest.thingName = cmdData.input_thingName; subscriptionRequest.jobId = jobId; jobs.SubscribeToDescribeJobExecutionAccepted( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, Mqtt5JobsSample::onDescribeJobExecutionAccepted); jobs.SubscribeToDescribeJobExecutionRejected( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, Mqtt5JobsSample::onRejectedError); DescribeJobExecutionRequest publishRequest = new DescribeJobExecutionRequest(); publishRequest.thingName = cmdData.input_thingName; publishRequest.jobId = jobId; publishRequest.includeJobDocument = true; publishRequest.executionNumber = 1L; jobs.PublishDescribeJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE); gotResponse.get(); } // If sample is not running in CI, then process the available jobs. if (isCI == false) { for (int jobIdx = 0; jobIdx < availableJobs.size(); ++jobIdx) { { gotResponse = new CompletableFuture<>(); // Start the next pending job StartNextPendingJobExecutionSubscriptionRequest subscriptionRequest = new StartNextPendingJobExecutionSubscriptionRequest(); subscriptionRequest.thingName = cmdData.input_thingName; jobs.SubscribeToStartNextPendingJobExecutionAccepted( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, Mqtt5JobsSample::onStartNextPendingJobExecutionAccepted); jobs.SubscribeToStartNextPendingJobExecutionRejected( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, Mqtt5JobsSample::onRejectedError); StartNextPendingJobExecutionRequest publishRequest = new StartNextPendingJobExecutionRequest(); publishRequest.thingName = cmdData.input_thingName; publishRequest.stepTimeoutInMinutes = 15L; jobs.PublishStartNextPendingJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE); gotResponse.get(); } { // Update the service to let it know we're executing gotResponse = new CompletableFuture<>(); UpdateJobExecutionSubscriptionRequest subscriptionRequest = new UpdateJobExecutionSubscriptionRequest(); subscriptionRequest.thingName = cmdData.input_thingName; subscriptionRequest.jobId = currentJobId; jobs.SubscribeToUpdateJobExecutionAccepted( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, (response) -> { System.out.println("Marked job " + currentJobId + " IN_PROGRESS"); gotResponse.complete(null); }); jobs.SubscribeToUpdateJobExecutionRejected( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, Mqtt5JobsSample::onRejectedError); UpdateJobExecutionRequest publishRequest = new UpdateJobExecutionRequest(); publishRequest.thingName = cmdData.input_thingName; publishRequest.jobId = currentJobId; publishRequest.executionNumber = currentExecutionNumber; publishRequest.status = JobStatus.IN_PROGRESS; publishRequest.expectedVersion = currentVersionNumber++; jobs.PublishUpdateJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE); gotResponse.get(); } // Fake doing something Thread.sleep(1000); { // Update the service to let it know we're done gotResponse = new CompletableFuture<>(); UpdateJobExecutionSubscriptionRequest subscriptionRequest = new UpdateJobExecutionSubscriptionRequest(); subscriptionRequest.thingName = cmdData.input_thingName; subscriptionRequest.jobId = currentJobId; jobs.SubscribeToUpdateJobExecutionAccepted( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, (response) -> { System.out.println("Marked job " + currentJobId + " SUCCEEDED"); gotResponse.complete(null); }); jobs.SubscribeToUpdateJobExecutionRejected( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, Mqtt5JobsSample::onRejectedError); UpdateJobExecutionRequest publishRequest = new UpdateJobExecutionRequest(); publishRequest.thingName = cmdData.input_thingName; publishRequest.jobId = currentJobId; publishRequest.executionNumber = currentExecutionNumber; publishRequest.status = JobStatus.SUCCEEDED; publishRequest.expectedVersion = currentVersionNumber++; jobs.PublishUpdateJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE); gotResponse.get(); } } } // Disconnect client.stop(null); try { lifecycleEvents.stoppedFuture.get(60, TimeUnit.SECONDS); } catch (Exception ex) { System.out.println("Exception encountered: " + ex.toString()); System.exit(1); } /* Close the client to free memory */ connection.close(); client.close(); } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { System.out.println("Exception encountered: " + ex.toString()); } CrtResource.waitForNoResources(); System.out.println("Complete!"); } }
5,188
0
Create_ds/aws-iot-device-sdk-java-v2/samples/Greengrass/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/Greengrass/src/main/java/greengrass/BasicDiscovery.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package greengrass; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.crt.io.*; import software.amazon.awssdk.crt.mqtt.*; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import software.amazon.awssdk.iot.discovery.DiscoveryClient; import software.amazon.awssdk.iot.discovery.DiscoveryClientConfig; import software.amazon.awssdk.iot.discovery.model.ConnectivityInfo; import software.amazon.awssdk.iot.discovery.model.DiscoverResponse; import software.amazon.awssdk.iot.discovery.model.GGCore; import software.amazon.awssdk.iot.discovery.model.GGGroup; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static software.amazon.awssdk.iot.discovery.DiscoveryClient.TLS_EXT_ALPN; import utils.commandlineutils.CommandLineUtils; public class BasicDiscovery { // When run normally, we want to exit nicely even if something goes wrong. // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code. static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); // Needed to access command line input data in getClientFromDiscovery static String input_thingName; static String input_certPath; static String input_keyPath; static CommandLineUtils cmdUtils; public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("BasicDiscovery", args); input_thingName = cmdData.input_thingName; input_certPath = cmdData.input_cert; input_keyPath = cmdData.input_key; try(final TlsContextOptions tlsCtxOptions = TlsContextOptions.createWithMtlsFromPath(cmdData.input_cert, cmdData.input_key)) { if(TlsContextOptions.isAlpnSupported()) { tlsCtxOptions.withAlpnList(TLS_EXT_ALPN); } if(cmdData.input_ca != null) { tlsCtxOptions.overrideDefaultTrustStoreFromPath(null, cmdData.input_ca); } HttpProxyOptions proxyOptions = null; if (cmdData.input_proxyHost != null && cmdData.input_proxyPort > 0) { proxyOptions = new HttpProxyOptions(); proxyOptions.setHost(cmdData.input_proxyHost); proxyOptions.setPort(cmdData.input_proxyPort); } try ( final SocketOptions socketOptions = new SocketOptions(); final DiscoveryClientConfig discoveryClientConfig = new DiscoveryClientConfig(tlsCtxOptions, socketOptions, cmdData.input_signingRegion, 1, proxyOptions); final DiscoveryClient discoveryClient = new DiscoveryClient(discoveryClientConfig)) { DiscoverResponse response = discoveryClient.discover(input_thingName).get(60, TimeUnit.SECONDS); if (isCI) { System.out.println("Received a greengrass discovery result! Not showing result in CI for possible data sensitivity."); } else { printGreengrassGroupList(response.getGGGroups(), ""); } if (cmdData.inputPrintDiscoverRespOnly == false) { try (final MqttClientConnection connection = getClientFromDiscovery(discoveryClient)) { if ("subscribe".equals(cmdData.input_mode) || "both".equals(cmdData.input_mode)) { final CompletableFuture<Integer> subFuture = connection.subscribe(cmdData.input_topic, QualityOfService.AT_MOST_ONCE, message -> { System.out.println(String.format("Message received on topic %s: %s", message.getTopic(), new String(message.getPayload(), StandardCharsets.UTF_8))); }); subFuture.get(); } final Scanner scanner = new Scanner(System.in); while (true) { String input = null; if ("publish".equals(cmdData.input_mode) || "both".equals(cmdData.input_mode)) { System.out.println("Enter the message you want to publish to topic " + cmdData.input_topic + " and press Enter. " + "Type 'exit' or 'quit' to exit this program: "); input = scanner.nextLine(); } if ("exit".equals(input) || "quit".equals(input)) { System.out.println("Terminating..."); break; } if ("publish".equals(cmdData.input_mode) || "both".equals(cmdData.input_mode)) { final CompletableFuture<Integer> publishResult = connection.publish(new MqttMessage(cmdData.input_topic, input.getBytes(StandardCharsets.UTF_8), QualityOfService.AT_MOST_ONCE, false)); Integer result = publishResult.get(); } } } } } } catch (CrtRuntimeException | InterruptedException | ExecutionException | TimeoutException ex) { System.out.println("Exception thrown: " + ex.toString()); ex.printStackTrace(); } CrtResource.waitForNoResources(); System.out.println("Complete!"); } private static void printGreengrassGroupList(List<GGGroup> groupList, String prefix) { for (int i = 0; i < groupList.size(); i++) { GGGroup group = groupList.get(i); System.out.println(prefix + "Group ID: " + group.getGGGroupId()); printGreengrassCoreList(group.getCores(), " "); } } private static void printGreengrassCoreList(List<GGCore> coreList, String prefix) { for (int i = 0; i < coreList.size(); i++) { GGCore core = coreList.get(i); System.out.println(prefix + "Thing ARN: " + core.getThingArn()); printGreengrassConnectivityList(core.getConnectivity(), prefix + " "); } } private static void printGreengrassConnectivityList(List<ConnectivityInfo> connectivityList, String prefix) { for (int i = 0; i < connectivityList.size(); i++) { ConnectivityInfo connectivityInfo = connectivityList.get(i); System.out.println(prefix + "Connectivity ID: " + connectivityInfo.getId()); System.out.println(prefix + "Connectivity Host Address: " + connectivityInfo.getHostAddress()); System.out.println(prefix + "Connectivity Port: " + connectivityInfo.getPortNumber()); } } private static MqttClientConnection getClientFromDiscovery(final DiscoveryClient discoveryClient ) throws ExecutionException, InterruptedException { final CompletableFuture<DiscoverResponse> futureResponse = discoveryClient.discover(input_thingName); final DiscoverResponse response = futureResponse.get(); if(response.getGGGroups() != null) { final Optional<GGGroup> groupOpt = response.getGGGroups().stream().findFirst(); if(groupOpt.isPresent()) { final GGGroup group = groupOpt.get(); final GGCore core = group.getCores().stream().findFirst().get(); for (ConnectivityInfo connInfo : core.getConnectivity()) { final String dnsOrIp = connInfo.getHostAddress(); final Integer port = connInfo.getPortNumber(); System.out.println(String.format("Connecting to group ID %s, with thing arn %s, using endpoint %s:%d", group.getGGGroupId(), core.getThingArn(), dnsOrIp, port)); final AwsIotMqttConnectionBuilder connectionBuilder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(input_certPath, input_keyPath) .withClientId(input_thingName) .withPort(port.shortValue()) .withEndpoint(dnsOrIp) .withConnectionEventCallbacks(new MqttClientConnectionEvents() { @Override public void onConnectionInterrupted(int errorCode) { System.out.println("Connection interrupted: " + errorCode); } @Override public void onConnectionResumed(boolean sessionPresent) { System.out.println("Connection resumed!"); } }); if (group.getCAs() != null) { connectionBuilder.withCertificateAuthority(group.getCAs().get(0)); } try (MqttClientConnection connection = connectionBuilder.build()) { if (connection.connect().get()) { System.out.println("Session resumed"); } else { System.out.println("Started a clean session"); } /* This lets the connection escape the try block without getting cleaned up */ connection.addRef(); return connection; } catch (Exception e) { System.out.println(String.format("Connection failed with exception %s", e.toString())); } } throw new RuntimeException("ThingName " + input_thingName + " could not connect to the green grass core using any of the endpoint connectivity options"); } } throw new RuntimeException("ThingName " + input_thingName + " does not have a Greengrass group/core configuration"); } }
5,189
0
Create_ds/aws-iot-device-sdk-java-v2/samples/Mqtt5/SharedSubscription/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/Mqtt5/SharedSubscription/src/main/java/sharedsubscription/SharedSubscription.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package mqtt5.sharedsubscription; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt5.*; import software.amazon.awssdk.crt.mqtt5.Mqtt5ClientOptions.LifecycleEvents; import software.amazon.awssdk.crt.mqtt5.packets.*; import software.amazon.awssdk.iot.AwsIotMqtt5ClientBuilder; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import utils.commandlineutils.CommandLineUtils; public class SharedSubscription { /** * When run normally, we want to exit nicely even if something goes wrong * When run from CI, we want to let an exception escape which in turn causes the * exec:java task to return a non-zero exit code */ static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); /* Used for command line processing */ static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("Mqtt5 SharedSubscription: execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } /** * The interface that contains the functions invoked when the MQTT5 has a life-cycle event * (connect, disconnect, etc) that can be reacted to. */ static final class SampleLifecycleEvents implements Mqtt5ClientOptions.LifecycleEvents { SampleMqtt5Client sampleClient; CompletableFuture<Void> connectedFuture = new CompletableFuture<>(); CompletableFuture<Void> stoppedFuture = new CompletableFuture<>(); SampleLifecycleEvents(SampleMqtt5Client client) { sampleClient = client; if (sampleClient == null) { System.out.println("Invalid sample client passed to SampleLifecycleEvents"); } } @Override public void onAttemptingConnect(Mqtt5Client client, OnAttemptingConnectReturn onAttemptingConnectReturn) { System.out.println("[" + sampleClient.name + "]: Attempting connection..."); } @Override public void onConnectionSuccess(Mqtt5Client client, OnConnectionSuccessReturn onConnectionSuccessReturn) { System.out.println("[" + sampleClient.name + "]: Connection success, client ID: " + onConnectionSuccessReturn.getNegotiatedSettings().getAssignedClientID()); connectedFuture.complete(null); } @Override public void onConnectionFailure(Mqtt5Client client, OnConnectionFailureReturn onConnectionFailureReturn) { String errorString = CRT.awsErrorString(onConnectionFailureReturn.getErrorCode()); System.out.println("[" + sampleClient.name + "]: Connection failed with error: " + errorString); connectedFuture.completeExceptionally(new Exception("Could not connect: " + errorString)); } @Override public void onDisconnection(Mqtt5Client client, OnDisconnectionReturn onDisconnectionReturn) { System.out.println("[" + sampleClient.name + "]: Disconnected"); DisconnectPacket disconnectPacket = onDisconnectionReturn.getDisconnectPacket(); if (disconnectPacket != null) { System.out.println("\tDisconnection packet code: " + disconnectPacket.getReasonCode()); System.out.println("\tDisconnection packet reason: " + disconnectPacket.getReasonString()); if (disconnectPacket.getReasonCode() == DisconnectPacket.DisconnectReasonCode.SHARED_SUBSCRIPTIONS_NOT_SUPPORTED) { /* Stop the client, which will interrupt the subscription and stop the sample */ client.stop(null); } } } @Override public void onStopped(Mqtt5Client client, OnStoppedReturn onStoppedReturn) { System.out.println("[" + sampleClient.name + "]: Stopped"); stoppedFuture.complete(null); } } /** * The interface that contains the functions invoked when the MQTT5 client gets a message/publish * on a topic the MQTT5 client has subscribed to. */ static final class SamplePublishEvents implements Mqtt5ClientOptions.PublishEvents { SampleMqtt5Client sampleClient; SamplePublishEvents(SampleMqtt5Client client) { sampleClient = client; } @Override public void onMessageReceived(Mqtt5Client client, PublishReturn publishReturn) { if (sampleClient != null && sampleClient.client == client) { System.out.println("[" + sampleClient.name + "] Received a publish"); } PublishPacket publishPacket = publishReturn.getPublishPacket(); if (publishPacket != null) { System.out.println("\tPublish received on topic: " + publishPacket.getTopic()); System.out.println("\tMessage: " + new String(publishPacket.getPayload())); List<UserProperty> packetProperties = publishPacket.getUserProperties(); if (packetProperties != null) { for (int i = 0; i < packetProperties.size(); i++) { UserProperty property = packetProperties.get(i); System.out.println("\t\twith UserProperty: (" + property.key + ", " + property.value + ")"); } } } } } /** * For the purposes of this sample, we need to associate certain variables with a particular MQTT5 client * and to do so we use this class to hold all the data for a particular client used in the sample. */ static final class SampleMqtt5Client { Mqtt5Client client; String name; SamplePublishEvents publishEvents; SampleLifecycleEvents lifecycleEvents; /** * Creates a MQTT5 client using direct MQTT5 via mTLS with the passed input data. */ public static SampleMqtt5Client createMqtt5Client( String input_endpoint, String input_cert, String input_key, String input_ca, String input_clientId, String input_clientName) { SampleMqtt5Client sampleClient = new SampleMqtt5Client(); SamplePublishEvents publishEvents = new SamplePublishEvents(sampleClient); SampleLifecycleEvents lifecycleEvents = new SampleLifecycleEvents(sampleClient); Mqtt5Client client; try { AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newDirectMqttBuilderWithMtlsFromPath(input_endpoint, input_cert, input_key); ConnectPacket.ConnectPacketBuilder connectProperties = new ConnectPacket.ConnectPacketBuilder(); connectProperties.withClientId(input_clientId); builder.withConnectProperties(connectProperties); if (input_ca != "") { builder.withCertificateAuthorityFromPath(null, input_ca); } builder.withLifeCycleEvents(lifecycleEvents); builder.withPublishEvents(publishEvents); client = builder.build(); builder.close(); } catch (CrtRuntimeException ex) { System.out.println("Client creation failed!"); return null; } sampleClient.client = client; sampleClient.name = input_clientName; sampleClient.publishEvents = publishEvents; sampleClient.lifecycleEvents = lifecycleEvents; return sampleClient; } } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("Mqtt5SharedSubscription", args); /* Construct the shared topic */ String input_sharedTopic = "$share/" + cmdData.input_groupIdentifier + "/" + cmdData.input_topic; /* This sample uses a publisher and two subscribers */ SampleMqtt5Client publisher = null; SampleMqtt5Client subscriberOne = null; SampleMqtt5Client subscriberTwo = null; try { /* Create the MQTT5 clients: one publisher and two subscribers */ publisher = SampleMqtt5Client.createMqtt5Client( cmdData.input_endpoint, cmdData.input_cert, cmdData.input_key, cmdData.input_ca, cmdData.input_clientId + '1', "Publisher"); subscriberOne = SampleMqtt5Client.createMqtt5Client( cmdData.input_endpoint, cmdData.input_cert, cmdData.input_key, cmdData.input_ca, cmdData.input_clientId + '2', "Subscriber One"); subscriberTwo = SampleMqtt5Client.createMqtt5Client( cmdData.input_endpoint, cmdData.input_cert, cmdData.input_key, cmdData.input_ca, cmdData.input_clientId + '3', "Subscriber Two"); /* Connect all the clients */ publisher.client.start(); publisher.lifecycleEvents.connectedFuture.get(60, TimeUnit.SECONDS); System.out.println("[" + publisher.name + "]: Connected"); subscriberOne.client.start(); subscriberOne.lifecycleEvents.connectedFuture.get(60, TimeUnit.SECONDS); System.out.println("[" + subscriberOne.name + "]: Connected"); subscriberTwo.client.start(); subscriberTwo.lifecycleEvents.connectedFuture.get(60, TimeUnit.SECONDS); System.out.println("[" + subscriberTwo.name + "]: Connected"); /* Subscribe to the shared topic on the two subscribers */ SubscribePacket.SubscribePacketBuilder subscribeBuilder = new SubscribePacket.SubscribePacketBuilder(); subscribeBuilder.withSubscription(input_sharedTopic, QOS.AT_LEAST_ONCE, false, false, SubscribePacket.RetainHandlingType.DONT_SEND); subscriberOne.client.subscribe(subscribeBuilder.build()).get(60, TimeUnit.SECONDS); System.out.println( "[" + subscriberOne.name + "]: Subscribed to topic '" + cmdData.input_topic + "' in shared subscription group '" + cmdData.input_groupIdentifier + "'."); System.out.println("[" + subscriberOne.name + "]: Full subscribed topic is '" + input_sharedTopic + "'."); subscriberTwo.client.subscribe(subscribeBuilder.build()).get(60, TimeUnit.SECONDS); System.out.println( "[" + subscriberTwo.name + "]: Subscribed to topic '" + cmdData.input_topic + "' in shared subscription group '" + cmdData.input_groupIdentifier + "'."); System.out.println("[" + subscriberTwo.name + "]: Full subscribed topic is '" + input_sharedTopic + "'."); /* Publish using the publisher client */ PublishPacket.PublishPacketBuilder publishBuilder = new PublishPacket.PublishPacketBuilder(); publishBuilder.withTopic(cmdData.input_topic).withQOS(QOS.AT_LEAST_ONCE); int count = 0; if (cmdData.input_count > 0) { while (count++ < cmdData.input_count) { publishBuilder.withPayload(("\"" + cmdData.input_message + ": " + String.valueOf(count) + "\"").getBytes()); publisher.client.publish(publishBuilder.build()).get(60, TimeUnit.SECONDS); System.out.println("[" + publisher.name + "]: Sent publish"); Thread.sleep(1000); } /* Wait 5 seconds to let the last publish go out before unsubscribing */ Thread.sleep(5000); } else { System.out.println("Skipping publishing messages due to message count being zero..."); } /* Unsubscribe from the shared topic on the two subscribers */ UnsubscribePacket.UnsubscribePacketBuilder unsubscribeBuilder = new UnsubscribePacket.UnsubscribePacketBuilder(); unsubscribeBuilder.withSubscription(input_sharedTopic); subscriberOne.client.unsubscribe(unsubscribeBuilder.build()).get(60, TimeUnit.SECONDS); System.out.println( "[" + subscriberOne.name + "]: Unsubscribed to topic '" + cmdData.input_topic + "' in shared subscription group '" + cmdData.input_groupIdentifier + "'."); System.out.println("[" + subscriberOne.name + "]: Full unsubscribed topic is '" + input_sharedTopic + "'."); subscriberTwo.client.unsubscribe(unsubscribeBuilder.build()).get(60, TimeUnit.SECONDS); System.out.println( "[" + subscriberTwo.name + "]: Unsubscribed to topic '" + cmdData.input_topic + "' in shared subscription group '" + cmdData.input_groupIdentifier + "'."); System.out.println("[" + subscriberTwo.name + "]: Full unsubscribed topic is '" + input_sharedTopic + "'."); /* Disconnect all the clients */ publisher.client.stop(null); publisher.lifecycleEvents.stoppedFuture.get(60, TimeUnit.SECONDS); System.out.println("[" + publisher.name + "]: Fully stopped"); subscriberOne.client.stop(null); subscriberOne.lifecycleEvents.stoppedFuture.get(60, TimeUnit.SECONDS); System.out.println("[" + subscriberOne.name + "]: Fully stopped"); subscriberTwo.client.stop(null); subscriberTwo.lifecycleEvents.stoppedFuture.get(60, TimeUnit.SECONDS); System.out.println("[" + subscriberTwo.name + "]: Fully stopped"); } catch (Exception ex) { /* Something bad happened, abort and report! */ onApplicationFailure(ex); } finally { /* Close all the MQTT5 clients to make sure no native memory is leaked */ if (publisher != null && publisher.client != null) { publisher.client.close(); } if (subscriberOne != null && subscriberOne.client != null) { subscriberOne.client.close(); } if (subscriberTwo != null && subscriberTwo.client != null) { subscriberTwo.client.close(); } CrtResource.waitForNoResources(); } System.out.println("Complete!"); } }
5,190
0
Create_ds/aws-iot-device-sdk-java-v2/samples/Mqtt5/PubSub/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/samples/Mqtt5/PubSub/src/main/java/pubsub/PubSub.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package mqtt5.pubsub; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.io.ClientBootstrap; import software.amazon.awssdk.crt.mqtt5.*; import software.amazon.awssdk.crt.mqtt5.Mqtt5ClientOptions.LifecycleEvents; import software.amazon.awssdk.crt.mqtt5.packets.*; import software.amazon.awssdk.iot.AwsIotMqtt5ClientBuilder; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import utils.commandlineutils.CommandLineUtils; public class PubSub { // When run normally, we want to exit nicely even if something goes wrong // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static CommandLineUtils cmdUtils; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("Mqtt5 PubSub: execution failure", cause); } else if (cause != null) { System.out.println("Exception encountered: " + cause.toString()); } } static final class SampleLifecycleEvents implements Mqtt5ClientOptions.LifecycleEvents { CompletableFuture<Void> connectedFuture = new CompletableFuture<>(); CompletableFuture<Void> stoppedFuture = new CompletableFuture<>(); @Override public void onAttemptingConnect(Mqtt5Client client, OnAttemptingConnectReturn onAttemptingConnectReturn) { System.out.println("Mqtt5 Client: Attempting connection..."); } @Override public void onConnectionSuccess(Mqtt5Client client, OnConnectionSuccessReturn onConnectionSuccessReturn) { System.out.println("Mqtt5 Client: Connection success, client ID: " + onConnectionSuccessReturn.getNegotiatedSettings().getAssignedClientID()); connectedFuture.complete(null); } @Override public void onConnectionFailure(Mqtt5Client client, OnConnectionFailureReturn onConnectionFailureReturn) { String errorString = CRT.awsErrorString(onConnectionFailureReturn.getErrorCode()); System.out.println("Mqtt5 Client: Connection failed with error: " + errorString); connectedFuture.completeExceptionally(new Exception("Could not connect: " + errorString)); } @Override public void onDisconnection(Mqtt5Client client, OnDisconnectionReturn onDisconnectionReturn) { System.out.println("Mqtt5 Client: Disconnected"); DisconnectPacket disconnectPacket = onDisconnectionReturn.getDisconnectPacket(); if (disconnectPacket != null) { System.out.println("\tDisconnection packet code: " + disconnectPacket.getReasonCode()); System.out.println("\tDisconnection packet reason: " + disconnectPacket.getReasonString()); } } @Override public void onStopped(Mqtt5Client client, OnStoppedReturn onStoppedReturn) { System.out.println("Mqtt5 Client: Stopped"); stoppedFuture.complete(null); } } static final class SamplePublishEvents implements Mqtt5ClientOptions.PublishEvents { CountDownLatch messagesReceived; SamplePublishEvents(int messageCount) { messagesReceived = new CountDownLatch(messageCount); } @Override public void onMessageReceived(Mqtt5Client client, PublishReturn publishReturn) { PublishPacket publishPacket = publishReturn.getPublishPacket(); if (publishPacket == null) { messagesReceived.countDown(); return; } System.out.println("Publish received on topic: " + publishPacket.getTopic()); System.out.println("Message: " + new String(publishPacket.getPayload())); List<UserProperty> packetProperties = publishPacket.getUserProperties(); if (packetProperties != null) { for (int i = 0; i < packetProperties.size(); i++) { UserProperty property = packetProperties.get(i); System.out.println("\twith UserProperty: (" + property.key + ", " + property.value + ")"); } } messagesReceived.countDown(); } } public static void main(String[] args) { /** * cmdData is the arguments/input from the command line placed into a single struct for * use in this sample. This handles all of the command line parsing, validating, etc. * See the Utils/CommandLineUtils for more information. */ CommandLineUtils.SampleCommandLineData cmdData = CommandLineUtils.getInputForIoTSample("Mqtt5PubSub", args); try { /* Create a client based on desired connection type */ SampleLifecycleEvents lifecycleEvents = new SampleLifecycleEvents(); SamplePublishEvents publishEvents = new SamplePublishEvents(cmdData.input_count); Mqtt5Client client; /** * Create the MQTT connection from the builder */ if (cmdData.input_cert != "" || cmdData.input_key != "") { AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newDirectMqttBuilderWithMtlsFromPath( cmdData.input_endpoint, cmdData.input_cert, cmdData.input_key); ConnectPacket.ConnectPacketBuilder connectProperties = new ConnectPacket.ConnectPacketBuilder(); connectProperties.withClientId(cmdData.input_clientId); builder.withConnectProperties(connectProperties); builder.withLifeCycleEvents(lifecycleEvents); builder.withPublishEvents(publishEvents); client = builder.build(); builder.close(); } else { AwsIotMqtt5ClientBuilder.WebsocketSigv4Config websocketConfig = new AwsIotMqtt5ClientBuilder.WebsocketSigv4Config(); if (cmdData.input_signingRegion != "") { websocketConfig.region = cmdData.input_signingRegion; } AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newWebsocketMqttBuilderWithSigv4Auth( cmdData.input_endpoint, websocketConfig); ConnectPacket.ConnectPacketBuilder connectProperties = new ConnectPacket.ConnectPacketBuilder(); connectProperties.withClientId(cmdData.input_clientId); builder.withConnectProperties(connectProperties); builder.withLifeCycleEvents(lifecycleEvents); builder.withPublishEvents(publishEvents); client = builder.build(); builder.close(); } /* Connect */ client.start(); try { lifecycleEvents.connectedFuture.get(60, TimeUnit.SECONDS); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } /* Subscribe */ SubscribePacket.SubscribePacketBuilder subscribeBuilder = new SubscribePacket.SubscribePacketBuilder(); subscribeBuilder.withSubscription(cmdData.input_topic, QOS.AT_LEAST_ONCE, false, false, SubscribePacket.RetainHandlingType.DONT_SEND); try { client.subscribe(subscribeBuilder.build()).get(60, TimeUnit.SECONDS); } catch (Exception ex) { onApplicationFailure(ex); } /* Publish */ PublishPacket.PublishPacketBuilder publishBuilder = new PublishPacket.PublishPacketBuilder(); publishBuilder.withTopic(cmdData.input_topic).withQOS(QOS.AT_LEAST_ONCE); int count = 0; try { while (count++ < cmdData.input_count) { publishBuilder.withPayload(("\"" + cmdData.input_message + ": " + String.valueOf(count) + "\"").getBytes()); CompletableFuture<PublishResult> published = client.publish(publishBuilder.build()); published.get(60, TimeUnit.SECONDS); Thread.sleep(1000); } } catch (Exception ex) { onApplicationFailure(ex); } publishEvents.messagesReceived.await(120, TimeUnit.SECONDS); /* Disconnect */ DisconnectPacket.DisconnectPacketBuilder disconnectBuilder = new DisconnectPacket.DisconnectPacketBuilder(); disconnectBuilder.withReasonCode(DisconnectPacket.DisconnectReasonCode.NORMAL_DISCONNECTION); client.stop(disconnectBuilder.build()); try { lifecycleEvents.stoppedFuture.get(60, TimeUnit.SECONDS); } catch (Exception ex) { onApplicationFailure(ex); } /* Close the client to free memory */ client.close(); } catch (CrtRuntimeException | InterruptedException ex) { onApplicationFailure(ex); } CrtResource.waitForNoResources(); System.out.println("Complete!"); } }
5,191
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/tests
Create_ds/aws-iot-device-sdk-java-v2/sdk/tests/iot/ShadowStateTest.java
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import software.amazon.awssdk.iot.Timestamp; import software.amazon.awssdk.iot.iotshadow.model.ShadowState; import software.amazon.awssdk.iot.ShadowStateFactory; import java.util.HashMap; public class ShadowStateTest { private Gson shadowGson = null; @BeforeEach public void TestSetup() { if (shadowGson == null) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.disableHtmlEscaping(); gsonBuilder.registerTypeAdapter(Timestamp.class, new Timestamp.Serializer()); gsonBuilder.registerTypeAdapter(Timestamp.class, new Timestamp.Deserializer()); ShadowStateFactory shadowStateFactory = new ShadowStateFactory(); gsonBuilder.registerTypeAdapterFactory(shadowStateFactory); shadowGson = gsonBuilder.create(); } } @Test public void TestHardCoded() { ShadowState state = new ShadowState(); state.desired = new HashMap<String, Object>() {{ put("ThingOne", 10.0); put("ThingTwo", "Bob"); }}; String state_json = shadowGson.toJson(state); String expected_json = "{\"desired\":{\"ThingTwo\":\"Bob\",\"ThingOne\":10.0}}"; assertEquals(state_json, expected_json); } @Test public void TestCompareJsonOutputs() { ShadowState state = new ShadowState(); state.desired = new HashMap<String, Object>() {{ put("ThingOne", 10.0); put("ThingTwo", "Bob"); }}; String state_json = shadowGson.toJson(state); String state_two_input = "{\"desired\":{\"ThingTwo\":\"Bob\",\"ThingOne\":10.0}}"; ShadowState state_two = shadowGson.fromJson(state_two_input, ShadowState.class); String state_two_json = shadowGson.toJson(state_two); assertEquals(state_json, state_two_json); } @Test public void TestNullSendThroughJson() { ShadowState state = new ShadowState(); state.desired = new HashMap<String, Object>() {{ put("ThingOne", 10.0); put("ThingTwo", "Bob"); }}; state.reported = null; state.reportedIsNullable = true; String state_json = shadowGson.toJson(state); String expected_json = "{\"desired\":{\"ThingTwo\":\"Bob\",\"ThingOne\":10.0},\"reported\":null}"; assertEquals(state_json, expected_json); } }
5,192
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/tests
Create_ds/aws-iot-device-sdk-java-v2/sdk/tests/mqtt/MqttBuilderTest.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.util.UUID; import java.util.function.Consumer; import org.junit.jupiter.api.Test; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.WebsocketHandshakeTransformArgs; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; /** * NOTE: Will later add more testing and split MQTT5 testing setup from MQTT311 testing setup. * In the short term, the MQTT311 tests will reuse the majority of MQTT5 material. */ public class MqttBuilderTest { private String mqtt5IoTCoreHost; private String mqtt5IoTCoreRegion; private String mqtt5IoTCoreNoSigningAuthorizerName; private String mqtt5IoTCoreNoSigningAuthorizerUsername; private String mqtt5IoTCoreNoSigningAuthorizerPassword; private String mqtt5IoTCoreSigningAuthorizerName; private String mqtt5IoTCoreSigningAuthorizerUsername; private String mqtt5IoTCoreSigningAuthorizerPassword; private String mqtt5IoTCoreSigningAuthorizerToken; private String mqtt5IoTCoreSigningAuthorizerTokenKeyName; private String mqtt5IoTCoreSigningAuthorizerTokenSignature; private void populateTestingEnvironmentVariables() { mqtt5IoTCoreHost = System.getenv("AWS_TEST_MQTT5_IOT_CORE_HOST"); mqtt5IoTCoreRegion = System.getenv("AWS_TEST_MQTT5_IOT_CORE_REGION"); mqtt5IoTCoreNoSigningAuthorizerName = System.getenv("AWS_TEST_MQTT5_IOT_CORE_NO_SIGNING_AUTHORIZER_NAME"); mqtt5IoTCoreNoSigningAuthorizerUsername = System.getenv("AWS_TEST_MQTT5_IOT_CORE_NO_SIGNING_AUTHORIZER_USERNAME"); mqtt5IoTCoreNoSigningAuthorizerPassword = System.getenv("AWS_TEST_MQTT5_IOT_CORE_NO_SIGNING_AUTHORIZER_PASSWORD"); mqtt5IoTCoreSigningAuthorizerName = System.getenv("AWS_TEST_MQTT5_IOT_CORE_SIGNING_AUTHORIZER_NAME"); mqtt5IoTCoreSigningAuthorizerUsername = System.getenv("AWS_TEST_MQTT5_IOT_CORE_SIGNING_AUTHORIZER_USERNAME"); mqtt5IoTCoreSigningAuthorizerPassword = System.getenv("AWS_TEST_MQTT5_IOT_CORE_SIGNING_AUTHORIZER_PASSWORD"); mqtt5IoTCoreSigningAuthorizerToken = System.getenv("AWS_TEST_MQTT5_IOT_CORE_SIGNING_AUTHORIZER_TOKEN"); mqtt5IoTCoreSigningAuthorizerTokenKeyName = System.getenv("AWS_TEST_MQTT5_IOT_CORE_SIGNING_AUTHORIZER_TOKEN_KEY_NAME"); mqtt5IoTCoreSigningAuthorizerTokenSignature = System.getenv("AWS_TEST_MQTT5_IOT_CORE_SIGNING_AUTHORIZER_TOKEN_SIGNATURE"); } private Consumer<WebsocketHandshakeTransformArgs> websocketTransform = new Consumer<WebsocketHandshakeTransformArgs>() { @Override public void accept(WebsocketHandshakeTransformArgs t) { t.complete(t.getHttpRequest()); } }; MqttBuilderTest() { populateTestingEnvironmentVariables(); } /** * ============================================================ * IOT BUILDER TEST CASES * ============================================================ */ /* MQTT311 Custom Auth (no signing) connect */ @Test public void ConnIoT_CustomAuth_UC1() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreNoSigningAuthorizerName != null); assumeTrue(mqtt5IoTCoreNoSigningAuthorizerUsername != null); assumeTrue(mqtt5IoTCoreNoSigningAuthorizerPassword != null); try { AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newDefaultBuilder(); builder.withEndpoint(mqtt5IoTCoreHost); String clientId = "test-" + UUID.randomUUID().toString(); builder.withClientId(clientId); builder.withCustomAuthorizer( mqtt5IoTCoreNoSigningAuthorizerUsername, mqtt5IoTCoreNoSigningAuthorizerName, null, mqtt5IoTCoreNoSigningAuthorizerPassword, null, null); MqttClientConnection connection = builder.build(); builder.close(); connection.connect().get(); connection.disconnect().get(); connection.close(); } catch (Exception ex) { fail(ex); } } /* MQTT311 Custom Auth (with signing) connect */ @Test public void ConnIoT_CustomAuth_UC2() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerUsername != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerPassword != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerToken != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenKeyName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenSignature != null); try { AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newDefaultBuilder(); builder.withEndpoint(mqtt5IoTCoreHost); String clientId = "test-" + UUID.randomUUID().toString(); builder.withClientId(clientId); builder.withCustomAuthorizer( mqtt5IoTCoreSigningAuthorizerUsername, mqtt5IoTCoreSigningAuthorizerName, mqtt5IoTCoreSigningAuthorizerTokenSignature, mqtt5IoTCoreSigningAuthorizerPassword, mqtt5IoTCoreSigningAuthorizerTokenKeyName, mqtt5IoTCoreSigningAuthorizerToken); MqttClientConnection connection = builder.build(); builder.close(); connection.connect().get(); connection.disconnect().get(); connection.close(); } catch (Exception ex) { fail(ex); } } /* Custom Auth (no signing) connect - Websockets */ @Test public void ConnIoT_CustomAuth_UC3() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreRegion != null); assumeTrue(mqtt5IoTCoreNoSigningAuthorizerName != null); assumeTrue(mqtt5IoTCoreNoSigningAuthorizerUsername != null); assumeTrue(mqtt5IoTCoreNoSigningAuthorizerPassword != null); try { AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newDefaultBuilder(); builder.withEndpoint(mqtt5IoTCoreHost); String clientId = "test-" + UUID.randomUUID().toString(); builder.withClientId(clientId); builder.withWebsockets(true); builder.withWebsocketSigningRegion(mqtt5IoTCoreRegion); builder.withWebsocketHandshakeTransform(websocketTransform); builder.withCustomAuthorizer( mqtt5IoTCoreNoSigningAuthorizerUsername, mqtt5IoTCoreNoSigningAuthorizerName, null, mqtt5IoTCoreNoSigningAuthorizerPassword, null, null); MqttClientConnection connection = builder.build(); builder.close(); connection.connect().get(); connection.disconnect().get(); connection.close(); } catch (Exception ex) { fail(ex); } } /* Custom Auth (with signing) connect - Websockets */ @Test public void ConnIoT_CustomAuth_UC4() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreRegion != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerUsername != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerPassword != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerToken != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenKeyName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenSignature != null); try { AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newDefaultBuilder(); builder.withEndpoint(mqtt5IoTCoreHost); String clientId = "test-" + UUID.randomUUID().toString(); builder.withClientId(clientId); builder.withWebsockets(true); builder.withWebsocketSigningRegion(mqtt5IoTCoreRegion); builder.withWebsocketHandshakeTransform(websocketTransform); builder.withCustomAuthorizer( mqtt5IoTCoreSigningAuthorizerUsername, mqtt5IoTCoreSigningAuthorizerName, mqtt5IoTCoreSigningAuthorizerTokenSignature, mqtt5IoTCoreSigningAuthorizerPassword, mqtt5IoTCoreSigningAuthorizerTokenKeyName, mqtt5IoTCoreSigningAuthorizerToken); MqttClientConnection connection = builder.build(); builder.close(); connection.connect().get(); connection.disconnect().get(); connection.close(); } catch (Exception ex) { fail(ex); } } /* Custom Auth (with signing) connect - Websockets - Invalid Password */ @Test public void ConnIoT_CustomAuth_InvalidPassword() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerUsername != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerToken != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenKeyName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenSignature != null); try { AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newDefaultBuilder(); builder.withEndpoint(mqtt5IoTCoreHost); String clientId = "test-" + UUID.randomUUID().toString(); builder.withClientId(clientId); builder.withWebsockets(true); builder.withWebsocketSigningRegion(mqtt5IoTCoreRegion); builder.withWebsocketHandshakeTransform(websocketTransform); builder.withCustomAuthorizer( mqtt5IoTCoreSigningAuthorizerUsername, mqtt5IoTCoreSigningAuthorizerName, mqtt5IoTCoreSigningAuthorizerTokenSignature, "InvalidPassword", mqtt5IoTCoreSigningAuthorizerTokenKeyName, mqtt5IoTCoreSigningAuthorizerToken); MqttClientConnection connection = builder.build(); builder.close(); assertThrows(Exception.class, () -> connection.connect().get()); connection.close(); } catch (Exception ex) { fail(ex); } } /* Custom Auth (with signing) connect - Websockets - Invalid Token */ @Test public void ConnIoT_CustomAuth_InvalidToken() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreRegion != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerUsername != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerPassword != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerToken != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenSignature != null); try { AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newDefaultBuilder(); builder.withEndpoint(mqtt5IoTCoreHost); String clientId = "test-" + UUID.randomUUID().toString(); builder.withClientId(clientId); builder.withWebsockets(true); builder.withWebsocketSigningRegion(mqtt5IoTCoreRegion); builder.withWebsocketHandshakeTransform(websocketTransform); builder.withCustomAuthorizer( mqtt5IoTCoreSigningAuthorizerUsername, mqtt5IoTCoreSigningAuthorizerName, mqtt5IoTCoreSigningAuthorizerTokenSignature, mqtt5IoTCoreSigningAuthorizerPassword, "Invalid Token", mqtt5IoTCoreSigningAuthorizerToken); MqttClientConnection connection = builder.build(); builder.close(); assertThrows(Exception.class, () -> connection.connect().get()); connection.close(); } catch (Exception ex) { fail(ex); } } /* Custom Auth (with signing) connect - Websockets - Invalid Token Signature */ @Test public void ConnIoT_CustomAuth_InvalidTokenSignature() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreRegion != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerUsername != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerPassword != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerToken != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenKeyName != null); try { AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newDefaultBuilder(); builder.withEndpoint(mqtt5IoTCoreHost); String clientId = "test-" + UUID.randomUUID().toString(); builder.withClientId(clientId); builder.withWebsockets(true); builder.withWebsocketSigningRegion(mqtt5IoTCoreRegion); builder.withWebsocketHandshakeTransform(websocketTransform); builder.withCustomAuthorizer( mqtt5IoTCoreSigningAuthorizerUsername, mqtt5IoTCoreSigningAuthorizerName, "InvalidTokenSignature", mqtt5IoTCoreSigningAuthorizerPassword, mqtt5IoTCoreSigningAuthorizerTokenKeyName, mqtt5IoTCoreSigningAuthorizerToken); MqttClientConnection connection = builder.build(); builder.close(); assertThrows(Exception.class, () -> connection.connect().get()); connection.close(); } catch (Exception ex) { fail(ex); } } }
5,193
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/tests
Create_ds/aws-iot-device-sdk-java-v2/sdk/tests/mqtt5/Mqtt5BuilderTest.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeTrue; import org.junit.jupiter.api.Test; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.mqtt5.Mqtt5Client; import software.amazon.awssdk.crt.mqtt5.Mqtt5ClientOptions; import software.amazon.awssdk.crt.mqtt5.NegotiatedSettings; import software.amazon.awssdk.crt.mqtt5.OnAttemptingConnectReturn; import software.amazon.awssdk.crt.mqtt5.OnConnectionFailureReturn; import software.amazon.awssdk.crt.mqtt5.OnConnectionSuccessReturn; import software.amazon.awssdk.crt.mqtt5.OnDisconnectionReturn; import software.amazon.awssdk.crt.mqtt5.OnStoppedReturn; import software.amazon.awssdk.crt.mqtt5.PublishResult; import software.amazon.awssdk.crt.mqtt5.PublishReturn; import software.amazon.awssdk.crt.mqtt5.QOS; import software.amazon.awssdk.crt.mqtt5.packets.ConnAckPacket; import software.amazon.awssdk.crt.mqtt5.packets.DisconnectPacket; import software.amazon.awssdk.crt.mqtt5.packets.PublishPacket; import software.amazon.awssdk.crt.mqtt5.packets.SubscribePacket; import software.amazon.awssdk.crt.mqtt5.packets.UnsubscribePacket; import software.amazon.awssdk.iot.AwsIotMqtt5ClientBuilder; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; public class Mqtt5BuilderTest { private String mqtt5IoTCoreHost; private String mqtt5IoTCoreCertificatePath; private String mqtt5IoTCoreKeyPath; private String mqtt5IoTCoreNoSigningAuthorizerName; private String mqtt5IoTCoreNoSigningAuthorizerUsername; private String mqtt5IoTCoreNoSigningAuthorizerPassword; private String mqtt5IoTCoreSigningAuthorizerName; private String mqtt5IoTCoreSigningAuthorizerUsername; private String mqtt5IoTCoreSigningAuthorizerPassword; private String mqtt5IoTCoreSigningAuthorizerToken; private String mqtt5IoTCoreSigningAuthorizerTokenKeyName; private String mqtt5IoTCoreSigningAuthorizerTokenSignature; private void populateTestingEnvironmentVariables() { mqtt5IoTCoreHost = System.getenv("AWS_TEST_MQTT5_IOT_CORE_HOST"); mqtt5IoTCoreCertificatePath = System.getenv("AWS_TEST_MQTT5_IOT_CERTIFICATE_PATH"); mqtt5IoTCoreKeyPath = System.getenv("AWS_TEST_MQTT5_IOT_KEY_PATH"); mqtt5IoTCoreNoSigningAuthorizerName = System.getenv("AWS_TEST_MQTT5_IOT_CORE_NO_SIGNING_AUTHORIZER_NAME"); mqtt5IoTCoreNoSigningAuthorizerUsername = System.getenv("AWS_TEST_MQTT5_IOT_CORE_NO_SIGNING_AUTHORIZER_USERNAME"); mqtt5IoTCoreNoSigningAuthorizerPassword = System.getenv("AWS_TEST_MQTT5_IOT_CORE_NO_SIGNING_AUTHORIZER_PASSWORD"); mqtt5IoTCoreSigningAuthorizerName = System.getenv("AWS_TEST_MQTT5_IOT_CORE_SIGNING_AUTHORIZER_NAME"); mqtt5IoTCoreSigningAuthorizerUsername = System.getenv("AWS_TEST_MQTT5_IOT_CORE_SIGNING_AUTHORIZER_USERNAME"); mqtt5IoTCoreSigningAuthorizerPassword = System.getenv("AWS_TEST_MQTT5_IOT_CORE_SIGNING_AUTHORIZER_PASSWORD"); mqtt5IoTCoreSigningAuthorizerToken = System.getenv("AWS_TEST_MQTT5_IOT_CORE_SIGNING_AUTHORIZER_TOKEN"); mqtt5IoTCoreSigningAuthorizerTokenKeyName = System.getenv("AWS_TEST_MQTT5_IOT_CORE_SIGNING_AUTHORIZER_TOKEN_KEY_NAME"); mqtt5IoTCoreSigningAuthorizerTokenSignature = System.getenv("AWS_TEST_MQTT5_IOT_CORE_SIGNING_AUTHORIZER_TOKEN_SIGNATURE"); } Mqtt5BuilderTest() { populateTestingEnvironmentVariables(); } /** * ============================================================ * TEST HELPER FUNCTIONS * ============================================================ */ static final class LifecycleEvents_Futured implements Mqtt5ClientOptions.LifecycleEvents { CompletableFuture<Void> connectedFuture = new CompletableFuture<>(); CompletableFuture<Void> stopFuture = new CompletableFuture<>(); ConnAckPacket connectSuccessPacket = null; NegotiatedSettings connectSuccessSettings = null; int connectFailureCode = 0; ConnAckPacket connectFailurePacket = null; int disconnectFailureCode = 0; DisconnectPacket disconnectPacket = null; @Override public void onAttemptingConnect(Mqtt5Client client, OnAttemptingConnectReturn onAttemptingConnectReturn) {} @Override public void onConnectionSuccess(Mqtt5Client client, OnConnectionSuccessReturn onConnectionSuccessReturn) { connectSuccessPacket = onConnectionSuccessReturn.getConnAckPacket(); connectSuccessSettings = onConnectionSuccessReturn.getNegotiatedSettings(); connectedFuture.complete(null); } @Override public void onConnectionFailure(Mqtt5Client client, OnConnectionFailureReturn onConnectionFailureReturn) { connectFailureCode = onConnectionFailureReturn.getErrorCode(); connectFailurePacket = onConnectionFailureReturn.getConnAckPacket(); connectedFuture.completeExceptionally(new Exception("Could not connect! Failure code: " + CRT.awsErrorString(connectFailureCode))); } @Override public void onDisconnection(Mqtt5Client client, OnDisconnectionReturn onDisconnectionReturn) { disconnectFailureCode = onDisconnectionReturn.getErrorCode(); disconnectPacket = onDisconnectionReturn.getDisconnectPacket(); } @Override public void onStopped(Mqtt5Client client, OnStoppedReturn onStoppedReturn) { stopFuture.complete(null); } } static final class PublishEvents_Futured implements Mqtt5ClientOptions.PublishEvents { CompletableFuture<Void> publishReceivedFuture = new CompletableFuture<>(); PublishPacket publishPacket = null; @Override public void onMessageReceived(Mqtt5Client client, PublishReturn publishReturn) { publishPacket = publishReturn.getPublishPacket(); publishReceivedFuture.complete(null); } } private void TestSubPubUnsub(Mqtt5Client client, LifecycleEvents_Futured lifecycleEvents, PublishEvents_Futured publishEvents) { String topic_uuid = UUID.randomUUID().toString(); // Connect try { client.start(); lifecycleEvents.connectedFuture.get(120, TimeUnit.SECONDS); } catch (Exception ex) { fail("Exception in connecting: " + ex.toString()); } assertTrue(client.getIsConnected() == true); // Sub SubscribePacket.SubscribePacketBuilder subBuilder = new SubscribePacket.SubscribePacketBuilder(); subBuilder.withSubscription("test/topic/" + topic_uuid, QOS.AT_LEAST_ONCE); try { client.subscribe(subBuilder.build()).get(120, TimeUnit.SECONDS); } catch (Exception ex) { fail("Exception in subscribing: " + ex.toString()); } // Pub PublishPacket.PublishPacketBuilder pubBuilder = new PublishPacket.PublishPacketBuilder(); String publishPayload = "Hello World"; pubBuilder.withTopic("test/topic/" + topic_uuid).withQOS(QOS.AT_LEAST_ONCE).withPayload(publishPayload.getBytes()); try { PublishResult result = client.publish(pubBuilder.build()).get(120, TimeUnit.SECONDS); } catch (Exception ex) { fail("Exception in publishing: " + ex.toString()); } try { publishEvents.publishReceivedFuture.get(120, TimeUnit.SECONDS); String resultStr = new String(publishEvents.publishPacket.getPayload()); assertTrue(resultStr.equals(publishPayload)); } catch (Exception ex) { fail("Exception in getting publish: " + ex.toString()); } // Unsubscribe UnsubscribePacket.UnsubscribePacketBuilder unsubBuilder = new UnsubscribePacket.UnsubscribePacketBuilder(); unsubBuilder.withSubscription("test/topic/" + topic_uuid); try { client.unsubscribe(unsubBuilder.build()).get(120, TimeUnit.SECONDS); } catch (Exception ex) { fail("Exception in unsubscribing: " + ex.toString()); } // Disconnect/Stop try { client.stop(new DisconnectPacket.DisconnectPacketBuilder().build()); lifecycleEvents.stopFuture.get(120, TimeUnit.SECONDS); } catch (Exception ex) { fail("Exception in stopping: " + ex.toString()); } assertTrue(client.getIsConnected() == false); } /** * ============================================================ * IOT BUILDER TEST CASES * ============================================================ */ /* Testing direct connect with mTLS (cert and key) */ @Test public void ConnIoT_DirectConnect_UC1() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreCertificatePath != null); assumeTrue(mqtt5IoTCoreKeyPath != null); AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newDirectMqttBuilderWithMtlsFromPath( mqtt5IoTCoreHost, mqtt5IoTCoreCertificatePath, mqtt5IoTCoreKeyPath); LifecycleEvents_Futured lifecycleEvents = new LifecycleEvents_Futured(); builder.withLifeCycleEvents(lifecycleEvents); PublishEvents_Futured publishEvents = new PublishEvents_Futured(); builder.withPublishEvents(publishEvents); Mqtt5Client client = builder.build(); TestSubPubUnsub(client, lifecycleEvents, publishEvents); client.close(); builder.close(); } /* Testing direct connect with mTLS (cert and key) - but with two clients from same builder */ @Test public void ConnIoT_DirectConnect_UC1_ALT() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreCertificatePath != null); assumeTrue(mqtt5IoTCoreKeyPath != null); AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newDirectMqttBuilderWithMtlsFromPath( mqtt5IoTCoreHost, mqtt5IoTCoreCertificatePath, mqtt5IoTCoreKeyPath); LifecycleEvents_Futured lifecycleEvents = new LifecycleEvents_Futured(); builder.withLifeCycleEvents(lifecycleEvents); PublishEvents_Futured publishEvents = new PublishEvents_Futured(); builder.withPublishEvents(publishEvents); Mqtt5Client client = builder.build(); TestSubPubUnsub(client, lifecycleEvents, publishEvents); client.close(); // Create a second client using the same builder: LifecycleEvents_Futured lifecycleEventsTwo = new LifecycleEvents_Futured(); builder.withLifeCycleEvents(lifecycleEventsTwo); PublishEvents_Futured publishEventsTwo = new PublishEvents_Futured(); builder.withPublishEvents(publishEventsTwo); Mqtt5Client clientTwo = builder.build(); TestSubPubUnsub(clientTwo, lifecycleEventsTwo, publishEventsTwo); clientTwo.close(); // Builder must be closed to free everything builder.close(); } /* Websocket connect */ @Test public void ConnIoT_WebsocketConnect_UC1() { assumeTrue(mqtt5IoTCoreHost != null); AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newWebsocketMqttBuilderWithSigv4Auth( mqtt5IoTCoreHost, null); LifecycleEvents_Futured lifecycleEvents = new LifecycleEvents_Futured(); builder.withLifeCycleEvents(lifecycleEvents); PublishEvents_Futured publishEvents = new PublishEvents_Futured(); builder.withPublishEvents(publishEvents); Mqtt5Client client = builder.build(); TestSubPubUnsub(client, lifecycleEvents, publishEvents); client.close(); builder.close(); } /* Custom Auth (no signing) connect */ @Test public void ConnIoT_CustomAuth_UC1() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreNoSigningAuthorizerName != null); assumeTrue(mqtt5IoTCoreNoSigningAuthorizerUsername != null); assumeTrue(mqtt5IoTCoreNoSigningAuthorizerPassword != null); AwsIotMqtt5ClientBuilder.MqttConnectCustomAuthConfig customAuthConfig = new AwsIotMqtt5ClientBuilder.MqttConnectCustomAuthConfig(); customAuthConfig.authorizerName = mqtt5IoTCoreNoSigningAuthorizerName; customAuthConfig.username = mqtt5IoTCoreNoSigningAuthorizerUsername; customAuthConfig.password = mqtt5IoTCoreNoSigningAuthorizerPassword.getBytes(); AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newDirectMqttBuilderWithCustomAuth( mqtt5IoTCoreHost, customAuthConfig); LifecycleEvents_Futured lifecycleEvents = new LifecycleEvents_Futured(); builder.withLifeCycleEvents(lifecycleEvents); PublishEvents_Futured publishEvents = new PublishEvents_Futured(); builder.withPublishEvents(publishEvents); Mqtt5Client client = builder.build(); TestSubPubUnsub(client, lifecycleEvents, publishEvents); client.close(); builder.close(); } /* Custom Auth (with signing) connect */ @Test public void ConnIoT_CustomAuth_UC2() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerUsername != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerPassword != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerToken != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenKeyName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenSignature != null); AwsIotMqtt5ClientBuilder.MqttConnectCustomAuthConfig customAuthConfig = new AwsIotMqtt5ClientBuilder.MqttConnectCustomAuthConfig(); customAuthConfig.authorizerName = mqtt5IoTCoreSigningAuthorizerName; customAuthConfig.username = mqtt5IoTCoreSigningAuthorizerUsername; customAuthConfig.password = mqtt5IoTCoreSigningAuthorizerPassword.getBytes(); customAuthConfig.tokenValue = mqtt5IoTCoreSigningAuthorizerToken; customAuthConfig.tokenKeyName = mqtt5IoTCoreSigningAuthorizerTokenKeyName; customAuthConfig.tokenSignature = mqtt5IoTCoreSigningAuthorizerTokenSignature; AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newDirectMqttBuilderWithCustomAuth( mqtt5IoTCoreHost, customAuthConfig); LifecycleEvents_Futured lifecycleEvents = new LifecycleEvents_Futured(); builder.withLifeCycleEvents(lifecycleEvents); PublishEvents_Futured publishEvents = new PublishEvents_Futured(); builder.withPublishEvents(publishEvents); Mqtt5Client client = builder.build(); TestSubPubUnsub(client, lifecycleEvents, publishEvents); client.close(); builder.close(); } /* Custom Auth (no signing) connect - Websockets */ @Test public void ConnIoT_CustomAuth_UC3() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreNoSigningAuthorizerName != null); assumeTrue(mqtt5IoTCoreNoSigningAuthorizerUsername != null); assumeTrue(mqtt5IoTCoreNoSigningAuthorizerPassword != null); AwsIotMqtt5ClientBuilder.MqttConnectCustomAuthConfig customAuthConfig = new AwsIotMqtt5ClientBuilder.MqttConnectCustomAuthConfig(); customAuthConfig.authorizerName = mqtt5IoTCoreNoSigningAuthorizerName; customAuthConfig.username = mqtt5IoTCoreNoSigningAuthorizerUsername; customAuthConfig.password = mqtt5IoTCoreNoSigningAuthorizerPassword.getBytes(); AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newWebsocketMqttBuilderWithCustomAuth( mqtt5IoTCoreHost, customAuthConfig); LifecycleEvents_Futured lifecycleEvents = new LifecycleEvents_Futured(); builder.withLifeCycleEvents(lifecycleEvents); PublishEvents_Futured publishEvents = new PublishEvents_Futured(); builder.withPublishEvents(publishEvents); Mqtt5Client client = builder.build(); TestSubPubUnsub(client, lifecycleEvents, publishEvents); client.close(); builder.close(); } /* Custom Auth (with signing) connect - Websockets */ @Test public void ConnIoT_CustomAuth_UC4() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerUsername != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerPassword != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerToken != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenKeyName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenSignature != null); AwsIotMqtt5ClientBuilder.MqttConnectCustomAuthConfig customAuthConfig = new AwsIotMqtt5ClientBuilder.MqttConnectCustomAuthConfig(); customAuthConfig.authorizerName = mqtt5IoTCoreSigningAuthorizerName; customAuthConfig.username = mqtt5IoTCoreSigningAuthorizerUsername; customAuthConfig.password = mqtt5IoTCoreSigningAuthorizerPassword.getBytes(); customAuthConfig.tokenValue = mqtt5IoTCoreSigningAuthorizerToken; customAuthConfig.tokenKeyName = mqtt5IoTCoreSigningAuthorizerTokenKeyName; customAuthConfig.tokenSignature = mqtt5IoTCoreSigningAuthorizerTokenSignature; AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newWebsocketMqttBuilderWithCustomAuth( mqtt5IoTCoreHost, customAuthConfig); LifecycleEvents_Futured lifecycleEvents = new LifecycleEvents_Futured(); builder.withLifeCycleEvents(lifecycleEvents); PublishEvents_Futured publishEvents = new PublishEvents_Futured(); builder.withPublishEvents(publishEvents); Mqtt5Client client = builder.build(); TestSubPubUnsub(client, lifecycleEvents, publishEvents); client.close(); builder.close(); } /* Custom Auth (with signing) connect - Websockets - Invalid Password */ @Test public void ConnIoT_CustomAuth_InvalidPassword() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerUsername != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerToken != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenKeyName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenSignature != null); AwsIotMqtt5ClientBuilder.MqttConnectCustomAuthConfig customAuthConfig = new AwsIotMqtt5ClientBuilder.MqttConnectCustomAuthConfig(); customAuthConfig.authorizerName = mqtt5IoTCoreSigningAuthorizerName; customAuthConfig.username = mqtt5IoTCoreSigningAuthorizerUsername; customAuthConfig.password = "InvalidPassword".getBytes(); customAuthConfig.tokenValue = mqtt5IoTCoreSigningAuthorizerToken; customAuthConfig.tokenKeyName = mqtt5IoTCoreSigningAuthorizerTokenKeyName; customAuthConfig.tokenSignature = mqtt5IoTCoreSigningAuthorizerTokenSignature; AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newWebsocketMqttBuilderWithCustomAuth( mqtt5IoTCoreHost, customAuthConfig); LifecycleEvents_Futured lifecycleEvents = new LifecycleEvents_Futured(); builder.withLifeCycleEvents(lifecycleEvents); PublishEvents_Futured publishEvents = new PublishEvents_Futured(); builder.withPublishEvents(publishEvents); Mqtt5Client client = builder.build(); client.start(); assertThrows(Exception.class, () -> lifecycleEvents.connectedFuture.get(120, TimeUnit.SECONDS)); client.close(); builder.close(); } /* Custom Auth (with signing) connect - Websockets - Invalid Token */ @Test public void ConnIoT_CustomAuth_InvalidToken() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerUsername != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerPassword != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerToken != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenSignature != null); AwsIotMqtt5ClientBuilder.MqttConnectCustomAuthConfig customAuthConfig = new AwsIotMqtt5ClientBuilder.MqttConnectCustomAuthConfig(); customAuthConfig.authorizerName = mqtt5IoTCoreSigningAuthorizerName; customAuthConfig.username = mqtt5IoTCoreSigningAuthorizerUsername; customAuthConfig.password = mqtt5IoTCoreSigningAuthorizerPassword.getBytes(); customAuthConfig.tokenValue = mqtt5IoTCoreSigningAuthorizerToken; customAuthConfig.tokenKeyName = "Invalid Token"; customAuthConfig.tokenSignature = mqtt5IoTCoreSigningAuthorizerTokenSignature; AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newWebsocketMqttBuilderWithCustomAuth( mqtt5IoTCoreHost, customAuthConfig); LifecycleEvents_Futured lifecycleEvents = new LifecycleEvents_Futured(); builder.withLifeCycleEvents(lifecycleEvents); PublishEvents_Futured publishEvents = new PublishEvents_Futured(); builder.withPublishEvents(publishEvents); Mqtt5Client client = builder.build(); client.start(); assertThrows(Exception.class, () -> lifecycleEvents.connectedFuture.get(120, TimeUnit.SECONDS)); client.close(); builder.close(); } /* Custom Auth (with signing) connect - Websockets - Invalid Token Signature */ @Test public void ConnIoT_CustomAuth_InvalidTokenSignature() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerName != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerUsername != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerPassword != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerToken != null); assumeTrue(mqtt5IoTCoreSigningAuthorizerTokenKeyName != null); AwsIotMqtt5ClientBuilder.MqttConnectCustomAuthConfig customAuthConfig = new AwsIotMqtt5ClientBuilder.MqttConnectCustomAuthConfig(); customAuthConfig.authorizerName = mqtt5IoTCoreSigningAuthorizerName; customAuthConfig.username = mqtt5IoTCoreSigningAuthorizerUsername; customAuthConfig.password = mqtt5IoTCoreSigningAuthorizerPassword.getBytes(); customAuthConfig.tokenValue = mqtt5IoTCoreSigningAuthorizerToken; customAuthConfig.tokenKeyName = mqtt5IoTCoreSigningAuthorizerTokenKeyName; customAuthConfig.tokenSignature = "InvalidTokenSignature"; AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newWebsocketMqttBuilderWithCustomAuth( mqtt5IoTCoreHost, customAuthConfig); LifecycleEvents_Futured lifecycleEvents = new LifecycleEvents_Futured(); builder.withLifeCycleEvents(lifecycleEvents); PublishEvents_Futured publishEvents = new PublishEvents_Futured(); builder.withPublishEvents(publishEvents); Mqtt5Client client = builder.build(); client.start(); assertThrows(Exception.class, () -> lifecycleEvents.connectedFuture.get(120, TimeUnit.SECONDS)); client.close(); builder.close(); } /* MQTT311 builder to MQTT5 builder - simple direct connection */ @Test public void ConnIoT_DirectConnect_MQTT311_to_MQTT5_UC1() { assumeTrue(mqtt5IoTCoreHost != null); assumeTrue(mqtt5IoTCoreCertificatePath != null); assumeTrue(mqtt5IoTCoreKeyPath != null); // Make a simple MQTT311 builder AwsIotMqttConnectionBuilder mqtt311Builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath( mqtt5IoTCoreCertificatePath, mqtt5IoTCoreKeyPath); mqtt311Builder.withEndpoint(mqtt5IoTCoreHost); AwsIotMqtt5ClientBuilder builder = null; // CONVERT try { builder = mqtt311Builder.toAwsIotMqtt5ClientBuilder(); } catch (Exception ex) { fail("Exception occurred making AwsIotMqtt5ClientBuilder from MQTT311 config! Exception: " + ex.getMessage()); } // Close the MQTT311 builder mqtt311Builder.close(); LifecycleEvents_Futured lifecycleEvents = new LifecycleEvents_Futured(); builder.withLifeCycleEvents(lifecycleEvents); PublishEvents_Futured publishEvents = new PublishEvents_Futured(); builder.withPublishEvents(publishEvents); Mqtt5Client client = builder.build(); TestSubPubUnsub(client, lifecycleEvents, publishEvents); client.close(); builder.close(); } }
5,194
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-server/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-server/src/test/java/software/amazon/awssdk/eventstreamrpc/IpcServerTests.java
package software.amazon.awssdk.eventstreamrpc; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.Log; import software.amazon.awssdk.crt.eventstream.ServerConnectionContinuationHandler; import software.amazon.awssdk.crt.io.EventLoopGroup; import software.amazon.awssdk.crt.io.SocketOptions; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; import software.amazon.awssdk.eventstreamrpc.test.TestAuthNZHandlers; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.util.Collection; import java.util.HashSet; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.function.Function; /** * Note: use different ports for different tests */ public class IpcServerTests { private static final Random RANDOM = new Random(); //default instantiation uses time public static int randomPort() { return RANDOM.nextInt(65535-1024) + 1024; } static { Log.initLoggingToFile(Log.LogLevel.Trace, "crt-IpcServerTests.log"); } @Test public void testStartStopIpcServer() throws InterruptedException { final int port = randomPort(); final EventStreamRPCServiceHandler handler = new EventStreamRPCServiceHandler() { @Override protected EventStreamRPCServiceModel getServiceModel() { return new EventStreamRPCServiceModel() { @Override public String getServiceName() { return "TestService"; } /** * Retreives all operations on the service * * @return */ @Override public Collection<String> getAllOperations() { return new HashSet<>(); } @Override protected Optional<Class<? extends EventStreamJsonMessage>> getServiceClassType(String applicationModelType) { return Optional.empty(); } @Override public OperationModelContext getOperationModelContext(String operationName) { return null; } }; } @Override public Function<OperationContinuationHandlerContext, ? extends ServerConnectionContinuationHandler> getOperationHandler(String operationName) { return null; } @Override public boolean hasHandlerForOperation(String operation) { return true; } }; handler.setAuthenticationHandler(TestAuthNZHandlers.getAuthNHandler()); handler.setAuthorizationHandler(TestAuthNZHandlers.getAuthZHandler()); try(final EventLoopGroup elGroup = new EventLoopGroup(1); SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = SocketOptions.SocketDomain.IPv4; socketOptions.type = SocketOptions.SocketType.STREAM; try (final IpcServer ipcServer = new IpcServer(elGroup, socketOptions, null, "127.0.0.1", port, handler)) { ipcServer.runServer(); Socket clientSocket = new Socket(); SocketAddress address = new InetSocketAddress("127.0.0.1", port); clientSocket.connect(address, 3000); //no real assertion to be made here as long as the above connection works... clientSocket.close(); Thread.sleep(1_000); } } catch (IOException e) { throw new RuntimeException(e); } CrtResource.waitForNoResources(); } @Test public void testIpcServerDoubleStartFailure() { final int port = randomPort(); final EventStreamRPCServiceHandler handler = new EventStreamRPCServiceHandler() { @Override protected EventStreamRPCServiceModel getServiceModel() { return new EventStreamRPCServiceModel() { @Override public String getServiceName() { return "TestService"; } @Override public Collection<String> getAllOperations() { return new HashSet<>(); } @Override protected Optional<Class<? extends EventStreamJsonMessage>> getServiceClassType(String applicationModelType) { return Optional.empty(); } @Override public OperationModelContext getOperationModelContext(String operationName) { return null; } }; } @Override public Function<OperationContinuationHandlerContext, ? extends ServerConnectionContinuationHandler> getOperationHandler(String operationName) { return null; } @Override public boolean hasHandlerForOperation(String operation) { return true; } }; handler.setAuthenticationHandler(TestAuthNZHandlers.getAuthNHandler()); handler.setAuthorizationHandler(TestAuthNZHandlers.getAuthZHandler()); try (final EventLoopGroup elGroup = new EventLoopGroup(1); SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = SocketOptions.SocketDomain.IPv4; socketOptions.type = SocketOptions.SocketType.STREAM; try(final IpcServer ipcServer = new IpcServer(elGroup, socketOptions, null, "127.0.0.1", port, handler)) { ipcServer.runServer(); Assertions.assertThrows(IllegalStateException.class, () -> { ipcServer.runServer(); }); } } CrtResource.waitForNoResources(); } @Test public void testIpcServerModelNotSet() { final int port = randomPort(); final EventStreamRPCServiceHandler handler = new EventStreamRPCServiceHandler() { @Override protected EventStreamRPCServiceModel getServiceModel() { return null; } @Override public Function<OperationContinuationHandlerContext, ? extends ServerConnectionContinuationHandler> getOperationHandler(String operationName) { return null; } @Override public boolean hasHandlerForOperation(String operation) { return true; } //what'll trigger the validation failure }; handler.setAuthenticationHandler(TestAuthNZHandlers.getAuthNHandler()); handler.setAuthorizationHandler(TestAuthNZHandlers.getAuthZHandler()); try (final EventLoopGroup elGroup = new EventLoopGroup(1); SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = SocketOptions.SocketDomain.IPv4; socketOptions.type = SocketOptions.SocketType.STREAM; try (final IpcServer ipcServer = new IpcServer(elGroup, socketOptions, null, "127.0.0.1", port, handler)) { Assertions.assertThrows(InvalidServiceConfigurationException.class, () -> { ipcServer.runServer(); }); } } CrtResource.waitForNoResources(); } @Test public void testIpcServerOperationNotSet() { final int port = randomPort(); final Set<String> OPERATION_SET = new HashSet<>(); OPERATION_SET.add("dummyOperationName"); final EventStreamRPCServiceHandler handler = new EventStreamRPCServiceHandler() { @Override protected EventStreamRPCServiceModel getServiceModel() { return new EventStreamRPCServiceModel() { @Override public String getServiceName() { return "TestService"; } @Override public Collection<String> getAllOperations() { return OPERATION_SET; } @Override protected Optional<Class<? extends EventStreamJsonMessage>> getServiceClassType(String applicationModelType) { return Optional.empty(); } @Override public OperationModelContext getOperationModelContext(String operationName) { return null; } }; } @Override public Function<OperationContinuationHandlerContext, ? extends ServerConnectionContinuationHandler> getOperationHandler(String operationName) { return null; } @Override public boolean hasHandlerForOperation(String operation) { return false; } //what'll trigger the validation failure }; handler.setAuthenticationHandler(TestAuthNZHandlers.getAuthNHandler()); handler.setAuthorizationHandler(TestAuthNZHandlers.getAuthZHandler()); try (final EventLoopGroup elGroup = new EventLoopGroup(1); SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = SocketOptions.SocketDomain.IPv4; socketOptions.type = SocketOptions.SocketType.STREAM; try (final IpcServer ipcServer = new IpcServer(elGroup, socketOptions, null, "127.0.0.1", port, handler)) { Assertions.assertThrows(InvalidServiceConfigurationException.class, () -> { ipcServer.runServer(); }); } } CrtResource.waitForNoResources(); } @Test public void testIpcServerAuthNUnset() { final int port = randomPort(); final Set<String> OPERATION_SET = new HashSet<>(); OPERATION_SET.add("dummyOperationName"); final EventStreamRPCServiceHandler handler = new EventStreamRPCServiceHandler() { @Override protected EventStreamRPCServiceModel getServiceModel() { return new EventStreamRPCServiceModel() { @Override public String getServiceName() { return "TestService"; } @Override public Collection<String> getAllOperations() { return new HashSet<>(); } @Override protected Optional<Class<? extends EventStreamJsonMessage>> getServiceClassType(String applicationModelType) { return Optional.empty(); } @Override public OperationModelContext getOperationModelContext(String operationName) { return null; } }; } @Override public Function<OperationContinuationHandlerContext, ? extends ServerConnectionContinuationHandler> getOperationHandler(String operationName) { return null; } @Override public boolean hasHandlerForOperation(String operation) { return true; } }; //missing handler.setAuthenticationHandler(TestAuthNZHandlers.getAuthNHandler()); handler.setAuthorizationHandler(TestAuthNZHandlers.getAuthZHandler()); try (final EventLoopGroup elGroup = new EventLoopGroup(1); SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = SocketOptions.SocketDomain.IPv4; socketOptions.type = SocketOptions.SocketType.STREAM; try (final IpcServer ipcServer = new IpcServer(elGroup, socketOptions, null, "127.0.0.1", port, handler)) { Assertions.assertThrows(InvalidServiceConfigurationException.class, () -> { ipcServer.runServer(); }); } } CrtResource.waitForNoResources(); } @Test public void testIpcServerAuthZUnset() { final int port = randomPort(); final Set<String> OPERATION_SET = new HashSet<>(); OPERATION_SET.add("dummyOperationName"); final EventStreamRPCServiceHandler handler = new EventStreamRPCServiceHandler() { @Override protected EventStreamRPCServiceModel getServiceModel() { return new EventStreamRPCServiceModel() { @Override public String getServiceName() { return "TestService"; } @Override public Collection<String> getAllOperations() { return new HashSet<>(); } @Override protected Optional<Class<? extends EventStreamJsonMessage>> getServiceClassType(String applicationModelType) { return Optional.empty(); } @Override public OperationModelContext getOperationModelContext(String operationName) { return null; } }; } @Override public Function<OperationContinuationHandlerContext, ? extends ServerConnectionContinuationHandler> getOperationHandler(String operationName) { return null; } @Override public boolean hasHandlerForOperation(String operation) { return true; } }; handler.setAuthenticationHandler(TestAuthNZHandlers.getAuthNHandler()); //missing: handler.setAuthorizationHandler(TestAuthNZHandlers.getAuthZHandler()); try (final EventLoopGroup elGroup = new EventLoopGroup(1); SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = SocketOptions.SocketDomain.IPv4; socketOptions.type = SocketOptions.SocketType.STREAM; try (final IpcServer ipcServer = new IpcServer(elGroup, socketOptions, null, "127.0.0.1", port, handler)) { Assertions.assertThrows(InvalidServiceConfigurationException.class, () -> { ipcServer.runServer(); }); } } CrtResource.waitForNoResources(); } }
5,195
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-server/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-server/src/test/java/software/amazon/awssdk/eventstreamrpc/EchoTestServiceTests.java
package software.amazon.awssdk.eventstreamrpc; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awstest.CauseServiceErrorResponseHandler; import software.amazon.awssdk.awstest.CauseStreamServiceToErrorResponseHandler; import software.amazon.awssdk.awstest.EchoMessageResponseHandler; import software.amazon.awssdk.awstest.EchoStreamMessagesResponseHandler; import software.amazon.awssdk.awstest.EchoTestRPC; import software.amazon.awssdk.awstest.EchoTestRPCServiceModel; import software.amazon.awssdk.awstest.model.CauseServiceErrorRequest; import software.amazon.awssdk.awstest.model.EchoMessageRequest; import software.amazon.awssdk.awstest.model.EchoMessageResponse; import software.amazon.awssdk.awstest.model.EchoStreamingMessage; import software.amazon.awssdk.awstest.model.EchoStreamingRequest; import software.amazon.awssdk.awstest.model.FruitEnum; import software.amazon.awssdk.awstest.model.MessageData; import software.amazon.awssdk.awstest.model.Pair; import software.amazon.awssdk.awstest.model.ServiceError; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.Log; import software.amazon.awssdk.eventstreamrpc.echotest.EchoTestServiceRunner; import software.amazon.awssdk.eventstreamrpc.model.EventStreamOperationError; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiConsumer; import java.util.stream.Collectors; public class EchoTestServiceTests { static { Log.initLoggingToFile(Log.LogLevel.Trace, "crt-EchoTestService.log"); } final BiConsumer<EchoTestRPC, MessageData> DO_ECHO_FN = (client, data) -> { final EchoMessageRequest request = new EchoMessageRequest(); request.setMessage(data); final EchoMessageResponseHandler responseHandler = client.echoMessage(request, Optional.empty()); EchoMessageResponse response = null; try { response = responseHandler.getResponse().get(10, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { Assertions.fail(e); } Assertions.assertEquals(request.getMessage(), response.getMessage(), "Data echoed back not equivalent!"); }; @Test public void testInvokeEchoMessage() throws Exception { final CompletableFuture<Void> clientErrorAfter = EchoTestServiceRunner.runLocalEchoTestServer((connection, client) -> { //note the successive calls are actually growing the same original message //rather than replacing any single field set. Instead of using lambdas, we could //use a parameterized test, but this has the benefit of proving successive calls work cleanly final MessageData data = new MessageData(); data.setEnumMessage(FruitEnum.PINEAPPLE); DO_ECHO_FN.accept(client, data); data.setStringMessage("Hello EventStream RPC world"); DO_ECHO_FN.accept(client, data); data.setBooleanMessage(true); DO_ECHO_FN.accept(client, data); data.setBlobMessage(new byte[] {23, 42, -120, -3, 53}); DO_ECHO_FN.accept(client, data); data.setTimeMessage(Instant.ofEpochSecond(1606173648)); DO_ECHO_FN.accept(client, data); }); try { clientErrorAfter.get(1, TimeUnit.SECONDS); } catch (TimeoutException e) { //eat this because it means there was no exception which is good } catch (ExecutionException e) { //throw this because it means the client did have a problem Assertions.fail(e.getCause()); } CrtResource.waitForNoResources(); } @Test //this test takes too long to complete so turn it off by default public void testLongRunningServerOperations() throws Exception { final int numIterations = Integer.parseInt(System.getProperty("numIterations", "10")); final int threadPoolSize = Integer.parseInt(System.getProperty("threadPoolSize", "16")); //max threads, since tasks are IO intense, doesn't need to be large final int parallelTaskMultiplyFactor = Integer.parseInt(System.getProperty("parallelTaskFactor", "10")); //however many tasks to run in parallel final int taskLengthMultiplyFactor = Integer.parseInt(System.getProperty("taskLengthFactor", "10")); //whatever work each task does (very small), do it this many times within a single run with a short sleep in between final long taskRepeatSleepDelayMs = 10; //time to sleep before repeating a tasks' impl final ArrayList<BiConsumer<EventStreamRPCConnection, EchoTestRPC>> tasks = new ArrayList<>(); final ExecutorService service = Executors.newFixedThreadPool(threadPoolSize); tasks.add((connection, client) -> { final MessageData data = new MessageData(); data.setEnumMessage(FruitEnum.PINEAPPLE); DO_ECHO_FN.accept(client, data); data.setStringMessage("Hello EventStream RPC world"); DO_ECHO_FN.accept(client, data); data.setBooleanMessage(true); DO_ECHO_FN.accept(client, data); data.setBlobMessage(new byte[] {23, 42, -120, -3, 53}); DO_ECHO_FN.accept(client, data); data.setTimeMessage(Instant.ofEpochSecond(1606173648)); DO_ECHO_FN.accept(client, data); }); tasks.add((connection, client) -> { final CauseServiceErrorResponseHandler responseHandler = client.causeServiceError(new CauseServiceErrorRequest(), Optional.empty()); futureCausesOperationError(responseHandler.getResponse(), ServiceError.class, "ServiceError"); }); tasks.add((connection, client) -> { final CompletableFuture<Throwable> exceptionReceivedFuture = new CompletableFuture<>(); final CauseStreamServiceToErrorResponseHandler streamErrorResponseHandler = client.causeStreamServiceToError(EchoStreamingRequest.VOID, Optional.of(new StreamResponseHandler<EchoStreamingMessage>() { @Override public void onStreamEvent(EchoStreamingMessage streamEvent) { exceptionReceivedFuture.completeExceptionally(new RuntimeException("Stream event received when expecting error!")); } @Override public boolean onStreamError(Throwable error) { //this is normal, but we are looking for a specific one exceptionReceivedFuture.complete(error); return true; } @Override public void onStreamClosed() { if (!exceptionReceivedFuture.isDone()) { exceptionReceivedFuture.completeExceptionally(new RuntimeException("Stream closed before exception thrown!")); } } })); try { final EchoStreamingMessage msg = new EchoStreamingMessage(); final MessageData data = new MessageData(); data.setStringMessage("basicStringMessage"); msg.setStreamMessage(data); streamErrorResponseHandler.sendStreamEvent(msg); //sends message, exception should be is the response final Throwable t = exceptionReceivedFuture.get(10, TimeUnit.SECONDS); Assertions.assertTrue(t instanceof ServiceError); final ServiceError error = (ServiceError)t; Assertions.assertEquals("ServiceError", error.getErrorCode()); } catch (InterruptedException | ExecutionException | TimeoutException e) { Assertions.fail(e); } }); int count[] = { 0 }; EchoTestServiceRunner.runLocalEchoTestServerClientLoopUnixDomain( CRT.getOSIdentifier().equals("windows") ? "\\\\.\\pipe\\TestP-" + UUID.randomUUID() : "/tmp/ipc.sock", (connection, client) -> { final Collection<Future<?>> taskFutures = new LinkedList<>(); for (int i = 0; i < parallelTaskMultiplyFactor; ++i) { //multiply the tasks evenly taskFutures.addAll(tasks.stream() .map(task -> service.submit(()-> { for (int taskExecIndx = 0; taskExecIndx < taskLengthMultiplyFactor; ++taskExecIndx) { task.accept(connection, client); try { Thread.sleep(taskRepeatSleepDelayMs); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("Task repeat..."); } })) .collect(Collectors.toList())); } taskFutures.forEach(task -> { try { task.get(10, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { Assertions.fail(e); } }); System.out.println("ALL TASKS finished an ITERATION: " + ++count[0]); }, numIterations); CrtResource.waitForNoResources(); } public void futureCausesOperationError(final CompletableFuture<?> future, Class<? extends EventStreamOperationError> clazz, String code) { try { future.get(60, TimeUnit.SECONDS); } catch (ExecutionException e) { final Throwable t = e.getCause(); if (t == null) { Assertions.fail("ExecutionException thrown has no CausedBy exception. Something else went wrong with future completion"); } else if(!clazz.isInstance(t)) { Assertions.fail("ExecutionException thrown has unexpected caused type", t); } else { final EventStreamOperationError error = (EventStreamOperationError)t; Assertions.assertEquals(code, error.getErrorCode(), "Non-matching error code returned"); } } catch (InterruptedException | TimeoutException e) { throw new RuntimeException(e); } } @Test public void testInvokeErrorOperation() throws Exception { final CompletableFuture<Void> clientErrorAfter = EchoTestServiceRunner.runLocalEchoTestServer((connection, client) -> { final CauseServiceErrorResponseHandler responseHandler = client.causeServiceError(new CauseServiceErrorRequest(), Optional.empty()); futureCausesOperationError(responseHandler.getResponse(), ServiceError.class, "ServiceError"); //after an error, perform another operation on the same connection that should still be open for business final MessageData data = new MessageData(); data.setStringMessage("Post error string message"); DO_ECHO_FN.accept(client, data); final CauseServiceErrorResponseHandler responseHandler2 = client.causeServiceError(new CauseServiceErrorRequest(), Optional.empty()); futureCausesOperationError(responseHandler2.getResponse(), ServiceError.class, "ServiceError"); final CauseServiceErrorResponseHandler responseHandler3 = client.causeServiceError(new CauseServiceErrorRequest(), Optional.empty()); futureCausesOperationError(responseHandler3.getResponse(), ServiceError.class, "ServiceError"); //call non error again DO_ECHO_FN.accept(client, data); }); try { clientErrorAfter.get(1, TimeUnit.SECONDS); } catch (TimeoutException e) { //eat this because it means there was no exception which is good } catch (ExecutionException e) { //throw this because it means the client did have a problem Assertions.fail(e.getCause()); } CrtResource.waitForNoResources(); } @Test public void testInvokeEchoStreamMessagesClientClose() throws Exception { final CompletableFuture<Void> clientErrorAfter = EchoTestServiceRunner.runLocalEchoTestServer((connection, client) -> { final EchoStreamingRequest req = EchoStreamingRequest.VOID; final List<EchoStreamingMessage> messagesToSend = new ArrayList<>(); final EchoStreamingMessage msg1 = new EchoStreamingMessage(); final MessageData data1 = new MessageData(); data1.setStringMessage("fooStreamingMessage"); msg1.setStreamMessage(data1); messagesToSend.add(msg1); final EchoStreamingMessage msg2 = new EchoStreamingMessage(); final MessageData data2 = new MessageData(); data2.setEnumMessage(FruitEnum.ORANGE); msg2.setStreamMessage(data2); messagesToSend.add(msg2); final EchoStreamingMessage msg3 = new EchoStreamingMessage(); final MessageData data3 = new MessageData(); data3.setTimeMessage(Instant.ofEpochSecond(1606173648)); msg3.setStreamMessage(data3); messagesToSend.add(msg3); final EchoStreamingMessage msg4 = new EchoStreamingMessage(); final MessageData data4 = new MessageData(); final List<String> listOfStrings = new ArrayList<>(3); listOfStrings.add("item1"); listOfStrings.add("item2"); listOfStrings.add("item3"); data4.setStringListMessage(listOfStrings); msg4.setStreamMessage(data4); messagesToSend.add(msg4); final EchoStreamingMessage msg5 = new EchoStreamingMessage(); final Pair kvPair = new Pair(); kvPair.setKey("keyTest"); kvPair.setValue("testValue"); msg5.setKeyValuePair(kvPair); final CompletableFuture<Void> finishedStreamingEvents = new CompletableFuture<>(); final CompletableFuture<Void> streamClosedFuture = new CompletableFuture<>(); final Iterator<EchoStreamingMessage> sentIterator = messagesToSend.iterator(); final int numEventsVerified[] = new int[] { 0 }; final EchoStreamMessagesResponseHandler responseHandler = client.echoStreamMessages(req, Optional.of(new StreamResponseHandler<EchoStreamingMessage>() { @Override public void onStreamEvent(EchoStreamingMessage streamEvent) { if (sentIterator.hasNext()) { final EchoStreamingMessage expectedMsg = sentIterator.next(); if (!expectedMsg.equals(streamEvent)) { finishedStreamingEvents.completeExceptionally(new RuntimeException("Steam message echo'd is not the same as sent!")); } else { numEventsVerified[0]++; if (numEventsVerified[0] == messagesToSend.size()) { finishedStreamingEvents.complete(null); } } } else { finishedStreamingEvents.completeExceptionally(new RuntimeException("Service returned an extra unexpected message back over stream: " + EchoTestRPCServiceModel.getInstance().toJsonString(streamEvent))); } } @Override public boolean onStreamError(Throwable error) { finishedStreamingEvents.completeExceptionally( new RuntimeException("Service threw an error while waiting for stream events!", error)); streamClosedFuture.completeExceptionally(new RuntimeException("Service threw an error while waiting for stream events!", error)); return true; } @Override public void onStreamClosed() { streamClosedFuture.complete(null); } })); messagesToSend.stream().forEachOrdered(event -> { responseHandler.sendStreamEvent(event); //no need to slow down? }); try { finishedStreamingEvents.get(5, TimeUnit.SECONDS); } catch (ExecutionException | InterruptedException | TimeoutException e) { Assertions.fail(e); } try { responseHandler.closeStream().get(5, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new RuntimeException(e); } //after a streaming operation client closes, perform another operation on the same connection final MessageData data = new MessageData(); data.setEnumMessage(FruitEnum.PINEAPPLE); DO_ECHO_FN.accept(client, data); }); try { clientErrorAfter.get(1, TimeUnit.SECONDS); } catch (TimeoutException e) { //eat this because it means there was no exception which is good } catch (ExecutionException e) { //throw this because it means the client did have a problem Assertions.fail(e.getCause()); } CrtResource.waitForNoResources(); } @Test public void testInvokeEchoStreamMessages() throws Exception { final CompletableFuture<Void> clientErrorAfter = EchoTestServiceRunner.runLocalEchoTestServer((connection, client) -> { final EchoStreamingRequest req = EchoStreamingRequest.VOID; final List<EchoStreamingMessage> messagesToSend = new ArrayList<>(); final EchoStreamingMessage msg1 = new EchoStreamingMessage(); final MessageData data1 = new MessageData(); data1.setStringMessage("fooStreamingMessage"); msg1.setStreamMessage(data1); messagesToSend.add(msg1); final EchoStreamingMessage msg2 = new EchoStreamingMessage(); final MessageData data2 = new MessageData(); data2.setEnumMessage(FruitEnum.ORANGE); msg2.setStreamMessage(data2); messagesToSend.add(msg2); final EchoStreamingMessage msg3 = new EchoStreamingMessage(); final MessageData data3 = new MessageData(); data3.setTimeMessage(Instant.ofEpochSecond(1606173648)); msg3.setStreamMessage(data3); messagesToSend.add(msg3); final EchoStreamingMessage msg4 = new EchoStreamingMessage(); final MessageData data4 = new MessageData(); final List<String> listOfStrings = new ArrayList<>(3); listOfStrings.add("item1"); listOfStrings.add("item2"); listOfStrings.add("item3"); data4.setStringListMessage(listOfStrings); msg4.setStreamMessage(data4); messagesToSend.add(msg4); final EchoStreamingMessage msg5 = new EchoStreamingMessage(); final Pair kvPair = new Pair(); kvPair.setKey("keyTest"); kvPair.setValue("testValue"); msg5.setKeyValuePair(kvPair); final CompletableFuture<Void> finishedStreamingEvents = new CompletableFuture<>(); final CompletableFuture<Void> streamClosedFuture = new CompletableFuture<>(); final Iterator<EchoStreamingMessage> sentIterator = messagesToSend.iterator(); final int numEventsVerified[] = new int[] { 0 }; final EchoStreamMessagesResponseHandler responseHandler = client.echoStreamMessages(req, Optional.of(new StreamResponseHandler<EchoStreamingMessage>() { @Override public void onStreamEvent(EchoStreamingMessage streamEvent) { if (sentIterator.hasNext()) { final EchoStreamingMessage expectedMsg = sentIterator.next(); if (!expectedMsg.equals(streamEvent)) { finishedStreamingEvents.completeExceptionally(new RuntimeException("Steam message echo'd is not the same as sent!")); } else { numEventsVerified[0]++; if (numEventsVerified[0] == messagesToSend.size()) { finishedStreamingEvents.complete(null); } } } else { finishedStreamingEvents.completeExceptionally(new RuntimeException("Service returned an extra unexpected message back over stream: " + EchoTestRPCServiceModel.getInstance().toJsonString(streamEvent))); } } @Override public boolean onStreamError(Throwable error) { finishedStreamingEvents.completeExceptionally( new RuntimeException("Service threw an error while waiting for stream events!", error)); streamClosedFuture.completeExceptionally(new RuntimeException("Service threw an error while waiting for stream events!", error)); return true; } @Override public void onStreamClosed() { streamClosedFuture.complete(null); } })); messagesToSend.stream().forEachOrdered(event -> { responseHandler.sendStreamEvent(event); //no need to slow down? }); try { finishedStreamingEvents.get(5, TimeUnit.SECONDS); } catch (ExecutionException | InterruptedException | TimeoutException e) { Assertions.fail(e); } //after a streaming operation, perform another operation on the same connection final MessageData data = new MessageData(); data.setEnumMessage(FruitEnum.PINEAPPLE); DO_ECHO_FN.accept(client, data); //now command the stream to close final EchoStreamingMessage closeMsg = new EchoStreamingMessage(); final MessageData dataClose = new MessageData(); dataClose.setStringMessage("close"); //implementation of the close operation in test-codegen-model closeMsg.setStreamMessage(dataClose); responseHandler.sendStreamEvent(closeMsg); try { streamClosedFuture.get(5, TimeUnit.SECONDS); } catch (ExecutionException | InterruptedException | TimeoutException e) { Assertions.fail(e); } }); try { clientErrorAfter.get(1, TimeUnit.SECONDS); } catch (TimeoutException e) { //eat this because it means there was no exception which is good } catch (ExecutionException e) { //throw this because it means the client did have a problem Assertions.fail(e.getCause()); } CrtResource.waitForNoResources(); } @Test public void testInvokeEchoStreamError() throws Exception { final CompletableFuture<Void> clientErrorAfter = EchoTestServiceRunner.runLocalEchoTestServer((connection, client) -> { final CompletableFuture<Throwable> exceptionReceivedFuture = new CompletableFuture<>(); final CauseStreamServiceToErrorResponseHandler streamErrorResponseHandler = client.causeStreamServiceToError(EchoStreamingRequest.VOID, Optional.of(new StreamResponseHandler<EchoStreamingMessage>() { @Override public void onStreamEvent(EchoStreamingMessage streamEvent) { exceptionReceivedFuture.completeExceptionally(new RuntimeException("Stream event received when expecting error!")); } @Override public boolean onStreamError(Throwable error) { //this is normal, but we are looking for a specific one exceptionReceivedFuture.complete(error); return true; } @Override public void onStreamClosed() { if (!exceptionReceivedFuture.isDone()) { exceptionReceivedFuture.completeExceptionally(new RuntimeException("Stream closed before exception thrown!")); } } })); try { final EchoStreamingMessage msg = new EchoStreamingMessage(); final MessageData data = new MessageData(); data.setStringMessage("basicStringMessage"); msg.setStreamMessage(data); streamErrorResponseHandler.sendStreamEvent(msg); //sends message, exception should be is the response final Throwable t = exceptionReceivedFuture.get(60, TimeUnit.SECONDS); Assertions.assertTrue(t instanceof ServiceError); final ServiceError error = (ServiceError)t; Assertions.assertEquals("ServiceError", error.getErrorCode()); } catch (InterruptedException | ExecutionException | TimeoutException e) { Assertions.fail(e); } //after a streaming response error, perform another operation on the same //connection that should still be open for business final MessageData data = new MessageData(); data.setStringMessage("Post stream error string message"); DO_ECHO_FN.accept(client, data); }); try { clientErrorAfter.get(1, TimeUnit.SECONDS); } catch (TimeoutException e) { //eat this because it means there was no exception which is good } catch (ExecutionException e) { //throw this because it means the client did have a problem Assertions.fail(e.getCause()); } CrtResource.waitForNoResources(); } }
5,196
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-server/src/test/java/software/amazon/awssdk/eventstreamrpc
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-server/src/test/java/software/amazon/awssdk/eventstreamrpc/echotest/EchoStreamMessagesHandler.java
package software.amazon.awssdk.eventstreamrpc.echotest; import software.amazon.awssdk.awstest.GeneratedAbstractEchoStreamMessagesOperationHandler; import software.amazon.awssdk.awstest.model.EchoStreamingMessage; import software.amazon.awssdk.awstest.model.EchoStreamingRequest; import software.amazon.awssdk.awstest.model.EchoStreamingResponse; import software.amazon.awssdk.awstest.model.MessageData; import software.amazon.awssdk.eventstreamrpc.OperationContinuationHandlerContext; /** * Handler responds to any stream message by sending the data right back. Specialhandling */ public class EchoStreamMessagesHandler extends GeneratedAbstractEchoStreamMessagesOperationHandler { protected EchoStreamMessagesHandler(OperationContinuationHandlerContext context) { super(context); } @Override protected void onStreamClosed() { //do nothing } @Override public EchoStreamingResponse handleRequest(EchoStreamingRequest request) { return EchoStreamingResponse.VOID; } @Override public void handleStreamEvent(EchoStreamingMessage streamRequestEvent) { sendStreamEvent(streamRequestEvent); if (streamRequestEvent.getSetUnionMember().equals(EchoStreamingMessage.UnionMember.STREAM_MESSAGE)) { final MessageData data = streamRequestEvent.getStreamMessage(); if ("close".equalsIgnoreCase(data.getStringMessage())) { //follow with a stream close closeStream(); } } } }
5,197
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-server/src/test/java/software/amazon/awssdk/eventstreamrpc
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-server/src/test/java/software/amazon/awssdk/eventstreamrpc/echotest/GetAllCustomersHandler.java
package software.amazon.awssdk.eventstreamrpc.echotest; import software.amazon.awssdk.awstest.GeneratedAbstractGetAllCustomersOperationHandler; import software.amazon.awssdk.awstest.model.GetAllCustomersRequest; import software.amazon.awssdk.awstest.model.GetAllCustomersResponse; import software.amazon.awssdk.eventstreamrpc.OperationContinuationHandlerContext; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class GetAllCustomersHandler extends GeneratedAbstractGetAllCustomersOperationHandler { protected GetAllCustomersHandler(OperationContinuationHandlerContext context) { super(context); } @Override protected void onStreamClosed() { // do nothing } @Override public GetAllCustomersResponse handleRequest(GetAllCustomersRequest request) { final GetAllCustomersResponse response = new GetAllCustomersResponse(); return response; } @Override public void handleStreamEvent(EventStreamJsonMessage streamRequestEvent) { // maybe unsupported operation? throw new RuntimeException("No stream event should be occurring on this operation"); } }
5,198
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-server/src/test/java/software/amazon/awssdk/eventstreamrpc
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-server/src/test/java/software/amazon/awssdk/eventstreamrpc/echotest/EchoTestServiceRunner.java
package software.amazon.awssdk.eventstreamrpc.echotest; import software.amazon.awssdk.awstest.EchoTestRPC; import software.amazon.awssdk.awstest.EchoTestRPCClient; import software.amazon.awssdk.awstest.EchoTestRPCService; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.io.ClientBootstrap; import software.amazon.awssdk.crt.io.EventLoopGroup; import software.amazon.awssdk.crt.io.HostResolver; import software.amazon.awssdk.crt.io.SocketOptions; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnectionConfig; import software.amazon.awssdk.eventstreamrpc.RpcServer; import software.amazon.awssdk.eventstreamrpc.test.TestAuthNZHandlers; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; /** * Helper to runs the echo server for unit tests, or any other sandbox testing */ public class EchoTestServiceRunner implements AutoCloseable { private static final Random RANDOM = new Random(); //default instantiation uses time public static int randomPort() { return RANDOM.nextInt(65535-1024) + 1024; } private RpcServer rpcServer; private final EventLoopGroup elGroup; private final SocketOptions.SocketDomain domain; private final String hostname; private final int port; public EchoTestServiceRunner(EventLoopGroup elGroup, String hostname, int port) { this(elGroup, SocketOptions.SocketDomain.IPv4, hostname, port); } public EchoTestServiceRunner(EventLoopGroup elGroup, SocketOptions.SocketDomain domain, String hostname, int port) { this.elGroup = elGroup; this.hostname = hostname; this.port = port; this.domain = domain; } public void runService() { try (SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = domain; socketOptions.type = SocketOptions.SocketType.STREAM; final EchoTestRPCService service = new EchoTestRPCService(); //wiring of operation handlers service.setEchoMessageHandler(EchoMessageHandler::new); service.setEchoStreamMessagesHandler(EchoStreamMessagesHandler::new); service.setCauseServiceErrorHandler(CauseServiceErrorHandler::new); service.setCauseStreamServiceToErrorHandler(CauseStreamServiceToError::new); service.setGetAllCustomersHandler(GetAllCustomersHandler::new); service.setGetAllProductsHandler(GetAllProductsHandler::new); service.setAuthenticationHandler(TestAuthNZHandlers.getAuthNHandler()); service.setAuthorizationHandler(TestAuthNZHandlers.getAuthZHandler()); rpcServer = new RpcServer(elGroup, socketOptions, null, hostname, port, service); rpcServer.runServer(); } } @Override public void close() throws Exception { if (rpcServer != null) { rpcServer.close(); } } /** * Executes testClientLogic in a runnable. * * If the connection encountered an error before the clientTestLogic completes this method will throw that error. * * If the client completes normally first, this will complete normally. * * If the client throws an exception first, this method will throw that exception * * Note: Use the returned CompletableFuture to check if any errors are occurring AFTER the testClientLogic runs. This * may be needed/worth checking * * @param testClientLogic return * @return A CompletableFuture of any connection level error that may have occurred after the testClientLogic completes * @throws Exception throws an exception either from the test client logic having thrown, or the connection itself * encountering an error before test client logic completes */ public static CompletableFuture<Void> runLocalEchoTestServer(final BiConsumer<EventStreamRPCConnection, EchoTestRPC> testClientLogic) throws Exception { final int port = randomPort(); final String hostname = "127.0.0.1"; try (final EventLoopGroup elGroup = new EventLoopGroup(1); final EchoTestServiceRunner runner = new EchoTestServiceRunner(elGroup, hostname, port); final HostResolver resolver = new HostResolver(elGroup, 64); final ClientBootstrap clientBootstrap = new ClientBootstrap(elGroup, resolver); final SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = SocketOptions.SocketDomain.IPv4; socketOptions.type = SocketOptions.SocketType.STREAM; runner.runService(); final EventStreamRPCConnectionConfig config = new EventStreamRPCConnectionConfig(clientBootstrap, elGroup, socketOptions, null, hostname, port, () -> TestAuthNZHandlers.getClientAuth("accepted.foo")); try (EventStreamRPCConnection connection = new EventStreamRPCConnection(config)) { final CompletableFuture<Void> connectFuture = new CompletableFuture<>(); final CompletableFuture<Void> clientErrorFuture = new CompletableFuture<>(); //only completes exceptionally if there's an error connection.connect(new EventStreamRPCConnection.LifecycleHandler() { @Override public void onConnect() { connectFuture.complete(null); } @Override public void onDisconnect(int errorCode) { if (!connectFuture.isDone()) { connectFuture.completeExceptionally(new RuntimeException("Client initial connection failed due to: " + CRT.awsErrorName(errorCode))); } else if (errorCode != CRT.AWS_CRT_SUCCESS) { clientErrorFuture.completeExceptionally(new RuntimeException("Client disconnected due to: " + CRT.awsErrorName(errorCode))); } else { } //don't care if it normal closure/disconnect } @Override public boolean onError(Throwable t) { if (!connectFuture.isDone()) { connectFuture.completeExceptionally(t); } else { clientErrorFuture.completeExceptionally(t); } return false; } }); connectFuture.get(480, TimeUnit.SECONDS); //wait for connection to move forward final EchoTestRPC client = new EchoTestRPCClient(connection); final CompletableFuture<Object> runClientOrError = CompletableFuture.anyOf(clientErrorFuture, CompletableFuture.runAsync(() -> testClientLogic.accept(connection, client), Executors.newSingleThreadExecutor())); runClientOrError.get(240, TimeUnit.SECONDS); return clientErrorFuture; } } } /** * Enables a bit of a performance/load test by reconnecting the client to the same running server multiple times * and each time the client connects, it runs the test logic for the number of times. * * !!! WARNING SocketOptions.SocketDomain is LOCAL for this server. Test client must match */ public static void runLocalEchoTestServerClientLoopUnixDomain(final String domainSocket, final BiConsumer<EventStreamRPCConnection, EchoTestRPC> testClientLogic, int nCount) throws Exception { final int port = randomPort(); Files.deleteIfExists(Paths.get(domainSocket)); try (final EventLoopGroup elGroup = new EventLoopGroup(1); final EchoTestServiceRunner runner = new EchoTestServiceRunner(elGroup, SocketOptions.SocketDomain.LOCAL, domainSocket, port); final SocketOptions socketOptions = new SocketOptions(); final HostResolver hostResolver = new HostResolver(elGroup, 64); final ClientBootstrap clientBootstrap = new ClientBootstrap(elGroup, hostResolver)) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = SocketOptions.SocketDomain.LOCAL; socketOptions.type = SocketOptions.SocketType.STREAM; runner.runService(); for (int i = 0; i < nCount; ++i) { final EventStreamRPCConnectionConfig config = new EventStreamRPCConnectionConfig(clientBootstrap, elGroup, socketOptions, null, domainSocket, port, () -> TestAuthNZHandlers.getClientAuth("accepted.foo")); try (EventStreamRPCConnection connection = new EventStreamRPCConnection(config)) { final CompletableFuture<Void> connectFuture = new CompletableFuture<>(); final CompletableFuture<Void> clientErrorFuture = new CompletableFuture<>(); //only completes exceptionally if there's an error connection.connect(new EventStreamRPCConnection.LifecycleHandler() { @Override public void onConnect() { connectFuture.complete(null); } @Override public void onDisconnect(int errorCode) { if (!connectFuture.isDone()) { connectFuture.completeExceptionally(new RuntimeException("Client initial connection failed due to: " + CRT.awsErrorName(errorCode))); } else if (errorCode != CRT.AWS_CRT_SUCCESS) { clientErrorFuture.completeExceptionally(new RuntimeException("Client disconnected due to: " + CRT.awsErrorName(errorCode))); } else { } //don't care if it normal closure/disconnect } @Override public boolean onError(Throwable t) { if (!connectFuture.isDone()) { connectFuture.completeExceptionally(t); } else { clientErrorFuture.completeExceptionally(t); } return false; } }); connectFuture.get(30, TimeUnit.SECONDS); //wait for connection to move forward final EchoTestRPC client = new EchoTestRPCClient(connection); final CompletableFuture<Object> runClientOrError = CompletableFuture.anyOf(clientErrorFuture, CompletableFuture.runAsync( () -> testClientLogic.accept(connection, client), Executors.newSingleThreadExecutor())); runClientOrError.get(240, TimeUnit.SECONDS); } } } //given this method is rather explicitly meant to be used in JUnit tests and intends to check per iteration //calling waitForNoResources() is necessary to call here, and appropriate CrtResource.waitForNoResources(); } /** * Runs this dumb service via CLI * @param args * @throws Exception */ public static void main(String []args) throws Exception { try(final EventLoopGroup elGroup = new EventLoopGroup(1); EchoTestServiceRunner runner = new EchoTestServiceRunner(elGroup, args[0], Integer.parseInt(args[1]))) { runner.runService(); final Semaphore semaphore = new Semaphore(1); semaphore.acquire(); semaphore.acquire(); //wait until control+C } } }
5,199