repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1
value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
playn/playn | core/src/playn/core/json/JsonParser.java | JsonParser.createHelpfulException | private JsonParserException createHelpfulException(char first, char[] expected, int failurePosition)
throws JsonParserException {
// Build the first part of the token
StringBuilder errorToken = new StringBuilder(first
+ (expected == null ? "" : new String(expected, 0, failurePosition)));
// Consume the whole pseudo-token to make a better error message
while (isAsciiLetter(peekChar()) && errorToken.length() < 15)
errorToken.append((char)advanceChar());
return createParseException(null, "Unexpected token '" + errorToken + "'"
+ (expected == null ? "" : ". Did you mean '" + first + new String(expected) + "'?"), true);
} | java | private JsonParserException createHelpfulException(char first, char[] expected, int failurePosition)
throws JsonParserException {
// Build the first part of the token
StringBuilder errorToken = new StringBuilder(first
+ (expected == null ? "" : new String(expected, 0, failurePosition)));
// Consume the whole pseudo-token to make a better error message
while (isAsciiLetter(peekChar()) && errorToken.length() < 15)
errorToken.append((char)advanceChar());
return createParseException(null, "Unexpected token '" + errorToken + "'"
+ (expected == null ? "" : ". Did you mean '" + first + new String(expected) + "'?"), true);
} | [
"private",
"JsonParserException",
"createHelpfulException",
"(",
"char",
"first",
",",
"char",
"[",
"]",
"expected",
",",
"int",
"failurePosition",
")",
"throws",
"JsonParserException",
"{",
"// Build the first part of the token",
"StringBuilder",
"errorToken",
"=",
"new"... | Throws a helpful exception based on the current alphanumeric token. | [
"Throws",
"a",
"helpful",
"exception",
"based",
"on",
"the",
"current",
"alphanumeric",
"token",
"."
] | 7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66 | https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/json/JsonParser.java#L445-L457 | train |
playn/playn | scene/src/playn/scene/Interaction.java | Interaction.capture | public void capture (CaptureMode mode) {
assert dispatchLayer != null;
if (canceled) throw new IllegalStateException("Cannot capture canceled interaction.");
if (capturingLayer != dispatchLayer && captured()) throw new IllegalStateException(
"Interaction already captured by " + capturingLayer);
capturingLayer = dispatchLayer;
captureMode = mode;
notifyCancel(capturingLayer, captureMode, event);
} | java | public void capture (CaptureMode mode) {
assert dispatchLayer != null;
if (canceled) throw new IllegalStateException("Cannot capture canceled interaction.");
if (capturingLayer != dispatchLayer && captured()) throw new IllegalStateException(
"Interaction already captured by " + capturingLayer);
capturingLayer = dispatchLayer;
captureMode = mode;
notifyCancel(capturingLayer, captureMode, event);
} | [
"public",
"void",
"capture",
"(",
"CaptureMode",
"mode",
")",
"{",
"assert",
"dispatchLayer",
"!=",
"null",
";",
"if",
"(",
"canceled",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot capture canceled interaction.\"",
")",
";",
"if",
"(",
"capturingLa... | Captures this interaction in the specified capture mode. Depending on the mode, subsequent
events will go only to the current layer, or that layer and its parents, or that layer and
its children. Other layers in the interaction will receive a cancellation event and nothing
further. | [
"Captures",
"this",
"interaction",
"in",
"the",
"specified",
"capture",
"mode",
".",
"Depending",
"on",
"the",
"mode",
"subsequent",
"events",
"will",
"go",
"only",
"to",
"the",
"current",
"layer",
"or",
"that",
"layer",
"and",
"its",
"parents",
"or",
"that"... | 7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66 | https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/scene/src/playn/scene/Interaction.java#L80-L88 | train |
playn/playn | core/src/playn/core/GLBatch.java | GLBatch.begin | public void begin (float fbufWidth, float fbufHeight, boolean flip) {
if (begun) throw new IllegalStateException(getClass().getSimpleName() + " mismatched begin()");
begun = true;
} | java | public void begin (float fbufWidth, float fbufHeight, boolean flip) {
if (begun) throw new IllegalStateException(getClass().getSimpleName() + " mismatched begin()");
begun = true;
} | [
"public",
"void",
"begin",
"(",
"float",
"fbufWidth",
",",
"float",
"fbufHeight",
",",
"boolean",
"flip",
")",
"{",
"if",
"(",
"begun",
")",
"throw",
"new",
"IllegalStateException",
"(",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
"+",
"\" mismat... | Must be called before this batch is used to accumulate and send drawing commands.
@param flip whether or not to flip the y-axis. This is generally true when rendering to the
default frame buffer (the screen), and false when rendering to textures. | [
"Must",
"be",
"called",
"before",
"this",
"batch",
"is",
"used",
"to",
"accumulate",
"and",
"send",
"drawing",
"commands",
"."
] | 7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66 | https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/GLBatch.java#L32-L35 | train |
playn/playn | robovm/src/playn/robovm/RoboFont.java | RoboFont.registerVariant | public static void registerVariant(String name, Style style, String variantName) {
Map<String,String> styleVariants = _variants.get(style);
if (styleVariants == null) {
_variants.put(style, styleVariants = new HashMap<String,String>());
}
styleVariants.put(name, variantName);
} | java | public static void registerVariant(String name, Style style, String variantName) {
Map<String,String> styleVariants = _variants.get(style);
if (styleVariants == null) {
_variants.put(style, styleVariants = new HashMap<String,String>());
}
styleVariants.put(name, variantName);
} | [
"public",
"static",
"void",
"registerVariant",
"(",
"String",
"name",
",",
"Style",
"style",
",",
"String",
"variantName",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"styleVariants",
"=",
"_variants",
".",
"get",
"(",
"style",
")",
";",
"if",
"(... | Registers a font for use when a bold, italic or bold italic variant is requested. iOS does not
programmatically generate bold, italic and bold italic variants of fonts. Instead it uses the
actual bold, italic or bold italic variant of the font provided by the original designer.
<p> The built-in iOS fonts (Helvetica, Courier) have already had their variants mapped, but if
you add custom fonts to your game, you will need to register variants for the bold, italic or
bold italic versions if you intend to make use of them. </p>
<p> Alternatively, you can simply request a font variant by name (e.g. {@code
graphics().createFont("Arial Bold Italic", Font.Style.PLAIN, 16)}) to use a specific font
variant directly. This variant mapping process exists only to simplify cross-platform
development. </p> | [
"Registers",
"a",
"font",
"for",
"use",
"when",
"a",
"bold",
"italic",
"or",
"bold",
"italic",
"variant",
"is",
"requested",
".",
"iOS",
"does",
"not",
"programmatically",
"generate",
"bold",
"italic",
"and",
"bold",
"italic",
"variants",
"of",
"fonts",
".",... | 7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66 | https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/robovm/src/playn/robovm/RoboFont.java#L41-L47 | train |
playn/playn | html/src/playn/super/java/nio/FloatBuffer.java | FloatBuffer.allocate | public static FloatBuffer allocate (int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException();
}
ByteBuffer bb = ByteBuffer.allocateDirect(capacity * 4);
bb.order(ByteOrder.nativeOrder());
return bb.asFloatBuffer();
} | java | public static FloatBuffer allocate (int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException();
}
ByteBuffer bb = ByteBuffer.allocateDirect(capacity * 4);
bb.order(ByteOrder.nativeOrder());
return bb.asFloatBuffer();
} | [
"public",
"static",
"FloatBuffer",
"allocate",
"(",
"int",
"capacity",
")",
"{",
"if",
"(",
"capacity",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"}",
"ByteBuffer",
"bb",
"=",
"ByteBuffer",
".",
"allocateDirect",
"(",
"... | Creates a float buffer based on a newly allocated float array.
@param capacity the capacity of the new buffer.
@return the created float buffer.
@throws IllegalArgumentException if {@code capacity} is less than zero. | [
"Creates",
"a",
"float",
"buffer",
"based",
"on",
"a",
"newly",
"allocated",
"float",
"array",
"."
] | 7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66 | https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/html/src/playn/super/java/nio/FloatBuffer.java#L50-L57 | train |
playn/playn | html/src/playn/super/java/nio/FloatBuffer.java | FloatBuffer.compareTo | public int compareTo (FloatBuffer otherBuffer) {
int compareRemaining = (remaining() < otherBuffer.remaining()) ?
remaining() : otherBuffer.remaining();
int thisPos = position;
int otherPos = otherBuffer.position;
// BEGIN android-changed
float thisFloat, otherFloat;
while (compareRemaining > 0) {
thisFloat = get(thisPos);
otherFloat = otherBuffer.get(otherPos);
// checks for float and NaN inequality
if ((thisFloat != otherFloat) &&
((thisFloat == thisFloat) || (otherFloat == otherFloat))) {
return thisFloat < otherFloat ? -1 : 1;
}
thisPos++;
otherPos++;
compareRemaining--;
}
// END android-changed
return remaining() - otherBuffer.remaining();
} | java | public int compareTo (FloatBuffer otherBuffer) {
int compareRemaining = (remaining() < otherBuffer.remaining()) ?
remaining() : otherBuffer.remaining();
int thisPos = position;
int otherPos = otherBuffer.position;
// BEGIN android-changed
float thisFloat, otherFloat;
while (compareRemaining > 0) {
thisFloat = get(thisPos);
otherFloat = otherBuffer.get(otherPos);
// checks for float and NaN inequality
if ((thisFloat != otherFloat) &&
((thisFloat == thisFloat) || (otherFloat == otherFloat))) {
return thisFloat < otherFloat ? -1 : 1;
}
thisPos++;
otherPos++;
compareRemaining--;
}
// END android-changed
return remaining() - otherBuffer.remaining();
} | [
"public",
"int",
"compareTo",
"(",
"FloatBuffer",
"otherBuffer",
")",
"{",
"int",
"compareRemaining",
"=",
"(",
"remaining",
"(",
")",
"<",
"otherBuffer",
".",
"remaining",
"(",
")",
")",
"?",
"remaining",
"(",
")",
":",
"otherBuffer",
".",
"remaining",
"(... | Compare the remaining floats of this buffer to another float buffer's remaining floats.
@param otherBuffer another float buffer.
@return a negative value if this is less than {@code otherBuffer}; 0 if this equals to
{@code otherBuffer}; a positive value if this is greater than {@code otherBuffer}.
@exception ClassCastException if {@code otherBuffer} is not a float buffer. | [
"Compare",
"the",
"remaining",
"floats",
"of",
"this",
"buffer",
"to",
"another",
"float",
"buffer",
"s",
"remaining",
"floats",
"."
] | 7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66 | https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/html/src/playn/super/java/nio/FloatBuffer.java#L93-L114 | train |
pinterest/secor | src/main/java/com/pinterest/secor/util/ThriftUtil.java | ThriftUtil.getMessageClass | @SuppressWarnings("rawtypes")
public Class<? extends TBase> getMessageClass(String topic) {
return allTopics ? messageClassForAll : messageClassByTopic.get(topic);
} | java | @SuppressWarnings("rawtypes")
public Class<? extends TBase> getMessageClass(String topic) {
return allTopics ? messageClassForAll : messageClassByTopic.get(topic);
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"public",
"Class",
"<",
"?",
"extends",
"TBase",
">",
"getMessageClass",
"(",
"String",
"topic",
")",
"{",
"return",
"allTopics",
"?",
"messageClassForAll",
":",
"messageClassByTopic",
".",
"get",
"(",
"topic",
... | Returns configured thrift message class for the given Kafka topic
@param topic
Kafka topic
@return thrift message class used by this utility instance, or
<code>null</code> in case valid class couldn't be found in the
configuration. | [
"Returns",
"configured",
"thrift",
"message",
"class",
"for",
"the",
"given",
"Kafka",
"topic"
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/ThriftUtil.java#L120-L123 | train |
pinterest/secor | src/main/java/com/pinterest/secor/uploader/Uploader.java | Uploader.init | public void init(SecorConfig config, OffsetTracker offsetTracker, FileRegistry fileRegistry,
UploadManager uploadManager, MessageReader messageReader, MetricCollector metricCollector,
DeterministicUploadPolicyTracker deterministicUploadPolicyTracker) {
init(config, offsetTracker, fileRegistry, uploadManager, messageReader,
new ZookeeperConnector(config), metricCollector, deterministicUploadPolicyTracker);
} | java | public void init(SecorConfig config, OffsetTracker offsetTracker, FileRegistry fileRegistry,
UploadManager uploadManager, MessageReader messageReader, MetricCollector metricCollector,
DeterministicUploadPolicyTracker deterministicUploadPolicyTracker) {
init(config, offsetTracker, fileRegistry, uploadManager, messageReader,
new ZookeeperConnector(config), metricCollector, deterministicUploadPolicyTracker);
} | [
"public",
"void",
"init",
"(",
"SecorConfig",
"config",
",",
"OffsetTracker",
"offsetTracker",
",",
"FileRegistry",
"fileRegistry",
",",
"UploadManager",
"uploadManager",
",",
"MessageReader",
"messageReader",
",",
"MetricCollector",
"metricCollector",
",",
"Deterministic... | Init the Uploader with its dependent objects.
@param config Secor configuration
@param offsetTracker Tracker of the current offset of topics partitions
@param fileRegistry Registry of log files on a per-topic and per-partition basis
@param uploadManager Manager of the physical upload of log files to the remote repository
@param metricCollector component that ingest metrics into monitoring system | [
"Init",
"the",
"Uploader",
"with",
"its",
"dependent",
"objects",
"."
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/uploader/Uploader.java#L79-L84 | train |
pinterest/secor | src/main/java/com/pinterest/secor/uploader/Uploader.java | Uploader.init | public void init(SecorConfig config, OffsetTracker offsetTracker, FileRegistry fileRegistry,
UploadManager uploadManager, MessageReader messageReader,
ZookeeperConnector zookeeperConnector, MetricCollector metricCollector,
DeterministicUploadPolicyTracker deterministicUploadPolicyTracker) {
mConfig = config;
mOffsetTracker = offsetTracker;
mFileRegistry = fileRegistry;
mUploadManager = uploadManager;
mMessageReader = messageReader;
mZookeeperConnector = zookeeperConnector;
mTopicFilter = mConfig.getKafkaTopicUploadAtMinuteMarkFilter();
mMetricCollector = metricCollector;
mDeterministicUploadPolicyTracker = deterministicUploadPolicyTracker;
if (mConfig.getOffsetsStorage().equals(SecorConstants.KAFKA_OFFSETS_STORAGE_KAFKA)) {
isOffsetsStorageKafka = true;
}
} | java | public void init(SecorConfig config, OffsetTracker offsetTracker, FileRegistry fileRegistry,
UploadManager uploadManager, MessageReader messageReader,
ZookeeperConnector zookeeperConnector, MetricCollector metricCollector,
DeterministicUploadPolicyTracker deterministicUploadPolicyTracker) {
mConfig = config;
mOffsetTracker = offsetTracker;
mFileRegistry = fileRegistry;
mUploadManager = uploadManager;
mMessageReader = messageReader;
mZookeeperConnector = zookeeperConnector;
mTopicFilter = mConfig.getKafkaTopicUploadAtMinuteMarkFilter();
mMetricCollector = metricCollector;
mDeterministicUploadPolicyTracker = deterministicUploadPolicyTracker;
if (mConfig.getOffsetsStorage().equals(SecorConstants.KAFKA_OFFSETS_STORAGE_KAFKA)) {
isOffsetsStorageKafka = true;
}
} | [
"public",
"void",
"init",
"(",
"SecorConfig",
"config",
",",
"OffsetTracker",
"offsetTracker",
",",
"FileRegistry",
"fileRegistry",
",",
"UploadManager",
"uploadManager",
",",
"MessageReader",
"messageReader",
",",
"ZookeeperConnector",
"zookeeperConnector",
",",
"MetricC... | For testing use only. | [
"For",
"testing",
"use",
"only",
"."
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/uploader/Uploader.java#L87-L103 | train |
pinterest/secor | src/main/java/com/pinterest/secor/uploader/Uploader.java | Uploader.createReader | protected FileReader createReader(LogFilePath srcPath, CompressionCodec codec) throws Exception {
return ReflectionUtil.createFileReader(
mConfig.getFileReaderWriterFactory(),
srcPath,
codec,
mConfig
);
} | java | protected FileReader createReader(LogFilePath srcPath, CompressionCodec codec) throws Exception {
return ReflectionUtil.createFileReader(
mConfig.getFileReaderWriterFactory(),
srcPath,
codec,
mConfig
);
} | [
"protected",
"FileReader",
"createReader",
"(",
"LogFilePath",
"srcPath",
",",
"CompressionCodec",
"codec",
")",
"throws",
"Exception",
"{",
"return",
"ReflectionUtil",
".",
"createFileReader",
"(",
"mConfig",
".",
"getFileReaderWriterFactory",
"(",
")",
",",
"srcPath... | This method is intended to be overwritten in tests.
@param srcPath source Path
@param codec compression codec
@return FileReader created file reader
@throws Exception on error | [
"This",
"method",
"is",
"intended",
"to",
"be",
"overwritten",
"in",
"tests",
"."
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/uploader/Uploader.java#L162-L169 | train |
pinterest/secor | src/main/java/com/pinterest/secor/uploader/Uploader.java | Uploader.applyPolicy | public void applyPolicy(boolean forceUpload) throws Exception {
Collection<TopicPartition> topicPartitions = mFileRegistry.getTopicPartitions();
for (TopicPartition topicPartition : topicPartitions) {
checkTopicPartition(topicPartition, forceUpload);
}
} | java | public void applyPolicy(boolean forceUpload) throws Exception {
Collection<TopicPartition> topicPartitions = mFileRegistry.getTopicPartitions();
for (TopicPartition topicPartition : topicPartitions) {
checkTopicPartition(topicPartition, forceUpload);
}
} | [
"public",
"void",
"applyPolicy",
"(",
"boolean",
"forceUpload",
")",
"throws",
"Exception",
"{",
"Collection",
"<",
"TopicPartition",
">",
"topicPartitions",
"=",
"mFileRegistry",
".",
"getTopicPartitions",
"(",
")",
";",
"for",
"(",
"TopicPartition",
"topicPartitio... | Apply the Uploader policy for pushing partition files to the underlying storage.
For each of the partitions of the file registry, apply the policy for flushing
them to the underlying storage.
This method could be subclassed to provide an alternate policy. The custom uploader
class name would need to be specified in the secor.upload.class.
@throws Exception if any error occurs while appying the policy | [
"Apply",
"the",
"Uploader",
"policy",
"for",
"pushing",
"partition",
"files",
"to",
"the",
"underlying",
"storage",
"."
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/uploader/Uploader.java#L317-L322 | train |
pinterest/secor | src/main/java/com/pinterest/secor/io/impl/JsonORCFileReaderWriterFactory.java | JsonORCFileReaderWriterFactory.resolveCompression | private CompressionKind resolveCompression(CompressionCodec codec) {
if (codec instanceof Lz4Codec)
return CompressionKind.LZ4;
else if (codec instanceof SnappyCodec)
return CompressionKind.SNAPPY;
// although GZip and ZLIB are not same thing
// there is no better named codec for this case,
// use hadoop Gzip codec to enable ORC ZLIB compression
else if (codec instanceof GzipCodec)
return CompressionKind.ZLIB;
else
return CompressionKind.NONE;
} | java | private CompressionKind resolveCompression(CompressionCodec codec) {
if (codec instanceof Lz4Codec)
return CompressionKind.LZ4;
else if (codec instanceof SnappyCodec)
return CompressionKind.SNAPPY;
// although GZip and ZLIB are not same thing
// there is no better named codec for this case,
// use hadoop Gzip codec to enable ORC ZLIB compression
else if (codec instanceof GzipCodec)
return CompressionKind.ZLIB;
else
return CompressionKind.NONE;
} | [
"private",
"CompressionKind",
"resolveCompression",
"(",
"CompressionCodec",
"codec",
")",
"{",
"if",
"(",
"codec",
"instanceof",
"Lz4Codec",
")",
"return",
"CompressionKind",
".",
"LZ4",
";",
"else",
"if",
"(",
"codec",
"instanceof",
"SnappyCodec",
")",
"return",... | Used for returning the compression kind used in ORC
@param codec
@return | [
"Used",
"for",
"returning",
"the",
"compression",
"kind",
"used",
"in",
"ORC"
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/io/impl/JsonORCFileReaderWriterFactory.java#L197-L209 | train |
pinterest/secor | src/main/java/com/pinterest/secor/tools/LogFileVerifier.java | LogFileVerifier.createFileReader | private FileReader createFileReader(LogFilePath logFilePath) throws Exception {
CompressionCodec codec = null;
if (mConfig.getCompressionCodec() != null && !mConfig.getCompressionCodec().isEmpty()) {
codec = CompressionUtil.createCompressionCodec(mConfig.getCompressionCodec());
}
FileReader fileReader = ReflectionUtil.createFileReader(
mConfig.getFileReaderWriterFactory(),
logFilePath,
codec,
mConfig
);
return fileReader;
} | java | private FileReader createFileReader(LogFilePath logFilePath) throws Exception {
CompressionCodec codec = null;
if (mConfig.getCompressionCodec() != null && !mConfig.getCompressionCodec().isEmpty()) {
codec = CompressionUtil.createCompressionCodec(mConfig.getCompressionCodec());
}
FileReader fileReader = ReflectionUtil.createFileReader(
mConfig.getFileReaderWriterFactory(),
logFilePath,
codec,
mConfig
);
return fileReader;
} | [
"private",
"FileReader",
"createFileReader",
"(",
"LogFilePath",
"logFilePath",
")",
"throws",
"Exception",
"{",
"CompressionCodec",
"codec",
"=",
"null",
";",
"if",
"(",
"mConfig",
".",
"getCompressionCodec",
"(",
")",
"!=",
"null",
"&&",
"!",
"mConfig",
".",
... | Helper to create a file reader writer from config
@param logFilePath
@return
@throws Exception | [
"Helper",
"to",
"create",
"a",
"file",
"reader",
"writer",
"from",
"config"
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/tools/LogFileVerifier.java#L203-L215 | train |
pinterest/secor | src/main/java/com/pinterest/secor/util/ProtobufUtil.java | ProtobufUtil.getMessageClass | public Class<? extends Message> getMessageClass(String topic) {
return allTopics ? messageClassForAll : messageClassByTopic.get(topic);
} | java | public Class<? extends Message> getMessageClass(String topic) {
return allTopics ? messageClassForAll : messageClassByTopic.get(topic);
} | [
"public",
"Class",
"<",
"?",
"extends",
"Message",
">",
"getMessageClass",
"(",
"String",
"topic",
")",
"{",
"return",
"allTopics",
"?",
"messageClassForAll",
":",
"messageClassByTopic",
".",
"get",
"(",
"topic",
")",
";",
"}"
] | Returns configured protobuf message class for the given Kafka topic
@param topic
Kafka topic
@return protobuf message class used by this utility instance, or
<code>null</code> in case valid class couldn't be found in the
configuration. | [
"Returns",
"configured",
"protobuf",
"message",
"class",
"for",
"the",
"given",
"Kafka",
"topic"
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/ProtobufUtil.java#L139-L141 | train |
pinterest/secor | src/main/java/com/pinterest/secor/util/ProtobufUtil.java | ProtobufUtil.decodeProtobufMessage | public Message decodeProtobufMessage(String topic, byte[] payload){
Method parseMethod = allTopics ? messageParseMethodForAll : messageParseMethodByTopic.get(topic);
try {
return (Message) parseMethod.invoke(null, payload);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't parse protobuf message, since parseMethod() is not callable. "
+ "Please check your protobuf version (this code works with protobuf >= 2.6.1)", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Can't parse protobuf message, since parseMethod() is not accessible. "
+ "Please check your protobuf version (this code works with protobuf >= 2.6.1)", e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Error parsing protobuf message", e);
}
} | java | public Message decodeProtobufMessage(String topic, byte[] payload){
Method parseMethod = allTopics ? messageParseMethodForAll : messageParseMethodByTopic.get(topic);
try {
return (Message) parseMethod.invoke(null, payload);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't parse protobuf message, since parseMethod() is not callable. "
+ "Please check your protobuf version (this code works with protobuf >= 2.6.1)", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Can't parse protobuf message, since parseMethod() is not accessible. "
+ "Please check your protobuf version (this code works with protobuf >= 2.6.1)", e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Error parsing protobuf message", e);
}
} | [
"public",
"Message",
"decodeProtobufMessage",
"(",
"String",
"topic",
",",
"byte",
"[",
"]",
"payload",
")",
"{",
"Method",
"parseMethod",
"=",
"allTopics",
"?",
"messageParseMethodForAll",
":",
"messageParseMethodByTopic",
".",
"get",
"(",
"topic",
")",
";",
"t... | Decodes protobuf message
@param topic
Kafka topic name
@param payload
Byte array containing encoded protobuf
@return protobuf message instance
@throws RuntimeException
when there's problem decoding protobuf | [
"Decodes",
"protobuf",
"message"
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/ProtobufUtil.java#L181-L194 | train |
pinterest/secor | src/main/java/com/pinterest/secor/util/ProtobufUtil.java | ProtobufUtil.decodeProtobufOrJsonMessage | public Message decodeProtobufOrJsonMessage(String topic, byte[] payload) {
try {
if (shouldDecodeFromJsonMessage(topic)) {
return decodeJsonMessage(topic, payload);
}
} catch (InvalidProtocolBufferException e) {
//When trimming files, the Uploader will read and then decode messages in protobuf format
LOG.debug("Unable to translate JSON string {} to protobuf message", new String(payload, Charsets.UTF_8));
}
return decodeProtobufMessage(topic, payload);
} | java | public Message decodeProtobufOrJsonMessage(String topic, byte[] payload) {
try {
if (shouldDecodeFromJsonMessage(topic)) {
return decodeJsonMessage(topic, payload);
}
} catch (InvalidProtocolBufferException e) {
//When trimming files, the Uploader will read and then decode messages in protobuf format
LOG.debug("Unable to translate JSON string {} to protobuf message", new String(payload, Charsets.UTF_8));
}
return decodeProtobufMessage(topic, payload);
} | [
"public",
"Message",
"decodeProtobufOrJsonMessage",
"(",
"String",
"topic",
",",
"byte",
"[",
"]",
"payload",
")",
"{",
"try",
"{",
"if",
"(",
"shouldDecodeFromJsonMessage",
"(",
"topic",
")",
")",
"{",
"return",
"decodeJsonMessage",
"(",
"topic",
",",
"payloa... | Decodes protobuf message
If the secor.topic.message.format property is set to "JSON" for "topic" assume "payload" is JSON
@param topic
Kafka topic name
@param payload
Byte array containing encoded protobuf or JSON message
@return protobuf message instance
@throws RuntimeException
when there's problem decoding protobuf or JSON message | [
"Decodes",
"protobuf",
"message",
"If",
"the",
"secor",
".",
"topic",
".",
"message",
".",
"format",
"property",
"is",
"set",
"to",
"JSON",
"for",
"topic",
"assume",
"payload",
"is",
"JSON"
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/ProtobufUtil.java#L208-L218 | train |
pinterest/secor | src/main/java/com/pinterest/secor/util/ReflectionUtil.java | ReflectionUtil.createUploadManager | public static UploadManager createUploadManager(String className,
SecorConfig config) throws Exception {
Class<?> clazz = Class.forName(className);
if (!UploadManager.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.",
className, UploadManager.class.getName()));
}
// Assume that subclass of UploadManager has a constructor with the same signature as UploadManager
return (UploadManager) clazz.getConstructor(SecorConfig.class).newInstance(config);
} | java | public static UploadManager createUploadManager(String className,
SecorConfig config) throws Exception {
Class<?> clazz = Class.forName(className);
if (!UploadManager.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.",
className, UploadManager.class.getName()));
}
// Assume that subclass of UploadManager has a constructor with the same signature as UploadManager
return (UploadManager) clazz.getConstructor(SecorConfig.class).newInstance(config);
} | [
"public",
"static",
"UploadManager",
"createUploadManager",
"(",
"String",
"className",
",",
"SecorConfig",
"config",
")",
"throws",
"Exception",
"{",
"Class",
"<",
"?",
">",
"clazz",
"=",
"Class",
".",
"forName",
"(",
"className",
")",
";",
"if",
"(",
"!",
... | Create an UploadManager from its fully qualified class name.
The class passed in by name must be assignable to UploadManager
and have 1-parameter constructor accepting a SecorConfig.
See the secor.upload.manager.class config option.
@param className The class name of a subclass of UploadManager
@param config The SecorCondig to initialize the UploadManager with
@return an UploadManager instance with the runtime type of the class passed by name
@throws Exception on error | [
"Create",
"an",
"UploadManager",
"from",
"its",
"fully",
"qualified",
"class",
"name",
"."
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/ReflectionUtil.java#L56-L66 | train |
pinterest/secor | src/main/java/com/pinterest/secor/util/ReflectionUtil.java | ReflectionUtil.createUploader | public static Uploader createUploader(String className) throws Exception {
Class<?> clazz = Class.forName(className);
if (!Uploader.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.",
className, Uploader.class.getName()));
}
return (Uploader) clazz.newInstance();
} | java | public static Uploader createUploader(String className) throws Exception {
Class<?> clazz = Class.forName(className);
if (!Uploader.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.",
className, Uploader.class.getName()));
}
return (Uploader) clazz.newInstance();
} | [
"public",
"static",
"Uploader",
"createUploader",
"(",
"String",
"className",
")",
"throws",
"Exception",
"{",
"Class",
"<",
"?",
">",
"clazz",
"=",
"Class",
".",
"forName",
"(",
"className",
")",
";",
"if",
"(",
"!",
"Uploader",
".",
"class",
".",
"isAs... | Create an Uploader from its fully qualified class name.
The class passed in by name must be assignable to Uploader.
See the secor.upload.class config option.
@param className The class name of a subclass of Uploader
@return an UploadManager instance with the runtime type of the class passed by name
@throws Exception on error | [
"Create",
"an",
"Uploader",
"from",
"its",
"fully",
"qualified",
"class",
"name",
"."
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/ReflectionUtil.java#L78-L86 | train |
pinterest/secor | src/main/java/com/pinterest/secor/util/ReflectionUtil.java | ReflectionUtil.createMessageParser | public static MessageParser createMessageParser(String className,
SecorConfig config) throws Exception {
Class<?> clazz = Class.forName(className);
if (!MessageParser.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.",
className, MessageParser.class.getName()));
}
// Assume that subclass of MessageParser has a constructor with the same signature as MessageParser
return (MessageParser) clazz.getConstructor(SecorConfig.class).newInstance(config);
} | java | public static MessageParser createMessageParser(String className,
SecorConfig config) throws Exception {
Class<?> clazz = Class.forName(className);
if (!MessageParser.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.",
className, MessageParser.class.getName()));
}
// Assume that subclass of MessageParser has a constructor with the same signature as MessageParser
return (MessageParser) clazz.getConstructor(SecorConfig.class).newInstance(config);
} | [
"public",
"static",
"MessageParser",
"createMessageParser",
"(",
"String",
"className",
",",
"SecorConfig",
"config",
")",
"throws",
"Exception",
"{",
"Class",
"<",
"?",
">",
"clazz",
"=",
"Class",
".",
"forName",
"(",
"className",
")",
";",
"if",
"(",
"!",
... | Create a MessageParser from it's fully qualified class name.
The class passed in by name must be assignable to MessageParser and have 1-parameter constructor accepting a SecorConfig.
Allows the MessageParser to be pluggable by providing the class name of a desired MessageParser in config.
See the secor.message.parser.class config option.
@param className The class name of a subclass of MessageParser
@param config The SecorCondig to initialize the MessageParser with
@return a MessageParser instance with the runtime type of the class passed by name
@throws Exception on error | [
"Create",
"a",
"MessageParser",
"from",
"it",
"s",
"fully",
"qualified",
"class",
"name",
".",
"The",
"class",
"passed",
"in",
"by",
"name",
"must",
"be",
"assignable",
"to",
"MessageParser",
"and",
"have",
"1",
"-",
"parameter",
"constructor",
"accepting",
... | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/ReflectionUtil.java#L100-L110 | train |
pinterest/secor | src/main/java/com/pinterest/secor/util/ReflectionUtil.java | ReflectionUtil.createFileReaderWriterFactory | private static FileReaderWriterFactory createFileReaderWriterFactory(String className,
SecorConfig config) throws Exception {
Class<?> clazz = Class.forName(className);
if (!FileReaderWriterFactory.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.",
className, FileReaderWriterFactory.class.getName()));
}
try {
// Try to load constructor that accepts single parameter - secor
// configuration instance
return (FileReaderWriterFactory) clazz.getConstructor(SecorConfig.class).newInstance(config);
} catch (NoSuchMethodException e) {
// Fallback to parameterless constructor
return (FileReaderWriterFactory) clazz.newInstance();
}
} | java | private static FileReaderWriterFactory createFileReaderWriterFactory(String className,
SecorConfig config) throws Exception {
Class<?> clazz = Class.forName(className);
if (!FileReaderWriterFactory.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.",
className, FileReaderWriterFactory.class.getName()));
}
try {
// Try to load constructor that accepts single parameter - secor
// configuration instance
return (FileReaderWriterFactory) clazz.getConstructor(SecorConfig.class).newInstance(config);
} catch (NoSuchMethodException e) {
// Fallback to parameterless constructor
return (FileReaderWriterFactory) clazz.newInstance();
}
} | [
"private",
"static",
"FileReaderWriterFactory",
"createFileReaderWriterFactory",
"(",
"String",
"className",
",",
"SecorConfig",
"config",
")",
"throws",
"Exception",
"{",
"Class",
"<",
"?",
">",
"clazz",
"=",
"Class",
".",
"forName",
"(",
"className",
")",
";",
... | Create a FileReaderWriterFactory that is able to read and write a specific type of output log file.
The class passed in by name must be assignable to FileReaderWriterFactory.
Allows for pluggable FileReader and FileWriter instances to be constructed for a particular type of log file.
See the secor.file.reader.writer.factory config option.
@param className the class name of a subclass of FileReaderWriterFactory
@param config The SecorCondig to initialize the FileReaderWriterFactory with
@return a FileReaderWriterFactory with the runtime type of the class passed by name
@throws Exception | [
"Create",
"a",
"FileReaderWriterFactory",
"that",
"is",
"able",
"to",
"read",
"and",
"write",
"a",
"specific",
"type",
"of",
"output",
"log",
"file",
".",
"The",
"class",
"passed",
"in",
"by",
"name",
"must",
"be",
"assignable",
"to",
"FileReaderWriterFactory"... | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/ReflectionUtil.java#L124-L140 | train |
pinterest/secor | src/main/java/com/pinterest/secor/util/ReflectionUtil.java | ReflectionUtil.createFileWriter | public static FileWriter createFileWriter(String className, LogFilePath logFilePath,
CompressionCodec codec,
SecorConfig config)
throws Exception {
return createFileReaderWriterFactory(className, config).BuildFileWriter(logFilePath, codec);
} | java | public static FileWriter createFileWriter(String className, LogFilePath logFilePath,
CompressionCodec codec,
SecorConfig config)
throws Exception {
return createFileReaderWriterFactory(className, config).BuildFileWriter(logFilePath, codec);
} | [
"public",
"static",
"FileWriter",
"createFileWriter",
"(",
"String",
"className",
",",
"LogFilePath",
"logFilePath",
",",
"CompressionCodec",
"codec",
",",
"SecorConfig",
"config",
")",
"throws",
"Exception",
"{",
"return",
"createFileReaderWriterFactory",
"(",
"classNa... | Use the FileReaderWriterFactory specified by className to build a FileWriter
@param className the class name of a subclass of FileReaderWriterFactory to create a FileWriter from
@param logFilePath the LogFilePath that the returned FileWriter should write to
@param codec an instance CompressionCodec to compress the file written with, or null for no compression
@param config The SecorCondig to initialize the FileWriter with
@return a FileWriter specialised to write the type of files supported by the FileReaderWriterFactory
@throws Exception on error | [
"Use",
"the",
"FileReaderWriterFactory",
"specified",
"by",
"className",
"to",
"build",
"a",
"FileWriter"
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/ReflectionUtil.java#L152-L157 | train |
pinterest/secor | src/main/java/com/pinterest/secor/util/ReflectionUtil.java | ReflectionUtil.createFileReader | public static FileReader createFileReader(String className, LogFilePath logFilePath,
CompressionCodec codec,
SecorConfig config)
throws Exception {
return createFileReaderWriterFactory(className, config).BuildFileReader(logFilePath, codec);
} | java | public static FileReader createFileReader(String className, LogFilePath logFilePath,
CompressionCodec codec,
SecorConfig config)
throws Exception {
return createFileReaderWriterFactory(className, config).BuildFileReader(logFilePath, codec);
} | [
"public",
"static",
"FileReader",
"createFileReader",
"(",
"String",
"className",
",",
"LogFilePath",
"logFilePath",
",",
"CompressionCodec",
"codec",
",",
"SecorConfig",
"config",
")",
"throws",
"Exception",
"{",
"return",
"createFileReaderWriterFactory",
"(",
"classNa... | Use the FileReaderWriterFactory specified by className to build a FileReader
@param className the class name of a subclass of FileReaderWriterFactory to create a FileReader from
@param logFilePath the LogFilePath that the returned FileReader should read from
@param codec an instance CompressionCodec to decompress the file being read, or null for no compression
@param config The SecorCondig to initialize the FileReader with
@return a FileReader specialised to read the type of files supported by the FileReaderWriterFactory
@throws Exception on error | [
"Use",
"the",
"FileReaderWriterFactory",
"specified",
"by",
"className",
"to",
"build",
"a",
"FileReader"
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/ReflectionUtil.java#L169-L174 | train |
pinterest/secor | src/main/java/com/pinterest/secor/util/ReflectionUtil.java | ReflectionUtil.createMessageTransformer | public static MessageTransformer createMessageTransformer(
String className, SecorConfig config) throws Exception {
Class<?> clazz = Class.forName(className);
if (!MessageTransformer.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(String.format(
"The class '%s' is not assignable to '%s'.", className,
MessageTransformer.class.getName()));
}
return (MessageTransformer) clazz.getConstructor(SecorConfig.class)
.newInstance(config);
} | java | public static MessageTransformer createMessageTransformer(
String className, SecorConfig config) throws Exception {
Class<?> clazz = Class.forName(className);
if (!MessageTransformer.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(String.format(
"The class '%s' is not assignable to '%s'.", className,
MessageTransformer.class.getName()));
}
return (MessageTransformer) clazz.getConstructor(SecorConfig.class)
.newInstance(config);
} | [
"public",
"static",
"MessageTransformer",
"createMessageTransformer",
"(",
"String",
"className",
",",
"SecorConfig",
"config",
")",
"throws",
"Exception",
"{",
"Class",
"<",
"?",
">",
"clazz",
"=",
"Class",
".",
"forName",
"(",
"className",
")",
";",
"if",
"(... | Create a MessageTransformer from it's fully qualified class name. The
class passed in by name must be assignable to MessageTransformers and have
1-parameter constructor accepting a SecorConfig. Allows the MessageTransformers
to be pluggable by providing the class name of a desired MessageTransformers in
config.
See the secor.message.transformer.class config option.
@param className class name
@param config secor config
@return MessageTransformer
@throws Exception on error | [
"Create",
"a",
"MessageTransformer",
"from",
"it",
"s",
"fully",
"qualified",
"class",
"name",
".",
"The",
"class",
"passed",
"in",
"by",
"name",
"must",
"be",
"assignable",
"to",
"MessageTransformers",
"and",
"have",
"1",
"-",
"parameter",
"constructor",
"acc... | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/ReflectionUtil.java#L190-L200 | train |
pinterest/secor | src/main/java/com/pinterest/secor/util/ReflectionUtil.java | ReflectionUtil.createORCSchemaProvider | public static ORCSchemaProvider createORCSchemaProvider(
String className, SecorConfig config) throws Exception {
Class<?> clazz = Class.forName(className);
if (!ORCSchemaProvider.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(String.format(
"The class '%s' is not assignable to '%s'.", className,
ORCSchemaProvider.class.getName()));
}
return (ORCSchemaProvider) clazz.getConstructor(SecorConfig.class)
.newInstance(config);
} | java | public static ORCSchemaProvider createORCSchemaProvider(
String className, SecorConfig config) throws Exception {
Class<?> clazz = Class.forName(className);
if (!ORCSchemaProvider.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(String.format(
"The class '%s' is not assignable to '%s'.", className,
ORCSchemaProvider.class.getName()));
}
return (ORCSchemaProvider) clazz.getConstructor(SecorConfig.class)
.newInstance(config);
} | [
"public",
"static",
"ORCSchemaProvider",
"createORCSchemaProvider",
"(",
"String",
"className",
",",
"SecorConfig",
"config",
")",
"throws",
"Exception",
"{",
"Class",
"<",
"?",
">",
"clazz",
"=",
"Class",
".",
"forName",
"(",
"className",
")",
";",
"if",
"(",... | Create a ORCSchemaProvider from it's fully qualified class name. The
class passed in by name must be assignable to ORCSchemaProvider and have
1-parameter constructor accepting a SecorConfig. Allows the ORCSchemaProvider
to be pluggable by providing the class name of a desired ORCSchemaProvider in
config.
See the secor.orc.schema.provider config option.
@param className class name
@param config secor config
@return ORCSchemaProvider
@throws Exception on error | [
"Create",
"a",
"ORCSchemaProvider",
"from",
"it",
"s",
"fully",
"qualified",
"class",
"name",
".",
"The",
"class",
"passed",
"in",
"by",
"name",
"must",
"be",
"assignable",
"to",
"ORCSchemaProvider",
"and",
"have",
"1",
"-",
"parameter",
"constructor",
"accept... | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/ReflectionUtil.java#L243-L253 | train |
pinterest/secor | src/main/java/com/pinterest/secor/util/FileUtil.java | FileUtil.getMd5Hash | public static String getMd5Hash(String topic, String[] partitions) {
ArrayList<String> elements = new ArrayList<String>();
elements.add(topic);
for (String partition : partitions) {
elements.add(partition);
}
String pathPrefix = StringUtils.join(elements, "/");
try {
final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
byte[] md5Bytes = messageDigest.digest(pathPrefix.getBytes("UTF-8"));
return getHexEncode(md5Bytes).substring(0, 4);
} catch (NoSuchAlgorithmException e) {
LOG.error(e.getMessage());
} catch (UnsupportedEncodingException e) {
LOG.error(e.getMessage());
}
return "";
} | java | public static String getMd5Hash(String topic, String[] partitions) {
ArrayList<String> elements = new ArrayList<String>();
elements.add(topic);
for (String partition : partitions) {
elements.add(partition);
}
String pathPrefix = StringUtils.join(elements, "/");
try {
final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
byte[] md5Bytes = messageDigest.digest(pathPrefix.getBytes("UTF-8"));
return getHexEncode(md5Bytes).substring(0, 4);
} catch (NoSuchAlgorithmException e) {
LOG.error(e.getMessage());
} catch (UnsupportedEncodingException e) {
LOG.error(e.getMessage());
}
return "";
} | [
"public",
"static",
"String",
"getMd5Hash",
"(",
"String",
"topic",
",",
"String",
"[",
"]",
"partitions",
")",
"{",
"ArrayList",
"<",
"String",
">",
"elements",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"elements",
".",
"add",
"(",
"... | Generate MD5 hash of topic and partitions. And extract first 4 characters of the MD5 hash.
@param topic topic name
@param partitions partitions
@return md5 hash | [
"Generate",
"MD5",
"hash",
"of",
"topic",
"and",
"partitions",
".",
"And",
"extract",
"first",
"4",
"characters",
"of",
"the",
"MD5",
"hash",
"."
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/FileUtil.java#L248-L265 | train |
pinterest/secor | src/main/java/com/pinterest/secor/util/orc/schema/DefaultORCSchemaProvider.java | DefaultORCSchemaProvider.setSchemas | private void setSchemas(SecorConfig config) {
Map<String, String> schemaPerTopic = config.getORCMessageSchema();
for (Entry<String, String> entry : schemaPerTopic.entrySet()) {
String topic = entry.getKey();
TypeDescription schema = TypeDescription.fromString(entry
.getValue());
topicToSchemaMap.put(topic, schema);
// If common schema is given
if ("*".equals(topic)) {
schemaForAlltopic = schema;
}
}
} | java | private void setSchemas(SecorConfig config) {
Map<String, String> schemaPerTopic = config.getORCMessageSchema();
for (Entry<String, String> entry : schemaPerTopic.entrySet()) {
String topic = entry.getKey();
TypeDescription schema = TypeDescription.fromString(entry
.getValue());
topicToSchemaMap.put(topic, schema);
// If common schema is given
if ("*".equals(topic)) {
schemaForAlltopic = schema;
}
}
} | [
"private",
"void",
"setSchemas",
"(",
"SecorConfig",
"config",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"schemaPerTopic",
"=",
"config",
".",
"getORCMessageSchema",
"(",
")",
";",
"for",
"(",
"Entry",
"<",
"String",
",",
"String",
">",
"entry",
... | This method is used for fetching all ORC schemas from config
@param config | [
"This",
"method",
"is",
"used",
"for",
"fetching",
"all",
"ORC",
"schemas",
"from",
"config"
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/orc/schema/DefaultORCSchemaProvider.java#L62-L74 | train |
pinterest/secor | src/main/java/com/pinterest/secor/common/SecorConfig.java | SecorConfig.getPropertyMapForPrefix | public Map<String, String> getPropertyMapForPrefix(String prefix) {
Iterator<String> keys = mProperties.getKeys(prefix);
Map<String, String> map = new HashMap<String, String>();
while (keys.hasNext()) {
String key = keys.next();
String value = mProperties.getString(key);
map.put(key.substring(prefix.length() + 1), value);
}
return map;
} | java | public Map<String, String> getPropertyMapForPrefix(String prefix) {
Iterator<String> keys = mProperties.getKeys(prefix);
Map<String, String> map = new HashMap<String, String>();
while (keys.hasNext()) {
String key = keys.next();
String value = mProperties.getString(key);
map.put(key.substring(prefix.length() + 1), value);
}
return map;
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"getPropertyMapForPrefix",
"(",
"String",
"prefix",
")",
"{",
"Iterator",
"<",
"String",
">",
"keys",
"=",
"mProperties",
".",
"getKeys",
"(",
"prefix",
")",
";",
"Map",
"<",
"String",
",",
"String",
">... | This method is used for fetching all the properties which start with the given prefix.
It returns a Map of all those key-val.
e.g.
a.b.c=val1
a.b.d=val2
a.b.e=val3
If prefix is a.b then,
These will be fetched as a map {c = val1, d = val2, e = val3}
@param prefix property prefix
@return | [
"This",
"method",
"is",
"used",
"for",
"fetching",
"all",
"the",
"properties",
"which",
"start",
"with",
"the",
"given",
"prefix",
".",
"It",
"returns",
"a",
"Map",
"of",
"all",
"those",
"key",
"-",
"val",
"."
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/common/SecorConfig.java#L775-L784 | train |
pinterest/secor | src/main/java/com/pinterest/secor/tools/ProgressMonitor.java | ProgressMonitor.exportToStatsD | private void exportToStatsD(List<Stat> stats) {
// group stats by kafka group
for (Stat stat : stats) {
@SuppressWarnings("unchecked")
Map<String, String> tags = (Map<String, String>) stat.get(Stat.STAT_KEYS.TAGS.getName());
long value = Long.parseLong((String) stat.get(Stat.STAT_KEYS.VALUE.getName()));
if (mConfig.getStatsdDogstatdsTagsEnabled()) {
String metricName = (String) stat.get(Stat.STAT_KEYS.METRIC.getName());
String[] tagArray = new String[tags.size()];
int i = 0;
for (Map.Entry<String, String> e : tags.entrySet()) {
tagArray[i++] = e.getKey() + ':' + e.getValue();
}
mStatsDClient.recordGaugeValue(metricName, value, tagArray);
} else {
StringBuilder builder = new StringBuilder();
if (mConfig.getStatsDPrefixWithConsumerGroup()) {
builder.append(tags.get(Stat.STAT_KEYS.GROUP.getName()))
.append(PERIOD);
}
String metricName = builder
.append((String) stat.get(Stat.STAT_KEYS.METRIC.getName()))
.append(PERIOD)
.append(tags.get(Stat.STAT_KEYS.TOPIC.getName()))
.append(PERIOD)
.append(tags.get(Stat.STAT_KEYS.PARTITION.getName()))
.toString();
mStatsDClient.recordGaugeValue(metricName, value);
}
}
} | java | private void exportToStatsD(List<Stat> stats) {
// group stats by kafka group
for (Stat stat : stats) {
@SuppressWarnings("unchecked")
Map<String, String> tags = (Map<String, String>) stat.get(Stat.STAT_KEYS.TAGS.getName());
long value = Long.parseLong((String) stat.get(Stat.STAT_KEYS.VALUE.getName()));
if (mConfig.getStatsdDogstatdsTagsEnabled()) {
String metricName = (String) stat.get(Stat.STAT_KEYS.METRIC.getName());
String[] tagArray = new String[tags.size()];
int i = 0;
for (Map.Entry<String, String> e : tags.entrySet()) {
tagArray[i++] = e.getKey() + ':' + e.getValue();
}
mStatsDClient.recordGaugeValue(metricName, value, tagArray);
} else {
StringBuilder builder = new StringBuilder();
if (mConfig.getStatsDPrefixWithConsumerGroup()) {
builder.append(tags.get(Stat.STAT_KEYS.GROUP.getName()))
.append(PERIOD);
}
String metricName = builder
.append((String) stat.get(Stat.STAT_KEYS.METRIC.getName()))
.append(PERIOD)
.append(tags.get(Stat.STAT_KEYS.TOPIC.getName()))
.append(PERIOD)
.append(tags.get(Stat.STAT_KEYS.PARTITION.getName()))
.toString();
mStatsDClient.recordGaugeValue(metricName, value);
}
}
} | [
"private",
"void",
"exportToStatsD",
"(",
"List",
"<",
"Stat",
">",
"stats",
")",
"{",
"// group stats by kafka group",
"for",
"(",
"Stat",
"stat",
":",
"stats",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Map",
"<",
"String",
",",
"String... | Helper to publish stats to statsD client | [
"Helper",
"to",
"publish",
"stats",
"to",
"statsD",
"client"
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/tools/ProgressMonitor.java#L162-L192 | train |
pinterest/secor | src/main/java/com/pinterest/secor/common/FileRegistry.java | FileRegistry.getTopicPartitions | public Collection<TopicPartition> getTopicPartitions() {
Collection<TopicPartitionGroup> topicPartitions = getTopicPartitionGroups();
Set<TopicPartition> tps = new HashSet<TopicPartition>();
if (topicPartitions != null) {
for (TopicPartitionGroup g : topicPartitions) {
tps.addAll(g.getTopicPartitions());
}
}
return tps;
} | java | public Collection<TopicPartition> getTopicPartitions() {
Collection<TopicPartitionGroup> topicPartitions = getTopicPartitionGroups();
Set<TopicPartition> tps = new HashSet<TopicPartition>();
if (topicPartitions != null) {
for (TopicPartitionGroup g : topicPartitions) {
tps.addAll(g.getTopicPartitions());
}
}
return tps;
} | [
"public",
"Collection",
"<",
"TopicPartition",
">",
"getTopicPartitions",
"(",
")",
"{",
"Collection",
"<",
"TopicPartitionGroup",
">",
"topicPartitions",
"=",
"getTopicPartitionGroups",
"(",
")",
";",
"Set",
"<",
"TopicPartition",
">",
"tps",
"=",
"new",
"HashSet... | Get all topic partitions.
@return Collection of all registered topic partitions. | [
"Get",
"all",
"topic",
"partitions",
"."
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/common/FileRegistry.java#L58-L67 | train |
pinterest/secor | src/main/java/com/pinterest/secor/common/FileRegistry.java | FileRegistry.getPaths | public Collection<LogFilePath> getPaths(TopicPartitionGroup topicPartitionGroup) {
HashSet<LogFilePath> logFilePaths = mFiles.get(topicPartitionGroup);
if (logFilePaths == null) {
return new HashSet<LogFilePath>();
}
return new HashSet<LogFilePath>(logFilePaths);
} | java | public Collection<LogFilePath> getPaths(TopicPartitionGroup topicPartitionGroup) {
HashSet<LogFilePath> logFilePaths = mFiles.get(topicPartitionGroup);
if (logFilePaths == null) {
return new HashSet<LogFilePath>();
}
return new HashSet<LogFilePath>(logFilePaths);
} | [
"public",
"Collection",
"<",
"LogFilePath",
">",
"getPaths",
"(",
"TopicPartitionGroup",
"topicPartitionGroup",
")",
"{",
"HashSet",
"<",
"LogFilePath",
">",
"logFilePaths",
"=",
"mFiles",
".",
"get",
"(",
"topicPartitionGroup",
")",
";",
"if",
"(",
"logFilePaths"... | Get paths in a given topic partition.
@param topicPartitionGroup The topic partition to retrieve paths for.
@return Collection of file paths in the given topic partition. | [
"Get",
"paths",
"in",
"a",
"given",
"topic",
"partition",
"."
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/common/FileRegistry.java#L92-L98 | train |
pinterest/secor | src/main/java/com/pinterest/secor/common/FileRegistry.java | FileRegistry.getOrCreateWriter | public FileWriter getOrCreateWriter(LogFilePath path, CompressionCodec codec)
throws Exception {
FileWriter writer = mWriters.get(path);
if (writer == null) {
// Just in case.
FileUtil.delete(path.getLogFilePath());
FileUtil.delete(path.getLogFileCrcPath());
TopicPartitionGroup topicPartition = new TopicPartitionGroup(path.getTopic(),
path.getKafkaPartitions());
HashSet<LogFilePath> files = mFiles.get(topicPartition);
if (files == null) {
files = new HashSet<LogFilePath>();
mFiles.put(topicPartition, files);
}
if (!files.contains(path)) {
files.add(path);
}
writer = ReflectionUtil.createFileWriter(mConfig.getFileReaderWriterFactory(), path, codec, mConfig);
mWriters.put(path, writer);
mCreationTimes.put(path, System.currentTimeMillis() / 1000L);
LOG.debug("created writer for path {}", path.getLogFilePath());
LOG.debug("Register deleteOnExit for path {}", path.getLogFilePath());
FileUtil.deleteOnExit(path.getLogFileParentDir());
FileUtil.deleteOnExit(path.getLogFileDir());
FileUtil.deleteOnExit(path.getLogFilePath());
FileUtil.deleteOnExit(path.getLogFileCrcPath());
}
return writer;
} | java | public FileWriter getOrCreateWriter(LogFilePath path, CompressionCodec codec)
throws Exception {
FileWriter writer = mWriters.get(path);
if (writer == null) {
// Just in case.
FileUtil.delete(path.getLogFilePath());
FileUtil.delete(path.getLogFileCrcPath());
TopicPartitionGroup topicPartition = new TopicPartitionGroup(path.getTopic(),
path.getKafkaPartitions());
HashSet<LogFilePath> files = mFiles.get(topicPartition);
if (files == null) {
files = new HashSet<LogFilePath>();
mFiles.put(topicPartition, files);
}
if (!files.contains(path)) {
files.add(path);
}
writer = ReflectionUtil.createFileWriter(mConfig.getFileReaderWriterFactory(), path, codec, mConfig);
mWriters.put(path, writer);
mCreationTimes.put(path, System.currentTimeMillis() / 1000L);
LOG.debug("created writer for path {}", path.getLogFilePath());
LOG.debug("Register deleteOnExit for path {}", path.getLogFilePath());
FileUtil.deleteOnExit(path.getLogFileParentDir());
FileUtil.deleteOnExit(path.getLogFileDir());
FileUtil.deleteOnExit(path.getLogFilePath());
FileUtil.deleteOnExit(path.getLogFileCrcPath());
}
return writer;
} | [
"public",
"FileWriter",
"getOrCreateWriter",
"(",
"LogFilePath",
"path",
",",
"CompressionCodec",
"codec",
")",
"throws",
"Exception",
"{",
"FileWriter",
"writer",
"=",
"mWriters",
".",
"get",
"(",
"path",
")",
";",
"if",
"(",
"writer",
"==",
"null",
")",
"{... | Retrieve a writer for a given path or create a new one if it does not exist.
@param path The path to retrieve writer for.
@param codec Optional compression codec.
@return Writer for a given path.
@throws Exception on error | [
"Retrieve",
"a",
"writer",
"for",
"a",
"given",
"path",
"or",
"create",
"a",
"new",
"one",
"if",
"it",
"does",
"not",
"exist",
"."
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/common/FileRegistry.java#L118-L146 | train |
pinterest/secor | src/main/java/com/pinterest/secor/common/FileRegistry.java | FileRegistry.deletePath | public void deletePath(LogFilePath path) throws IOException {
TopicPartitionGroup topicPartition = new TopicPartitionGroup(path.getTopic(),
path.getKafkaPartitions());
HashSet<LogFilePath> paths = mFiles.get(topicPartition);
paths.remove(path);
if (paths.isEmpty()) {
mFiles.remove(topicPartition);
StatsUtil.clearLabel("secor.size." + topicPartition.getTopic() + "." +
topicPartition.getPartitions()[0]);
StatsUtil.clearLabel("secor.modification_age_sec." + topicPartition.getTopic() + "." +
topicPartition.getPartitions()[0]);
}
deleteWriter(path);
FileUtil.delete(path.getLogFilePath());
FileUtil.delete(path.getLogFileCrcPath());
} | java | public void deletePath(LogFilePath path) throws IOException {
TopicPartitionGroup topicPartition = new TopicPartitionGroup(path.getTopic(),
path.getKafkaPartitions());
HashSet<LogFilePath> paths = mFiles.get(topicPartition);
paths.remove(path);
if (paths.isEmpty()) {
mFiles.remove(topicPartition);
StatsUtil.clearLabel("secor.size." + topicPartition.getTopic() + "." +
topicPartition.getPartitions()[0]);
StatsUtil.clearLabel("secor.modification_age_sec." + topicPartition.getTopic() + "." +
topicPartition.getPartitions()[0]);
}
deleteWriter(path);
FileUtil.delete(path.getLogFilePath());
FileUtil.delete(path.getLogFileCrcPath());
} | [
"public",
"void",
"deletePath",
"(",
"LogFilePath",
"path",
")",
"throws",
"IOException",
"{",
"TopicPartitionGroup",
"topicPartition",
"=",
"new",
"TopicPartitionGroup",
"(",
"path",
".",
"getTopic",
"(",
")",
",",
"path",
".",
"getKafkaPartitions",
"(",
")",
"... | Delete a given path, the underlying file, and the corresponding writer.
@param path The path to delete.
@throws IOException on error | [
"Delete",
"a",
"given",
"path",
"the",
"underlying",
"file",
"and",
"the",
"corresponding",
"writer",
"."
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/common/FileRegistry.java#L153-L168 | train |
pinterest/secor | src/main/java/com/pinterest/secor/common/FileRegistry.java | FileRegistry.deleteWriter | public void deleteWriter(LogFilePath path) throws IOException {
FileWriter writer = mWriters.get(path);
if (writer == null) {
LOG.warn("No writer found for path {}", path.getLogFilePath());
} else {
LOG.info("Deleting writer for path {}", path.getLogFilePath());
writer.close();
mWriters.remove(path);
mCreationTimes.remove(path);
}
} | java | public void deleteWriter(LogFilePath path) throws IOException {
FileWriter writer = mWriters.get(path);
if (writer == null) {
LOG.warn("No writer found for path {}", path.getLogFilePath());
} else {
LOG.info("Deleting writer for path {}", path.getLogFilePath());
writer.close();
mWriters.remove(path);
mCreationTimes.remove(path);
}
} | [
"public",
"void",
"deleteWriter",
"(",
"LogFilePath",
"path",
")",
"throws",
"IOException",
"{",
"FileWriter",
"writer",
"=",
"mWriters",
".",
"get",
"(",
"path",
")",
";",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"No write... | Delete writer for a given topic partition. Underlying file is not removed.
@param path The path to remove the writer for.
@throws IOException on error | [
"Delete",
"writer",
"for",
"a",
"given",
"topic",
"partition",
".",
"Underlying",
"file",
"is",
"not",
"removed",
"."
] | 4099ff061db392f11044e57dedf46c1617895278 | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/common/FileRegistry.java#L195-L205 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceListenerHelper.java | DfuServiceListenerHelper.unregisterProgressListener | public static void unregisterProgressListener(@NonNull final Context context, @NonNull final DfuProgressListener listener) {
if (mProgressBroadcastReceiver != null) {
final boolean empty = mProgressBroadcastReceiver.removeProgressListener(listener);
if (empty) {
LocalBroadcastManager.getInstance(context).unregisterReceiver(mProgressBroadcastReceiver);
mProgressBroadcastReceiver = null;
}
}
} | java | public static void unregisterProgressListener(@NonNull final Context context, @NonNull final DfuProgressListener listener) {
if (mProgressBroadcastReceiver != null) {
final boolean empty = mProgressBroadcastReceiver.removeProgressListener(listener);
if (empty) {
LocalBroadcastManager.getInstance(context).unregisterReceiver(mProgressBroadcastReceiver);
mProgressBroadcastReceiver = null;
}
}
} | [
"public",
"static",
"void",
"unregisterProgressListener",
"(",
"@",
"NonNull",
"final",
"Context",
"context",
",",
"@",
"NonNull",
"final",
"DfuProgressListener",
"listener",
")",
"{",
"if",
"(",
"mProgressBroadcastReceiver",
"!=",
"null",
")",
"{",
"final",
"bool... | Unregisters the previously registered progress listener.
@param context the application context.
@param listener the listener to unregister. | [
"Unregisters",
"the",
"previously",
"registered",
"progress",
"listener",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceListenerHelper.java#L324-L333 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceListenerHelper.java | DfuServiceListenerHelper.unregisterLogListener | public static void unregisterLogListener(@NonNull final Context context, @NonNull final DfuLogListener listener) {
if (mLogBroadcastReceiver != null) {
final boolean empty = mLogBroadcastReceiver.removeLogListener(listener);
if (empty) {
LocalBroadcastManager.getInstance(context).unregisterReceiver(mLogBroadcastReceiver);
mLogBroadcastReceiver = null;
}
}
} | java | public static void unregisterLogListener(@NonNull final Context context, @NonNull final DfuLogListener listener) {
if (mLogBroadcastReceiver != null) {
final boolean empty = mLogBroadcastReceiver.removeLogListener(listener);
if (empty) {
LocalBroadcastManager.getInstance(context).unregisterReceiver(mLogBroadcastReceiver);
mLogBroadcastReceiver = null;
}
}
} | [
"public",
"static",
"void",
"unregisterLogListener",
"(",
"@",
"NonNull",
"final",
"Context",
"context",
",",
"@",
"NonNull",
"final",
"DfuLogListener",
"listener",
")",
"{",
"if",
"(",
"mLogBroadcastReceiver",
"!=",
"null",
")",
"{",
"final",
"boolean",
"empty"... | Unregisters the previously registered log listener.
@param context the application context.
@param listener the listener to unregister. | [
"Unregisters",
"the",
"previously",
"registered",
"log",
"listener",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceListenerHelper.java#L378-L387 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/internal/ArchiveInputStream.java | ArchiveInputStream.fullReset | public void fullReset() {
// Reset stream to SoftDevice if SD and BL firmware were given separately
if (softDeviceBytes != null && bootloaderBytes != null && currentSource == bootloaderBytes) {
currentSource = softDeviceBytes;
}
// Reset the bytes count to 0
bytesReadFromCurrentSource = 0;
mark(0);
reset();
} | java | public void fullReset() {
// Reset stream to SoftDevice if SD and BL firmware were given separately
if (softDeviceBytes != null && bootloaderBytes != null && currentSource == bootloaderBytes) {
currentSource = softDeviceBytes;
}
// Reset the bytes count to 0
bytesReadFromCurrentSource = 0;
mark(0);
reset();
} | [
"public",
"void",
"fullReset",
"(",
")",
"{",
"// Reset stream to SoftDevice if SD and BL firmware were given separately",
"if",
"(",
"softDeviceBytes",
"!=",
"null",
"&&",
"bootloaderBytes",
"!=",
"null",
"&&",
"currentSource",
"==",
"bootloaderBytes",
")",
"{",
"current... | Resets to the beginning of current stream.
If SD and BL were updated, the stream will be reset to the beginning.
If SD and BL were already sent and the current stream was changed to application,
this method will reset to the beginning of the application stream. | [
"Resets",
"to",
"the",
"beginning",
"of",
"current",
"stream",
".",
"If",
"SD",
"and",
"BL",
"were",
"updated",
"the",
"stream",
"will",
"be",
"reset",
"to",
"the",
"beginning",
".",
"If",
"SD",
"and",
"BL",
"were",
"already",
"sent",
"and",
"the",
"cu... | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/internal/ArchiveInputStream.java#L429-L438 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/BaseCustomDfuImpl.java | BaseCustomDfuImpl.writeInitData | void writeInitData(final BluetoothGattCharacteristic characteristic, final CRC32 crc32)
throws DfuException, DeviceDisconnectedException, UploadAbortedException {
try {
byte[] data = mBuffer;
int size;
while ((size = mInitPacketStream.read(data, 0, data.length)) != -1) {
writeInitPacket(characteristic, data, size);
if (crc32 != null)
crc32.update(data, 0, size);
}
} catch (final IOException e) {
loge("Error while reading Init packet file", e);
throw new DfuException("Error while reading Init packet file", DfuBaseService.ERROR_FILE_ERROR);
}
} | java | void writeInitData(final BluetoothGattCharacteristic characteristic, final CRC32 crc32)
throws DfuException, DeviceDisconnectedException, UploadAbortedException {
try {
byte[] data = mBuffer;
int size;
while ((size = mInitPacketStream.read(data, 0, data.length)) != -1) {
writeInitPacket(characteristic, data, size);
if (crc32 != null)
crc32.update(data, 0, size);
}
} catch (final IOException e) {
loge("Error while reading Init packet file", e);
throw new DfuException("Error while reading Init packet file", DfuBaseService.ERROR_FILE_ERROR);
}
} | [
"void",
"writeInitData",
"(",
"final",
"BluetoothGattCharacteristic",
"characteristic",
",",
"final",
"CRC32",
"crc32",
")",
"throws",
"DfuException",
",",
"DeviceDisconnectedException",
",",
"UploadAbortedException",
"{",
"try",
"{",
"byte",
"[",
"]",
"data",
"=",
... | Wends the whole init packet stream to the given characteristic.
@param characteristic the target characteristic
@param crc32 the CRC object to be updated based on the data sent
@throws DeviceDisconnectedException Thrown when the device will disconnect in the middle of
the transmission.
@throws DfuException Thrown if DFU error occur.
@throws UploadAbortedException Thrown if DFU operation was aborted by user. | [
"Wends",
"the",
"whole",
"init",
"packet",
"stream",
"to",
"the",
"given",
"characteristic",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/BaseCustomDfuImpl.java#L293-L307 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/BaseCustomDfuImpl.java | BaseCustomDfuImpl.uploadFirmwareImage | void uploadFirmwareImage(final BluetoothGattCharacteristic packetCharacteristic)
throws DeviceDisconnectedException, DfuException, UploadAbortedException {
if (mAborted)
throw new UploadAbortedException();
mReceivedData = null;
mError = 0;
mFirmwareUploadInProgress = true;
mPacketsSentSinceNotification = 0;
final byte[] buffer = mBuffer;
try {
final int size = mFirmwareStream.read(buffer);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE,
"Sending firmware to characteristic " + packetCharacteristic.getUuid() + "...");
writePacket(mGatt, packetCharacteristic, buffer, size);
} catch (final HexFileValidationException e) {
throw new DfuException("HEX file not valid", DfuBaseService.ERROR_FILE_INVALID);
} catch (final IOException e) {
throw new DfuException("Error while reading file", DfuBaseService.ERROR_FILE_IO_EXCEPTION);
}
try {
synchronized (mLock) {
while ((mFirmwareUploadInProgress && mReceivedData == null && mConnected && mError == 0) || mPaused)
mLock.wait();
}
} catch (final InterruptedException e) {
loge("Sleeping interrupted", e);
}
if (!mConnected)
throw new DeviceDisconnectedException("Uploading Firmware Image failed: device disconnected");
if (mError != 0)
throw new DfuException("Uploading Firmware Image failed", mError);
} | java | void uploadFirmwareImage(final BluetoothGattCharacteristic packetCharacteristic)
throws DeviceDisconnectedException, DfuException, UploadAbortedException {
if (mAborted)
throw new UploadAbortedException();
mReceivedData = null;
mError = 0;
mFirmwareUploadInProgress = true;
mPacketsSentSinceNotification = 0;
final byte[] buffer = mBuffer;
try {
final int size = mFirmwareStream.read(buffer);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE,
"Sending firmware to characteristic " + packetCharacteristic.getUuid() + "...");
writePacket(mGatt, packetCharacteristic, buffer, size);
} catch (final HexFileValidationException e) {
throw new DfuException("HEX file not valid", DfuBaseService.ERROR_FILE_INVALID);
} catch (final IOException e) {
throw new DfuException("Error while reading file", DfuBaseService.ERROR_FILE_IO_EXCEPTION);
}
try {
synchronized (mLock) {
while ((mFirmwareUploadInProgress && mReceivedData == null && mConnected && mError == 0) || mPaused)
mLock.wait();
}
} catch (final InterruptedException e) {
loge("Sleeping interrupted", e);
}
if (!mConnected)
throw new DeviceDisconnectedException("Uploading Firmware Image failed: device disconnected");
if (mError != 0)
throw new DfuException("Uploading Firmware Image failed", mError);
} | [
"void",
"uploadFirmwareImage",
"(",
"final",
"BluetoothGattCharacteristic",
"packetCharacteristic",
")",
"throws",
"DeviceDisconnectedException",
",",
"DfuException",
",",
"UploadAbortedException",
"{",
"if",
"(",
"mAborted",
")",
"throw",
"new",
"UploadAbortedException",
"... | Starts sending the data. This method is SYNCHRONOUS and terminates when the whole file will
be uploaded or the device get disconnected. If connection state will change, or an error
will occur, an exception will be thrown.
@param packetCharacteristic the characteristic to write file content to. Must be the DFU PACKET.
@throws DeviceDisconnectedException Thrown when the device will disconnect in the middle
of the transmission.
@throws DfuException Thrown if DFU error occur.
@throws UploadAbortedException Thrown if DFU operation was aborted by user. | [
"Starts",
"sending",
"the",
"data",
".",
"This",
"method",
"is",
"SYNCHRONOUS",
"and",
"terminates",
"when",
"the",
"whole",
"file",
"will",
"be",
"uploaded",
"or",
"the",
"device",
"get",
"disconnected",
".",
"If",
"connection",
"state",
"will",
"change",
"... | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/BaseCustomDfuImpl.java#L368-L402 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/BaseCustomDfuImpl.java | BaseCustomDfuImpl.writePacket | private void writePacket(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final byte[] buffer, final int size) {
byte[] locBuffer = buffer;
if (size <= 0) // This should never happen
return;
if (buffer.length != size) {
locBuffer = new byte[size];
System.arraycopy(buffer, 0, locBuffer, 0, size);
}
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
characteristic.setValue(locBuffer);
gatt.writeCharacteristic(characteristic);
} | java | private void writePacket(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final byte[] buffer, final int size) {
byte[] locBuffer = buffer;
if (size <= 0) // This should never happen
return;
if (buffer.length != size) {
locBuffer = new byte[size];
System.arraycopy(buffer, 0, locBuffer, 0, size);
}
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
characteristic.setValue(locBuffer);
gatt.writeCharacteristic(characteristic);
} | [
"private",
"void",
"writePacket",
"(",
"final",
"BluetoothGatt",
"gatt",
",",
"final",
"BluetoothGattCharacteristic",
"characteristic",
",",
"final",
"byte",
"[",
"]",
"buffer",
",",
"final",
"int",
"size",
")",
"{",
"byte",
"[",
"]",
"locBuffer",
"=",
"buffer... | Writes the buffer to the characteristic. The maximum size of the buffer is dependent on MTU.
This method is ASYNCHRONOUS and returns immediately after adding the data to TX queue.
@param characteristic the characteristic to write to. Should be the DFU PACKET.
@param buffer the buffer with 1-20 bytes.
@param size the number of bytes from the buffer to send. | [
"Writes",
"the",
"buffer",
"to",
"the",
"characteristic",
".",
"The",
"maximum",
"size",
"of",
"the",
"buffer",
"is",
"dependent",
"on",
"MTU",
".",
"This",
"method",
"is",
"ASYNCHRONOUS",
"and",
"returns",
"immediately",
"after",
"adding",
"the",
"data",
"t... | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/BaseCustomDfuImpl.java#L412-L423 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/LegacyButtonlessDfuImpl.java | LegacyButtonlessDfuImpl.readVersion | private int readVersion(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic)
throws DeviceDisconnectedException, DfuException, UploadAbortedException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read version number: device disconnected");
if (mAborted)
throw new UploadAbortedException();
// If the DFU Version characteristic is not available we return 0.
if (characteristic == null)
return 0;
mReceivedData = null;
mError = 0;
logi("Reading DFU version number...");
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Reading DFU version number...");
characteristic.setValue((byte[]) null);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.readCharacteristic(" + characteristic.getUuid() + ")");
gatt.readCharacteristic(characteristic);
// We have to wait until device receives a response or an error occur
try {
synchronized (mLock) {
while (((!mRequestCompleted || characteristic.getValue() == null) && mConnected && mError == 0 && !mAborted) || mPaused) {
mRequestCompleted = false;
mLock.wait();
}
}
} catch (final InterruptedException e) {
loge("Sleeping interrupted", e);
}
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read version number: device disconnected");
if (mError != 0)
throw new DfuException("Unable to read version number", mError);
// The version is a 16-bit unsigned int
return characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0);
} | java | private int readVersion(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic)
throws DeviceDisconnectedException, DfuException, UploadAbortedException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read version number: device disconnected");
if (mAborted)
throw new UploadAbortedException();
// If the DFU Version characteristic is not available we return 0.
if (characteristic == null)
return 0;
mReceivedData = null;
mError = 0;
logi("Reading DFU version number...");
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Reading DFU version number...");
characteristic.setValue((byte[]) null);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.readCharacteristic(" + characteristic.getUuid() + ")");
gatt.readCharacteristic(characteristic);
// We have to wait until device receives a response or an error occur
try {
synchronized (mLock) {
while (((!mRequestCompleted || characteristic.getValue() == null) && mConnected && mError == 0 && !mAborted) || mPaused) {
mRequestCompleted = false;
mLock.wait();
}
}
} catch (final InterruptedException e) {
loge("Sleeping interrupted", e);
}
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read version number: device disconnected");
if (mError != 0)
throw new DfuException("Unable to read version number", mError);
// The version is a 16-bit unsigned int
return characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0);
} | [
"private",
"int",
"readVersion",
"(",
"final",
"BluetoothGatt",
"gatt",
",",
"final",
"BluetoothGattCharacteristic",
"characteristic",
")",
"throws",
"DeviceDisconnectedException",
",",
"DfuException",
",",
"UploadAbortedException",
"{",
"if",
"(",
"!",
"mConnected",
")... | Reads the DFU Version characteristic if such exists. Otherwise it returns 0.
@param gatt the GATT device.
@param characteristic the characteristic to read.
@return a version number or 0 if not present on the bootloader.
@throws DeviceDisconnectedException Thrown when the device will disconnect in the middle of
the transmission.
@throws DfuException Thrown if DFU error occur.
@throws UploadAbortedException Thrown if DFU operation was aborted by user. | [
"Reads",
"the",
"DFU",
"Version",
"characteristic",
"if",
"such",
"exists",
".",
"Otherwise",
"it",
"returns",
"0",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/LegacyButtonlessDfuImpl.java#L210-L248 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/BaseDfuImpl.java | BaseDfuImpl.createBondApi18 | private boolean createBondApi18(@NonNull final BluetoothDevice device) {
/*
* There is a createBond() method in BluetoothDevice class but for now it's hidden. We will call it using reflections. It has been revealed in KitKat (Api19)
*/
try {
final Method createBond = device.getClass().getMethod("createBond");
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.getDevice().createBond() (hidden)");
return (Boolean) createBond.invoke(device);
} catch (final Exception e) {
Log.w(TAG, "An exception occurred while creating bond", e);
}
return false;
} | java | private boolean createBondApi18(@NonNull final BluetoothDevice device) {
/*
* There is a createBond() method in BluetoothDevice class but for now it's hidden. We will call it using reflections. It has been revealed in KitKat (Api19)
*/
try {
final Method createBond = device.getClass().getMethod("createBond");
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.getDevice().createBond() (hidden)");
return (Boolean) createBond.invoke(device);
} catch (final Exception e) {
Log.w(TAG, "An exception occurred while creating bond", e);
}
return false;
} | [
"private",
"boolean",
"createBondApi18",
"(",
"@",
"NonNull",
"final",
"BluetoothDevice",
"device",
")",
"{",
"/*\n\t\t * There is a createBond() method in BluetoothDevice class but for now it's hidden. We will call it using reflections. It has been revealed in KitKat (Api19)\n\t\t */",
"try... | A method that creates the bond to given device on API lower than Android 5.
@param device the target device
@return false if bonding failed (no hidden createBond() method in BluetoothDevice, or this method returned false | [
"A",
"method",
"that",
"creates",
"the",
"bond",
"to",
"given",
"device",
"on",
"API",
"lower",
"than",
"Android",
"5",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/BaseDfuImpl.java#L611-L623 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/BaseDfuImpl.java | BaseDfuImpl.removeBond | @SuppressWarnings("UnusedReturnValue")
boolean removeBond() {
final BluetoothDevice device = mGatt.getDevice();
if (device.getBondState() == BluetoothDevice.BOND_NONE)
return true;
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Removing bond information...");
boolean result = false;
/*
* There is a removeBond() method in BluetoothDevice class but for now it's hidden. We will call it using reflections.
*/
try {
//noinspection JavaReflectionMemberAccess
final Method removeBond = device.getClass().getMethod("removeBond");
mRequestCompleted = false;
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.getDevice().removeBond() (hidden)");
result = (Boolean) removeBond.invoke(device);
// We have to wait until device is unbounded
try {
synchronized (mLock) {
while (!mRequestCompleted && !mAborted)
mLock.wait();
}
} catch (final InterruptedException e) {
loge("Sleeping interrupted", e);
}
} catch (final Exception e) {
Log.w(TAG, "An exception occurred while removing bond information", e);
}
return result;
} | java | @SuppressWarnings("UnusedReturnValue")
boolean removeBond() {
final BluetoothDevice device = mGatt.getDevice();
if (device.getBondState() == BluetoothDevice.BOND_NONE)
return true;
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Removing bond information...");
boolean result = false;
/*
* There is a removeBond() method in BluetoothDevice class but for now it's hidden. We will call it using reflections.
*/
try {
//noinspection JavaReflectionMemberAccess
final Method removeBond = device.getClass().getMethod("removeBond");
mRequestCompleted = false;
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.getDevice().removeBond() (hidden)");
result = (Boolean) removeBond.invoke(device);
// We have to wait until device is unbounded
try {
synchronized (mLock) {
while (!mRequestCompleted && !mAborted)
mLock.wait();
}
} catch (final InterruptedException e) {
loge("Sleeping interrupted", e);
}
} catch (final Exception e) {
Log.w(TAG, "An exception occurred while removing bond information", e);
}
return result;
} | [
"@",
"SuppressWarnings",
"(",
"\"UnusedReturnValue\"",
")",
"boolean",
"removeBond",
"(",
")",
"{",
"final",
"BluetoothDevice",
"device",
"=",
"mGatt",
".",
"getDevice",
"(",
")",
";",
"if",
"(",
"device",
".",
"getBondState",
"(",
")",
"==",
"BluetoothDevice"... | Removes the bond information for the given device.
@return <code>true</code> if operation succeeded, <code>false</code> otherwise | [
"Removes",
"the",
"bond",
"information",
"for",
"the",
"given",
"device",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/BaseDfuImpl.java#L630-L661 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/BaseDfuImpl.java | BaseDfuImpl.requestMtu | @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
void requestMtu(@IntRange(from = 0, to = 517) final int mtu)
throws DeviceDisconnectedException, UploadAbortedException {
if (mAborted)
throw new UploadAbortedException();
mRequestCompleted = false;
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Requesting new MTU...");
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.requestMtu(" + mtu + ")");
if (!mGatt.requestMtu(mtu))
return;
// We have to wait until the MTU exchange finishes
try {
synchronized (mLock) {
while ((!mRequestCompleted && mConnected && mError == 0) || mPaused)
mLock.wait();
}
} catch (final InterruptedException e) {
loge("Sleeping interrupted", e);
}
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read Service Changed CCCD: device disconnected");
} | java | @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
void requestMtu(@IntRange(from = 0, to = 517) final int mtu)
throws DeviceDisconnectedException, UploadAbortedException {
if (mAborted)
throw new UploadAbortedException();
mRequestCompleted = false;
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Requesting new MTU...");
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.requestMtu(" + mtu + ")");
if (!mGatt.requestMtu(mtu))
return;
// We have to wait until the MTU exchange finishes
try {
synchronized (mLock) {
while ((!mRequestCompleted && mConnected && mError == 0) || mPaused)
mLock.wait();
}
} catch (final InterruptedException e) {
loge("Sleeping interrupted", e);
}
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read Service Changed CCCD: device disconnected");
} | [
"@",
"RequiresApi",
"(",
"api",
"=",
"Build",
".",
"VERSION_CODES",
".",
"LOLLIPOP",
")",
"void",
"requestMtu",
"(",
"@",
"IntRange",
"(",
"from",
"=",
"0",
",",
"to",
"=",
"517",
")",
"final",
"int",
"mtu",
")",
"throws",
"DeviceDisconnectedException",
... | Requests given MTU. This method is only supported on Android Lollipop or newer versions.
Only DFU from SDK 14.1 or newer supports MTU > 23.
@param mtu new MTU to be requested. | [
"Requests",
"given",
"MTU",
".",
"This",
"method",
"is",
"only",
"supported",
"on",
"Android",
"Lollipop",
"or",
"newer",
"versions",
".",
"Only",
"DFU",
"from",
"SDK",
"14",
".",
"1",
"or",
"newer",
"supports",
"MTU",
">",
"23",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/BaseDfuImpl.java#L679-L702 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/BaseDfuImpl.java | BaseDfuImpl.readNotificationResponse | byte[] readNotificationResponse()
throws DeviceDisconnectedException, DfuException, UploadAbortedException {
// do not clear the mReceiveData here. The response might already be obtained. Clear it in write request instead.
try {
synchronized (mLock) {
while ((mReceivedData == null && mConnected && mError == 0 && !mAborted) || mPaused)
mLock.wait();
}
} catch (final InterruptedException e) {
loge("Sleeping interrupted", e);
}
if (mAborted)
throw new UploadAbortedException();
if (!mConnected)
throw new DeviceDisconnectedException("Unable to write Op Code: device disconnected");
if (mError != 0)
throw new DfuException("Unable to write Op Code", mError);
return mReceivedData;
} | java | byte[] readNotificationResponse()
throws DeviceDisconnectedException, DfuException, UploadAbortedException {
// do not clear the mReceiveData here. The response might already be obtained. Clear it in write request instead.
try {
synchronized (mLock) {
while ((mReceivedData == null && mConnected && mError == 0 && !mAborted) || mPaused)
mLock.wait();
}
} catch (final InterruptedException e) {
loge("Sleeping interrupted", e);
}
if (mAborted)
throw new UploadAbortedException();
if (!mConnected)
throw new DeviceDisconnectedException("Unable to write Op Code: device disconnected");
if (mError != 0)
throw new DfuException("Unable to write Op Code", mError);
return mReceivedData;
} | [
"byte",
"[",
"]",
"readNotificationResponse",
"(",
")",
"throws",
"DeviceDisconnectedException",
",",
"DfuException",
",",
"UploadAbortedException",
"{",
"// do not clear the mReceiveData here. The response might already be obtained. Clear it in write request instead.",
"try",
"{",
"... | Waits until the notification will arrive. Returns the data returned by the notification.
This method will block the thread until response is not ready or the device gets disconnected.
If connection state will change, or an error will occur, an exception will be thrown.
@return the value returned by the Control Point notification
@throws DeviceDisconnectedException Thrown when the device will disconnect in the middle of
the transmission.
@throws DfuException Thrown if DFU error occur.
@throws UploadAbortedException Thrown if DFU operation was aborted by user. | [
"Waits",
"until",
"the",
"notification",
"will",
"arrive",
".",
"Returns",
"the",
"data",
"returned",
"by",
"the",
"notification",
".",
"This",
"method",
"will",
"block",
"the",
"thread",
"until",
"response",
"is",
"not",
"ready",
"or",
"the",
"device",
"get... | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/BaseDfuImpl.java#L715-L733 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/BaseDfuImpl.java | BaseDfuImpl.restartService | void restartService(@NonNull final Intent intent, final boolean scanForBootloader) {
String newAddress = null;
if (scanForBootloader) {
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Scanning for the DFU Bootloader...");
newAddress = BootloaderScannerFactory.getScanner().searchFor(mGatt.getDevice().getAddress());
logi("Scanning for new address finished with: " + newAddress);
if (newAddress != null)
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_INFO, "DFU Bootloader found with address " + newAddress);
else {
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_INFO, "DFU Bootloader not found. Trying the same address...");
}
}
if (newAddress != null)
intent.putExtra(DfuBaseService.EXTRA_DEVICE_ADDRESS, newAddress);
// Reset the DFU attempt counter
intent.putExtra(DfuBaseService.EXTRA_DFU_ATTEMPT, 0);
mService.startService(intent);
} | java | void restartService(@NonNull final Intent intent, final boolean scanForBootloader) {
String newAddress = null;
if (scanForBootloader) {
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Scanning for the DFU Bootloader...");
newAddress = BootloaderScannerFactory.getScanner().searchFor(mGatt.getDevice().getAddress());
logi("Scanning for new address finished with: " + newAddress);
if (newAddress != null)
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_INFO, "DFU Bootloader found with address " + newAddress);
else {
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_INFO, "DFU Bootloader not found. Trying the same address...");
}
}
if (newAddress != null)
intent.putExtra(DfuBaseService.EXTRA_DEVICE_ADDRESS, newAddress);
// Reset the DFU attempt counter
intent.putExtra(DfuBaseService.EXTRA_DFU_ATTEMPT, 0);
mService.startService(intent);
} | [
"void",
"restartService",
"(",
"@",
"NonNull",
"final",
"Intent",
"intent",
",",
"final",
"boolean",
"scanForBootloader",
")",
"{",
"String",
"newAddress",
"=",
"null",
";",
"if",
"(",
"scanForBootloader",
")",
"{",
"mService",
".",
"sendLogBroadcast",
"(",
"D... | Restarts the service based on the given intent. If parameter set this method will also scan for
an advertising bootloader that has address equal or incremented by 1 to the current one.
@param intent the intent to be started as a service
@param scanForBootloader true to scan for advertising bootloader, false to keep the same address | [
"Restarts",
"the",
"service",
"based",
"on",
"the",
"given",
"intent",
".",
"If",
"parameter",
"set",
"this",
"method",
"will",
"also",
"scan",
"for",
"an",
"advertising",
"bootloader",
"that",
"has",
"address",
"equal",
"or",
"incremented",
"by",
"1",
"to",... | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/BaseDfuImpl.java#L742-L762 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceInitiator.java | DfuServiceInitiator.setZip | public DfuServiceInitiator setZip(@Nullable final Uri uri, @Nullable final String path) {
return init(uri, path, 0, DfuBaseService.TYPE_AUTO, DfuBaseService.MIME_TYPE_ZIP);
} | java | public DfuServiceInitiator setZip(@Nullable final Uri uri, @Nullable final String path) {
return init(uri, path, 0, DfuBaseService.TYPE_AUTO, DfuBaseService.MIME_TYPE_ZIP);
} | [
"public",
"DfuServiceInitiator",
"setZip",
"(",
"@",
"Nullable",
"final",
"Uri",
"uri",
",",
"@",
"Nullable",
"final",
"String",
"path",
")",
"{",
"return",
"init",
"(",
"uri",
",",
"path",
",",
"0",
",",
"DfuBaseService",
".",
"TYPE_AUTO",
",",
"DfuBaseSe... | Sets the URI or path of the ZIP file.
At least one of the parameters must not be null.
If the URI and path are not null the URI will be used.
@param uri the URI of the file
@param path the path of the file
@return the builder | [
"Sets",
"the",
"URI",
"or",
"path",
"of",
"the",
"ZIP",
"file",
".",
"At",
"least",
"one",
"of",
"the",
"parameters",
"must",
"not",
"be",
"null",
".",
"If",
"the",
"URI",
"and",
"path",
"are",
"not",
"null",
"the",
"URI",
"will",
"be",
"used",
"."... | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceInitiator.java#L604-L606 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceInitiator.java | DfuServiceInitiator.start | public DfuServiceController start(@NonNull final Context context, @NonNull final Class<? extends DfuBaseService> service) {
if (fileType == -1)
throw new UnsupportedOperationException("You must specify the firmware file before starting the service");
final Intent intent = new Intent(context, service);
intent.putExtra(DfuBaseService.EXTRA_DEVICE_ADDRESS, deviceAddress);
intent.putExtra(DfuBaseService.EXTRA_DEVICE_NAME, deviceName);
intent.putExtra(DfuBaseService.EXTRA_DISABLE_NOTIFICATION, disableNotification);
intent.putExtra(DfuBaseService.EXTRA_FOREGROUND_SERVICE, startAsForegroundService);
intent.putExtra(DfuBaseService.EXTRA_FILE_MIME_TYPE, mimeType);
intent.putExtra(DfuBaseService.EXTRA_FILE_TYPE, fileType);
intent.putExtra(DfuBaseService.EXTRA_FILE_URI, fileUri);
intent.putExtra(DfuBaseService.EXTRA_FILE_PATH, filePath);
intent.putExtra(DfuBaseService.EXTRA_FILE_RES_ID, fileResId);
intent.putExtra(DfuBaseService.EXTRA_INIT_FILE_URI, initFileUri);
intent.putExtra(DfuBaseService.EXTRA_INIT_FILE_PATH, initFilePath);
intent.putExtra(DfuBaseService.EXTRA_INIT_FILE_RES_ID, initFileResId);
intent.putExtra(DfuBaseService.EXTRA_KEEP_BOND, keepBond);
intent.putExtra(DfuBaseService.EXTRA_RESTORE_BOND, restoreBond);
intent.putExtra(DfuBaseService.EXTRA_FORCE_DFU, forceDfu);
intent.putExtra(DfuBaseService.EXTRA_DISABLE_RESUME, disableResume);
intent.putExtra(DfuBaseService.EXTRA_MAX_DFU_ATTEMPTS, numberOfRetries);
intent.putExtra(DfuBaseService.EXTRA_MBR_SIZE, mbrSize);
if (mtu > 0)
intent.putExtra(DfuBaseService.EXTRA_MTU, mtu);
intent.putExtra(DfuBaseService.EXTRA_CURRENT_MTU, currentMtu);
intent.putExtra(DfuBaseService.EXTRA_UNSAFE_EXPERIMENTAL_BUTTONLESS_DFU, enableUnsafeExperimentalButtonlessDfu);
//noinspection StatementWithEmptyBody
if (packetReceiptNotificationsEnabled != null) {
intent.putExtra(DfuBaseService.EXTRA_PACKET_RECEIPT_NOTIFICATIONS_ENABLED, packetReceiptNotificationsEnabled);
intent.putExtra(DfuBaseService.EXTRA_PACKET_RECEIPT_NOTIFICATIONS_VALUE, numberOfPackets);
} else {
// For backwards compatibility:
// If the setPacketsReceiptNotificationsEnabled(boolean) has not been called, the PRN state and value are taken from
// SharedPreferences the way they were read in DFU Library in 1.0.3 and before, or set to default values.
// Default values: PRNs enabled on Android 4.3 - 5.1 and disabled starting from Android 6.0. Default PRN value is 12.
}
if (legacyDfuUuids != null)
intent.putExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_LEGACY_DFU, legacyDfuUuids);
if (secureDfuUuids != null)
intent.putExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_SECURE_DFU, secureDfuUuids);
if (experimentalButtonlessDfuUuids != null)
intent.putExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_EXPERIMENTAL_BUTTONLESS_DFU, experimentalButtonlessDfuUuids);
if (buttonlessDfuWithoutBondSharingUuids != null)
intent.putExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_BUTTONLESS_DFU_WITHOUT_BOND_SHARING, buttonlessDfuWithoutBondSharingUuids);
if (buttonlessDfuWithBondSharingUuids != null)
intent.putExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_BUTTONLESS_DFU_WITH_BOND_SHARING, buttonlessDfuWithBondSharingUuids);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && startAsForegroundService) {
// On Android Oreo and above the service must be started as a foreground service to make it accessible from
// a killed application.
context.startForegroundService(intent);
} else {
context.startService(intent);
}
return new DfuServiceController(context);
} | java | public DfuServiceController start(@NonNull final Context context, @NonNull final Class<? extends DfuBaseService> service) {
if (fileType == -1)
throw new UnsupportedOperationException("You must specify the firmware file before starting the service");
final Intent intent = new Intent(context, service);
intent.putExtra(DfuBaseService.EXTRA_DEVICE_ADDRESS, deviceAddress);
intent.putExtra(DfuBaseService.EXTRA_DEVICE_NAME, deviceName);
intent.putExtra(DfuBaseService.EXTRA_DISABLE_NOTIFICATION, disableNotification);
intent.putExtra(DfuBaseService.EXTRA_FOREGROUND_SERVICE, startAsForegroundService);
intent.putExtra(DfuBaseService.EXTRA_FILE_MIME_TYPE, mimeType);
intent.putExtra(DfuBaseService.EXTRA_FILE_TYPE, fileType);
intent.putExtra(DfuBaseService.EXTRA_FILE_URI, fileUri);
intent.putExtra(DfuBaseService.EXTRA_FILE_PATH, filePath);
intent.putExtra(DfuBaseService.EXTRA_FILE_RES_ID, fileResId);
intent.putExtra(DfuBaseService.EXTRA_INIT_FILE_URI, initFileUri);
intent.putExtra(DfuBaseService.EXTRA_INIT_FILE_PATH, initFilePath);
intent.putExtra(DfuBaseService.EXTRA_INIT_FILE_RES_ID, initFileResId);
intent.putExtra(DfuBaseService.EXTRA_KEEP_BOND, keepBond);
intent.putExtra(DfuBaseService.EXTRA_RESTORE_BOND, restoreBond);
intent.putExtra(DfuBaseService.EXTRA_FORCE_DFU, forceDfu);
intent.putExtra(DfuBaseService.EXTRA_DISABLE_RESUME, disableResume);
intent.putExtra(DfuBaseService.EXTRA_MAX_DFU_ATTEMPTS, numberOfRetries);
intent.putExtra(DfuBaseService.EXTRA_MBR_SIZE, mbrSize);
if (mtu > 0)
intent.putExtra(DfuBaseService.EXTRA_MTU, mtu);
intent.putExtra(DfuBaseService.EXTRA_CURRENT_MTU, currentMtu);
intent.putExtra(DfuBaseService.EXTRA_UNSAFE_EXPERIMENTAL_BUTTONLESS_DFU, enableUnsafeExperimentalButtonlessDfu);
//noinspection StatementWithEmptyBody
if (packetReceiptNotificationsEnabled != null) {
intent.putExtra(DfuBaseService.EXTRA_PACKET_RECEIPT_NOTIFICATIONS_ENABLED, packetReceiptNotificationsEnabled);
intent.putExtra(DfuBaseService.EXTRA_PACKET_RECEIPT_NOTIFICATIONS_VALUE, numberOfPackets);
} else {
// For backwards compatibility:
// If the setPacketsReceiptNotificationsEnabled(boolean) has not been called, the PRN state and value are taken from
// SharedPreferences the way they were read in DFU Library in 1.0.3 and before, or set to default values.
// Default values: PRNs enabled on Android 4.3 - 5.1 and disabled starting from Android 6.0. Default PRN value is 12.
}
if (legacyDfuUuids != null)
intent.putExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_LEGACY_DFU, legacyDfuUuids);
if (secureDfuUuids != null)
intent.putExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_SECURE_DFU, secureDfuUuids);
if (experimentalButtonlessDfuUuids != null)
intent.putExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_EXPERIMENTAL_BUTTONLESS_DFU, experimentalButtonlessDfuUuids);
if (buttonlessDfuWithoutBondSharingUuids != null)
intent.putExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_BUTTONLESS_DFU_WITHOUT_BOND_SHARING, buttonlessDfuWithoutBondSharingUuids);
if (buttonlessDfuWithBondSharingUuids != null)
intent.putExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_BUTTONLESS_DFU_WITH_BOND_SHARING, buttonlessDfuWithBondSharingUuids);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && startAsForegroundService) {
// On Android Oreo and above the service must be started as a foreground service to make it accessible from
// a killed application.
context.startForegroundService(intent);
} else {
context.startService(intent);
}
return new DfuServiceController(context);
} | [
"public",
"DfuServiceController",
"start",
"(",
"@",
"NonNull",
"final",
"Context",
"context",
",",
"@",
"NonNull",
"final",
"Class",
"<",
"?",
"extends",
"DfuBaseService",
">",
"service",
")",
"{",
"if",
"(",
"fileType",
"==",
"-",
"1",
")",
"throw",
"new... | Starts the DFU service.
@param context the application context
@param service the class derived from the BaseDfuService | [
"Starts",
"the",
"DFU",
"service",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceInitiator.java#L738-L795 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java | SecureDfuImpl.setObjectSize | private void setObjectSize(@NonNull final byte[] data, final int value) {
data[2] = (byte) (value & 0xFF);
data[3] = (byte) ((value >> 8) & 0xFF);
data[4] = (byte) ((value >> 16) & 0xFF);
data[5] = (byte) ((value >> 24) & 0xFF);
} | java | private void setObjectSize(@NonNull final byte[] data, final int value) {
data[2] = (byte) (value & 0xFF);
data[3] = (byte) ((value >> 8) & 0xFF);
data[4] = (byte) ((value >> 16) & 0xFF);
data[5] = (byte) ((value >> 24) & 0xFF);
} | [
"private",
"void",
"setObjectSize",
"(",
"@",
"NonNull",
"final",
"byte",
"[",
"]",
"data",
",",
"final",
"int",
"value",
")",
"{",
"data",
"[",
"2",
"]",
"=",
"(",
"byte",
")",
"(",
"value",
"&",
"0xFF",
")",
";",
"data",
"[",
"3",
"]",
"=",
"... | Sets the object size in correct position of the data array.
@param data control point data packet
@param value Object size in bytes. | [
"Sets",
"the",
"object",
"size",
"in",
"correct",
"position",
"of",
"the",
"data",
"array",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java#L737-L742 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java | SecureDfuImpl.writeCreateRequest | private void writeCreateRequest(final int type, final int size)
throws DeviceDisconnectedException, DfuException, UploadAbortedException, RemoteDfuException,
UnknownResponseException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to create object: device disconnected");
final byte[] data = (type == OBJECT_COMMAND) ? OP_CODE_CREATE_COMMAND : OP_CODE_CREATE_DATA;
setObjectSize(data, size);
writeOpCode(mControlPointCharacteristic, data);
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_CREATE_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Creating Command object failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Creating Command object failed", status);
} | java | private void writeCreateRequest(final int type, final int size)
throws DeviceDisconnectedException, DfuException, UploadAbortedException, RemoteDfuException,
UnknownResponseException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to create object: device disconnected");
final byte[] data = (type == OBJECT_COMMAND) ? OP_CODE_CREATE_COMMAND : OP_CODE_CREATE_DATA;
setObjectSize(data, size);
writeOpCode(mControlPointCharacteristic, data);
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_CREATE_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Creating Command object failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Creating Command object failed", status);
} | [
"private",
"void",
"writeCreateRequest",
"(",
"final",
"int",
"type",
",",
"final",
"int",
"size",
")",
"throws",
"DeviceDisconnectedException",
",",
"DfuException",
",",
"UploadAbortedException",
",",
"RemoteDfuException",
",",
"UnknownResponseException",
"{",
"if",
... | Writes Create Object request providing the type and size of the object.
@param type {@link #OBJECT_COMMAND} or {@link #OBJECT_DATA}.
@param size size of the object or current part of the object.
@throws DeviceDisconnectedException
@throws DfuException
@throws UploadAbortedException
@throws RemoteDfuException thrown when the returned status code is not equal to {@link #DFU_STATUS_SUCCESS}
@throws UnknownResponseException | [
"Writes",
"Create",
"Object",
"request",
"providing",
"the",
"type",
"and",
"size",
"of",
"the",
"object",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java#L807-L823 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java | SecureDfuImpl.selectObject | private ObjectInfo selectObject(final int type)
throws DeviceDisconnectedException, DfuException, UploadAbortedException,
RemoteDfuException, UnknownResponseException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read object info: device disconnected");
OP_CODE_SELECT_OBJECT[1] = (byte) type;
writeOpCode(mControlPointCharacteristic, OP_CODE_SELECT_OBJECT);
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_SELECT_OBJECT_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Selecting object failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Selecting object failed", status);
final ObjectInfo info = new ObjectInfo();
info.maxSize = mControlPointCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3);
info.offset = mControlPointCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3 + 4);
info.CRC32 = mControlPointCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3 + 8);
return info;
} | java | private ObjectInfo selectObject(final int type)
throws DeviceDisconnectedException, DfuException, UploadAbortedException,
RemoteDfuException, UnknownResponseException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read object info: device disconnected");
OP_CODE_SELECT_OBJECT[1] = (byte) type;
writeOpCode(mControlPointCharacteristic, OP_CODE_SELECT_OBJECT);
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_SELECT_OBJECT_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Selecting object failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Selecting object failed", status);
final ObjectInfo info = new ObjectInfo();
info.maxSize = mControlPointCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3);
info.offset = mControlPointCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3 + 4);
info.CRC32 = mControlPointCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3 + 8);
return info;
} | [
"private",
"ObjectInfo",
"selectObject",
"(",
"final",
"int",
"type",
")",
"throws",
"DeviceDisconnectedException",
",",
"DfuException",
",",
"UploadAbortedException",
",",
"RemoteDfuException",
",",
"UnknownResponseException",
"{",
"if",
"(",
"!",
"mConnected",
")",
... | Selects the current object and reads its metadata. The object info contains the max object
size, and the offset and CRC32 of the whole object until now.
@return object info.
@throws DeviceDisconnectedException
@throws DfuException
@throws UploadAbortedException
@throws RemoteDfuException thrown when the returned status code is not equal to
{@link #DFU_STATUS_SUCCESS}. | [
"Selects",
"the",
"current",
"object",
"and",
"reads",
"its",
"metadata",
".",
"The",
"object",
"info",
"contains",
"the",
"max",
"object",
"size",
"and",
"the",
"offset",
"and",
"CRC32",
"of",
"the",
"whole",
"object",
"until",
"now",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java#L836-L857 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java | SecureDfuImpl.readChecksum | private ObjectChecksum readChecksum() throws DeviceDisconnectedException, DfuException,
UploadAbortedException, RemoteDfuException, UnknownResponseException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected");
writeOpCode(mControlPointCharacteristic, OP_CODE_CALCULATE_CHECKSUM);
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_CALCULATE_CHECKSUM_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Receiving Checksum failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Receiving Checksum failed", status);
final ObjectChecksum checksum = new ObjectChecksum();
checksum.offset = mControlPointCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3);
checksum.CRC32 = mControlPointCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3 + 4);
return checksum;
} | java | private ObjectChecksum readChecksum() throws DeviceDisconnectedException, DfuException,
UploadAbortedException, RemoteDfuException, UnknownResponseException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected");
writeOpCode(mControlPointCharacteristic, OP_CODE_CALCULATE_CHECKSUM);
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_CALCULATE_CHECKSUM_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Receiving Checksum failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Receiving Checksum failed", status);
final ObjectChecksum checksum = new ObjectChecksum();
checksum.offset = mControlPointCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3);
checksum.CRC32 = mControlPointCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3 + 4);
return checksum;
} | [
"private",
"ObjectChecksum",
"readChecksum",
"(",
")",
"throws",
"DeviceDisconnectedException",
",",
"DfuException",
",",
"UploadAbortedException",
",",
"RemoteDfuException",
",",
"UnknownResponseException",
"{",
"if",
"(",
"!",
"mConnected",
")",
"throw",
"new",
"Devic... | Sends the Calculate Checksum request. As a response a notification will be sent with current
offset and CRC32 of the current object.
@return requested object info.
@throws DeviceDisconnectedException
@throws DfuException
@throws UploadAbortedException
@throws RemoteDfuException thrown when the returned status code is not equal to
{@link #DFU_STATUS_SUCCESS}. | [
"Sends",
"the",
"Calculate",
"Checksum",
"request",
".",
"As",
"a",
"response",
"a",
"notification",
"will",
"be",
"sent",
"with",
"current",
"offset",
"and",
"CRC32",
"of",
"the",
"current",
"object",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java#L870-L888 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java | SecureDfuImpl.writeExecute | private void writeExecute() throws DfuException, DeviceDisconnectedException,
UploadAbortedException, UnknownResponseException, RemoteDfuException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected");
writeOpCode(mControlPointCharacteristic, OP_CODE_EXECUTE);
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_EXECUTE_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Executing object failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Executing object failed", status);
} | java | private void writeExecute() throws DfuException, DeviceDisconnectedException,
UploadAbortedException, UnknownResponseException, RemoteDfuException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected");
writeOpCode(mControlPointCharacteristic, OP_CODE_EXECUTE);
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_EXECUTE_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Executing object failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Executing object failed", status);
} | [
"private",
"void",
"writeExecute",
"(",
")",
"throws",
"DfuException",
",",
"DeviceDisconnectedException",
",",
"UploadAbortedException",
",",
"UnknownResponseException",
",",
"RemoteDfuException",
"{",
"if",
"(",
"!",
"mConnected",
")",
"throw",
"new",
"DeviceDisconnec... | Sends the Execute operation code and awaits for a return notification containing status code.
The Execute command will confirm the last chunk of data or the last command that was sent.
Creating the same object again, instead of executing it allows to retransmitting it in case
of a CRC error.
@throws DfuException
@throws DeviceDisconnectedException
@throws UploadAbortedException
@throws UnknownResponseException
@throws RemoteDfuException thrown when the returned status code is not equal to
{@link #DFU_STATUS_SUCCESS}. | [
"Sends",
"the",
"Execute",
"operation",
"code",
"and",
"awaits",
"for",
"a",
"return",
"notification",
"containing",
"status",
"code",
".",
"The",
"Execute",
"command",
"will",
"confirm",
"the",
"last",
"chunk",
"of",
"data",
"or",
"the",
"last",
"command",
... | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java#L903-L916 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/internal/scanner/BootloaderScannerFactory.java | BootloaderScannerFactory.getScanner | public static BootloaderScanner getScanner() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
return new BootloaderScannerLollipop();
return new BootloaderScannerJB();
} | java | public static BootloaderScanner getScanner() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
return new BootloaderScannerLollipop();
return new BootloaderScannerJB();
} | [
"public",
"static",
"BootloaderScanner",
"getScanner",
"(",
")",
"{",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"Build",
".",
"VERSION_CODES",
".",
"LOLLIPOP",
")",
"return",
"new",
"BootloaderScannerLollipop",
"(",
")",
";",
"return",
"new",
... | Returns the scanner implementation.
@return the bootloader scanner | [
"Returns",
"the",
"scanner",
"implementation",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/internal/scanner/BootloaderScannerFactory.java#L38-L42 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java | DfuBaseService.openInputStream | private InputStream openInputStream(@NonNull final String filePath, final String mimeType, final int mbrSize, final int types)
throws IOException {
final InputStream is = new FileInputStream(filePath);
if (MIME_TYPE_ZIP.equals(mimeType))
return new ArchiveInputStream(is, mbrSize, types);
if (filePath.toLowerCase(Locale.US).endsWith("hex"))
return new HexInputStream(is, mbrSize);
return is;
} | java | private InputStream openInputStream(@NonNull final String filePath, final String mimeType, final int mbrSize, final int types)
throws IOException {
final InputStream is = new FileInputStream(filePath);
if (MIME_TYPE_ZIP.equals(mimeType))
return new ArchiveInputStream(is, mbrSize, types);
if (filePath.toLowerCase(Locale.US).endsWith("hex"))
return new HexInputStream(is, mbrSize);
return is;
} | [
"private",
"InputStream",
"openInputStream",
"(",
"@",
"NonNull",
"final",
"String",
"filePath",
",",
"final",
"String",
"mimeType",
",",
"final",
"int",
"mbrSize",
",",
"final",
"int",
"types",
")",
"throws",
"IOException",
"{",
"final",
"InputStream",
"is",
... | Opens the binary input stream that returns the firmware image content.
A Path to the file is given.
@param filePath the path to the HEX, BIN or ZIP file.
@param mimeType the file type.
@param mbrSize the size of MBR, by default 0x1000.
@param types the content files types in ZIP.
@return The input stream with binary image content. | [
"Opens",
"the",
"binary",
"input",
"stream",
"that",
"returns",
"the",
"firmware",
"image",
"content",
".",
"A",
"Path",
"to",
"the",
"file",
"is",
"given",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java#L1416-L1424 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java | DfuBaseService.openInputStream | private InputStream openInputStream(@NonNull final Uri stream, final String mimeType, final int mbrSize, final int types)
throws IOException {
final InputStream is = getContentResolver().openInputStream(stream);
if (MIME_TYPE_ZIP.equals(mimeType))
return new ArchiveInputStream(is, mbrSize, types);
final String[] projection = {MediaStore.Images.Media.DISPLAY_NAME};
final Cursor cursor = getContentResolver().query(stream, projection, null, null, null);
try {
if (cursor.moveToNext()) {
final String fileName = cursor.getString(0 /* DISPLAY_NAME*/);
if (fileName.toLowerCase(Locale.US).endsWith("hex"))
return new HexInputStream(is, mbrSize);
}
} finally {
cursor.close();
}
return is;
} | java | private InputStream openInputStream(@NonNull final Uri stream, final String mimeType, final int mbrSize, final int types)
throws IOException {
final InputStream is = getContentResolver().openInputStream(stream);
if (MIME_TYPE_ZIP.equals(mimeType))
return new ArchiveInputStream(is, mbrSize, types);
final String[] projection = {MediaStore.Images.Media.DISPLAY_NAME};
final Cursor cursor = getContentResolver().query(stream, projection, null, null, null);
try {
if (cursor.moveToNext()) {
final String fileName = cursor.getString(0 /* DISPLAY_NAME*/);
if (fileName.toLowerCase(Locale.US).endsWith("hex"))
return new HexInputStream(is, mbrSize);
}
} finally {
cursor.close();
}
return is;
} | [
"private",
"InputStream",
"openInputStream",
"(",
"@",
"NonNull",
"final",
"Uri",
"stream",
",",
"final",
"String",
"mimeType",
",",
"final",
"int",
"mbrSize",
",",
"final",
"int",
"types",
")",
"throws",
"IOException",
"{",
"final",
"InputStream",
"is",
"=",
... | Opens the binary input stream. A Uri to the stream is given.
@param stream the Uri to the stream.
@param mimeType the file type.
@param mbrSize the size of MBR, by default 0x1000.
@param types the content files types in ZIP.
@return The input stream with binary image content. | [
"Opens",
"the",
"binary",
"input",
"stream",
".",
"A",
"Uri",
"to",
"the",
"stream",
"is",
"given",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java#L1435-L1454 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java | DfuBaseService.terminateConnection | protected void terminateConnection(@NonNull final BluetoothGatt gatt, final int error) {
if (mConnectionState != STATE_DISCONNECTED) {
// Disconnect from the device
disconnect(gatt);
}
// Close the device
refreshDeviceCache(gatt, false); // This should be set to true when DFU Version is 0.5 or lower
close(gatt);
waitFor(600);
if (error != 0)
report(error);
} | java | protected void terminateConnection(@NonNull final BluetoothGatt gatt, final int error) {
if (mConnectionState != STATE_DISCONNECTED) {
// Disconnect from the device
disconnect(gatt);
}
// Close the device
refreshDeviceCache(gatt, false); // This should be set to true when DFU Version is 0.5 or lower
close(gatt);
waitFor(600);
if (error != 0)
report(error);
} | [
"protected",
"void",
"terminateConnection",
"(",
"@",
"NonNull",
"final",
"BluetoothGatt",
"gatt",
",",
"final",
"int",
"error",
")",
"{",
"if",
"(",
"mConnectionState",
"!=",
"STATE_DISCONNECTED",
")",
"{",
"// Disconnect from the device",
"disconnect",
"(",
"gatt"... | Disconnects from the device and cleans local variables in case of error.
This method is SYNCHRONOUS and wait until the disconnecting process will be completed.
@param gatt the GATT device to be disconnected.
@param error error number. | [
"Disconnects",
"from",
"the",
"device",
"and",
"cleans",
"local",
"variables",
"in",
"case",
"of",
"error",
".",
"This",
"method",
"is",
"SYNCHRONOUS",
"and",
"wait",
"until",
"the",
"disconnecting",
"process",
"will",
"be",
"completed",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java#L1519-L1531 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java | DfuBaseService.waitFor | protected void waitFor(final int millis) {
synchronized (mLock) {
try {
sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "wait(" + millis + ")");
mLock.wait(millis);
} catch (final InterruptedException e) {
loge("Sleeping interrupted", e);
}
}
} | java | protected void waitFor(final int millis) {
synchronized (mLock) {
try {
sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "wait(" + millis + ")");
mLock.wait(millis);
} catch (final InterruptedException e) {
loge("Sleeping interrupted", e);
}
}
} | [
"protected",
"void",
"waitFor",
"(",
"final",
"int",
"millis",
")",
"{",
"synchronized",
"(",
"mLock",
")",
"{",
"try",
"{",
"sendLogBroadcast",
"(",
"DfuBaseService",
".",
"LOG_LEVEL_DEBUG",
",",
"\"wait(\"",
"+",
"millis",
"+",
"\")\"",
")",
";",
"mLock",
... | Wait for given number of milliseconds.
@param millis waiting period. | [
"Wait",
"for",
"given",
"number",
"of",
"milliseconds",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java#L1577-L1586 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java | DfuBaseService.close | protected void close(final BluetoothGatt gatt) {
logi("Cleaning up...");
sendLogBroadcast(LOG_LEVEL_DEBUG, "gatt.close()");
gatt.close();
mConnectionState = STATE_CLOSED;
} | java | protected void close(final BluetoothGatt gatt) {
logi("Cleaning up...");
sendLogBroadcast(LOG_LEVEL_DEBUG, "gatt.close()");
gatt.close();
mConnectionState = STATE_CLOSED;
} | [
"protected",
"void",
"close",
"(",
"final",
"BluetoothGatt",
"gatt",
")",
"{",
"logi",
"(",
"\"Cleaning up...\"",
")",
";",
"sendLogBroadcast",
"(",
"LOG_LEVEL_DEBUG",
",",
"\"gatt.close()\"",
")",
";",
"gatt",
".",
"close",
"(",
")",
";",
"mConnectionState",
... | Closes the GATT device and cleans up.
@param gatt the GATT device to be closed. | [
"Closes",
"the",
"GATT",
"device",
"and",
"cleans",
"up",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java#L1593-L1598 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java | DfuBaseService.refreshDeviceCache | protected void refreshDeviceCache(final BluetoothGatt gatt, final boolean force) {
/*
* If the device is bonded this is up to the Service Changed characteristic to notify Android that the services has changed.
* There is no need for this trick in that case.
* If not bonded, the Android should not keep the services cached when the Service Changed characteristic is present in the target device database.
* However, due to the Android bug (still exists in Android 5.0.1), it is keeping them anyway and the only way to clear services is by using this hidden refresh method.
*/
if (force || gatt.getDevice().getBondState() == BluetoothDevice.BOND_NONE) {
sendLogBroadcast(LOG_LEVEL_DEBUG, "gatt.refresh() (hidden)");
/*
* There is a refresh() method in BluetoothGatt class but for now it's hidden. We will call it using reflections.
*/
try {
//noinspection JavaReflectionMemberAccess
final Method refresh = gatt.getClass().getMethod("refresh");
final boolean success = (Boolean) refresh.invoke(gatt);
logi("Refreshing result: " + success);
} catch (Exception e) {
loge("An exception occurred while refreshing device", e);
sendLogBroadcast(LOG_LEVEL_WARNING, "Refreshing failed");
}
}
} | java | protected void refreshDeviceCache(final BluetoothGatt gatt, final boolean force) {
/*
* If the device is bonded this is up to the Service Changed characteristic to notify Android that the services has changed.
* There is no need for this trick in that case.
* If not bonded, the Android should not keep the services cached when the Service Changed characteristic is present in the target device database.
* However, due to the Android bug (still exists in Android 5.0.1), it is keeping them anyway and the only way to clear services is by using this hidden refresh method.
*/
if (force || gatt.getDevice().getBondState() == BluetoothDevice.BOND_NONE) {
sendLogBroadcast(LOG_LEVEL_DEBUG, "gatt.refresh() (hidden)");
/*
* There is a refresh() method in BluetoothGatt class but for now it's hidden. We will call it using reflections.
*/
try {
//noinspection JavaReflectionMemberAccess
final Method refresh = gatt.getClass().getMethod("refresh");
final boolean success = (Boolean) refresh.invoke(gatt);
logi("Refreshing result: " + success);
} catch (Exception e) {
loge("An exception occurred while refreshing device", e);
sendLogBroadcast(LOG_LEVEL_WARNING, "Refreshing failed");
}
}
} | [
"protected",
"void",
"refreshDeviceCache",
"(",
"final",
"BluetoothGatt",
"gatt",
",",
"final",
"boolean",
"force",
")",
"{",
"/*\n\t\t * If the device is bonded this is up to the Service Changed characteristic to notify Android that the services has changed.\n\t\t * There is no need for t... | Clears the device cache. After uploading new firmware the DFU target will have other
services than before.
@param gatt the GATT device to be refreshed.
@param force <code>true</code> to force the refresh. | [
"Clears",
"the",
"device",
"cache",
".",
"After",
"uploading",
"new",
"firmware",
"the",
"DFU",
"target",
"will",
"have",
"other",
"services",
"than",
"before",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java#L1607-L1629 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java | DfuBaseService.updateProgressNotification | protected void updateProgressNotification(@NonNull final NotificationCompat.Builder builder, final int progress) {
// Add Abort action to the notification
if (progress != PROGRESS_ABORTED && progress != PROGRESS_COMPLETED) {
final Intent abortIntent = new Intent(BROADCAST_ACTION);
abortIntent.putExtra(EXTRA_ACTION, ACTION_ABORT);
final PendingIntent pendingAbortIntent = PendingIntent.getBroadcast(this, 1, abortIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(R.drawable.ic_action_notify_cancel, getString(R.string.dfu_action_abort), pendingAbortIntent);
}
} | java | protected void updateProgressNotification(@NonNull final NotificationCompat.Builder builder, final int progress) {
// Add Abort action to the notification
if (progress != PROGRESS_ABORTED && progress != PROGRESS_COMPLETED) {
final Intent abortIntent = new Intent(BROADCAST_ACTION);
abortIntent.putExtra(EXTRA_ACTION, ACTION_ABORT);
final PendingIntent pendingAbortIntent = PendingIntent.getBroadcast(this, 1, abortIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(R.drawable.ic_action_notify_cancel, getString(R.string.dfu_action_abort), pendingAbortIntent);
}
} | [
"protected",
"void",
"updateProgressNotification",
"(",
"@",
"NonNull",
"final",
"NotificationCompat",
".",
"Builder",
"builder",
",",
"final",
"int",
"progress",
")",
"{",
"// Add Abort action to the notification",
"if",
"(",
"progress",
"!=",
"PROGRESS_ABORTED",
"&&",... | This method allows you to update the notification showing the upload progress.
@param builder notification builder. | [
"This",
"method",
"allows",
"you",
"to",
"update",
"the",
"notification",
"showing",
"the",
"upload",
"progress",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java#L1725-L1733 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java | DfuBaseService.report | private void report(final int error) {
sendErrorBroadcast(error);
if (mDisableNotification)
return;
// create or update notification:
final String deviceAddress = mDeviceAddress;
final String deviceName = mDeviceName != null ? mDeviceName : getString(R.string.dfu_unknown_name);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_DFU)
.setSmallIcon(android.R.drawable.stat_sys_upload)
.setOnlyAlertOnce(true)
.setColor(Color.RED)
.setOngoing(false)
.setContentTitle(getString(R.string.dfu_status_error))
.setSmallIcon(android.R.drawable.stat_sys_upload_done)
.setContentText(getString(R.string.dfu_status_error_msg))
.setAutoCancel(true);
// update the notification
final Intent intent = new Intent(this, getNotificationTarget());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(EXTRA_DEVICE_ADDRESS, deviceAddress);
intent.putExtra(EXTRA_DEVICE_NAME, deviceName);
intent.putExtra(EXTRA_PROGRESS, error); // this may contains ERROR_CONNECTION_MASK bit!
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
// Any additional configuration?
updateErrorNotification(builder);
final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, builder.build());
} | java | private void report(final int error) {
sendErrorBroadcast(error);
if (mDisableNotification)
return;
// create or update notification:
final String deviceAddress = mDeviceAddress;
final String deviceName = mDeviceName != null ? mDeviceName : getString(R.string.dfu_unknown_name);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_DFU)
.setSmallIcon(android.R.drawable.stat_sys_upload)
.setOnlyAlertOnce(true)
.setColor(Color.RED)
.setOngoing(false)
.setContentTitle(getString(R.string.dfu_status_error))
.setSmallIcon(android.R.drawable.stat_sys_upload_done)
.setContentText(getString(R.string.dfu_status_error_msg))
.setAutoCancel(true);
// update the notification
final Intent intent = new Intent(this, getNotificationTarget());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(EXTRA_DEVICE_ADDRESS, deviceAddress);
intent.putExtra(EXTRA_DEVICE_NAME, deviceName);
intent.putExtra(EXTRA_PROGRESS, error); // this may contains ERROR_CONNECTION_MASK bit!
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
// Any additional configuration?
updateErrorNotification(builder);
final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, builder.build());
} | [
"private",
"void",
"report",
"(",
"final",
"int",
"error",
")",
"{",
"sendErrorBroadcast",
"(",
"error",
")",
";",
"if",
"(",
"mDisableNotification",
")",
"return",
";",
"// create or update notification:",
"final",
"String",
"deviceAddress",
"=",
"mDeviceAddress",
... | Creates or updates the notification in the Notification Manager. Sends broadcast with given
error number to the activity.
@param error the error number. | [
"Creates",
"or",
"updates",
"the",
"notification",
"in",
"the",
"Notification",
"Manager",
".",
"Sends",
"broadcast",
"with",
"given",
"error",
"number",
"to",
"the",
"activity",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java#L1741-L1775 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java | DfuBaseService.initialize | @SuppressWarnings("UnusedReturnValue")
private boolean initialize() {
// For API level 18 and above, get a reference to BluetoothAdapter through
// BluetoothManager.
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (bluetoothManager == null) {
loge("Unable to initialize BluetoothManager.");
return false;
}
mBluetoothAdapter = bluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
loge("Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
} | java | @SuppressWarnings("UnusedReturnValue")
private boolean initialize() {
// For API level 18 and above, get a reference to BluetoothAdapter through
// BluetoothManager.
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (bluetoothManager == null) {
loge("Unable to initialize BluetoothManager.");
return false;
}
mBluetoothAdapter = bluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
loge("Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
} | [
"@",
"SuppressWarnings",
"(",
"\"UnusedReturnValue\"",
")",
"private",
"boolean",
"initialize",
"(",
")",
"{",
"// For API level 18 and above, get a reference to BluetoothAdapter through",
"// BluetoothManager.",
"final",
"BluetoothManager",
"bluetoothManager",
"=",
"(",
"Bluetoo... | Initializes bluetooth adapter.
@return <code>True</code> if initialization was successful. | [
"Initializes",
"bluetooth",
"adapter",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java#L1923-L1940 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/internal/HexInputStream.java | HexInputStream.readLine | private int readLine() throws IOException {
// end of file reached
if (pos == -1)
return 0;
final InputStream in = this.in;
// temporary value
int b;
int lineSize, type, offset;
do {
// skip end of line
do {
b = in.read();
pos++;
} while (b == '\n' || b == '\r');
/*
* Each line starts with comma (':')
* Data is written in HEX, so each 2 ASCII letters give one byte.
* After the comma there is one byte (2 HEX signs) with line length
* (normally 10 -> 0x10 -> 16 bytes -> 32 HEX characters)
* After that there is a 4 byte of an address. This part may be skipped.
* There is a packet type after the address (1 byte = 2 HEX characters).
* 00 is the valid data. Other values can be skipped when converting to BIN file.
* Then goes n bytes of data followed by 1 byte (2 HEX chars) of checksum,
* which is also skipped in BIN file.
*/
checkComma(b); // checking the comma at the beginning
lineSize = readByte(in); // reading the length of the data in this line
pos += 2;
offset = readAddress(in);// reading the offset
pos += 4;
type = readByte(in); // reading the line type
pos += 2;
// if the line type is no longer data type (0x00), we've reached the end of the file
switch (type) {
case 0x00:
// data type
if (lastAddress + offset < MBRSize) { // skip MBR
type = -1; // some other than 0
pos += skip(in, lineSize * 2 /* 2 hex per one byte */ + 2 /* check sum */);
}
break;
case 0x01:
// end of file
pos = -1;
return 0;
case 0x02: {
// extended segment address
final int address = readAddress(in) << 4;
pos += 4;
if (bytesRead > 0 && (address >> 16) != (lastAddress >> 16) + 1)
return 0;
lastAddress = address;
pos += skip(in, 2 /* check sum */);
break;
}
case 0x04: {
// extended linear address
final int address = readAddress(in);
pos += 4;
if (bytesRead > 0 && address != (lastAddress >> 16) + 1)
return 0;
lastAddress = address << 16;
pos += skip(in, 2 /* check sum */);
break;
}
default:
final long toBeSkipped = lineSize * 2 /* 2 hex per one byte */ + 2 /* check sum */;
pos += skip(in, toBeSkipped);
break;
}
} while (type != 0);
// otherwise read lineSize bytes or fill the whole buffer
for (int i = 0; i < localBuf.length && i < lineSize; ++i) {
b = readByte(in);
pos += 2;
localBuf[i] = (byte) b;
}
pos += skip(in, 2); // skip the checksum
localPos = 0;
return lineSize;
} | java | private int readLine() throws IOException {
// end of file reached
if (pos == -1)
return 0;
final InputStream in = this.in;
// temporary value
int b;
int lineSize, type, offset;
do {
// skip end of line
do {
b = in.read();
pos++;
} while (b == '\n' || b == '\r');
/*
* Each line starts with comma (':')
* Data is written in HEX, so each 2 ASCII letters give one byte.
* After the comma there is one byte (2 HEX signs) with line length
* (normally 10 -> 0x10 -> 16 bytes -> 32 HEX characters)
* After that there is a 4 byte of an address. This part may be skipped.
* There is a packet type after the address (1 byte = 2 HEX characters).
* 00 is the valid data. Other values can be skipped when converting to BIN file.
* Then goes n bytes of data followed by 1 byte (2 HEX chars) of checksum,
* which is also skipped in BIN file.
*/
checkComma(b); // checking the comma at the beginning
lineSize = readByte(in); // reading the length of the data in this line
pos += 2;
offset = readAddress(in);// reading the offset
pos += 4;
type = readByte(in); // reading the line type
pos += 2;
// if the line type is no longer data type (0x00), we've reached the end of the file
switch (type) {
case 0x00:
// data type
if (lastAddress + offset < MBRSize) { // skip MBR
type = -1; // some other than 0
pos += skip(in, lineSize * 2 /* 2 hex per one byte */ + 2 /* check sum */);
}
break;
case 0x01:
// end of file
pos = -1;
return 0;
case 0x02: {
// extended segment address
final int address = readAddress(in) << 4;
pos += 4;
if (bytesRead > 0 && (address >> 16) != (lastAddress >> 16) + 1)
return 0;
lastAddress = address;
pos += skip(in, 2 /* check sum */);
break;
}
case 0x04: {
// extended linear address
final int address = readAddress(in);
pos += 4;
if (bytesRead > 0 && address != (lastAddress >> 16) + 1)
return 0;
lastAddress = address << 16;
pos += skip(in, 2 /* check sum */);
break;
}
default:
final long toBeSkipped = lineSize * 2 /* 2 hex per one byte */ + 2 /* check sum */;
pos += skip(in, toBeSkipped);
break;
}
} while (type != 0);
// otherwise read lineSize bytes or fill the whole buffer
for (int i = 0; i < localBuf.length && i < lineSize; ++i) {
b = readByte(in);
pos += 2;
localBuf[i] = (byte) b;
}
pos += skip(in, 2); // skip the checksum
localPos = 0;
return lineSize;
} | [
"private",
"int",
"readLine",
"(",
")",
"throws",
"IOException",
"{",
"// end of file reached",
"if",
"(",
"pos",
"==",
"-",
"1",
")",
"return",
"0",
";",
"final",
"InputStream",
"in",
"=",
"this",
".",
"in",
";",
"// temporary value",
"int",
"b",
";",
"... | Reads new line from the input stream. Input stream must be a HEX file.
The first line is always skipped.
@return the number of data bytes in the new line. 0 if end of file.
@throws java.io.IOException if this stream is closed or another IOException occurs. | [
"Reads",
"new",
"line",
"from",
"the",
"input",
"stream",
".",
"Input",
"stream",
"must",
"be",
"a",
"HEX",
"file",
".",
"The",
"first",
"line",
"is",
"always",
"skipped",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/internal/HexInputStream.java#L242-L328 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/LegacyDfuImpl.java | LegacyDfuImpl.readVersion | private int readVersion(@Nullable final BluetoothGattCharacteristic characteristic) {
// The value of this characteristic has been read before by LegacyButtonlessDfuImpl
return characteristic != null ? characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0) : 0;
} | java | private int readVersion(@Nullable final BluetoothGattCharacteristic characteristic) {
// The value of this characteristic has been read before by LegacyButtonlessDfuImpl
return characteristic != null ? characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0) : 0;
} | [
"private",
"int",
"readVersion",
"(",
"@",
"Nullable",
"final",
"BluetoothGattCharacteristic",
"characteristic",
")",
"{",
"// The value of this characteristic has been read before by LegacyButtonlessDfuImpl",
"return",
"characteristic",
"!=",
"null",
"?",
"characteristic",
".",
... | Returns the DFU Version characteristic if such exists. Otherwise it returns 0.
@param characteristic the characteristic to read.
@return a version number or 0 if not present on the bootloader. | [
"Returns",
"the",
"DFU",
"Version",
"characteristic",
"if",
"such",
"exists",
".",
"Otherwise",
"it",
"returns",
"0",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/LegacyDfuImpl.java#L588-L591 | train |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/LegacyDfuImpl.java | LegacyDfuImpl.resetAndRestart | private void resetAndRestart(@NonNull final BluetoothGatt gatt, @NonNull final Intent intent)
throws DfuException, DeviceDisconnectedException, UploadAbortedException {
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, "Last upload interrupted. Restarting device...");
// Send 'jump to bootloader command' (Start DFU)
mProgressInfo.setProgress(DfuBaseService.PROGRESS_DISCONNECTING);
logi("Sending Reset command (Op Code = 6)");
writeOpCode(mControlPointCharacteristic, OP_CODE_RESET);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Reset request sent");
// The device will reset so we don't have to send Disconnect signal.
mService.waitUntilDisconnected();
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_INFO, "Disconnected by the remote device");
final BluetoothGattService gas = gatt.getService(GENERIC_ATTRIBUTE_SERVICE_UUID);
final boolean hasServiceChanged = gas != null && gas.getCharacteristic(SERVICE_CHANGED_UUID) != null;
mService.refreshDeviceCache(gatt, !hasServiceChanged);
// Close the device
mService.close(gatt);
logi("Restarting the service");
final Intent newIntent = new Intent();
newIntent.fillIn(intent, Intent.FILL_IN_COMPONENT | Intent.FILL_IN_PACKAGE);
restartService(newIntent, false);
} | java | private void resetAndRestart(@NonNull final BluetoothGatt gatt, @NonNull final Intent intent)
throws DfuException, DeviceDisconnectedException, UploadAbortedException {
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, "Last upload interrupted. Restarting device...");
// Send 'jump to bootloader command' (Start DFU)
mProgressInfo.setProgress(DfuBaseService.PROGRESS_DISCONNECTING);
logi("Sending Reset command (Op Code = 6)");
writeOpCode(mControlPointCharacteristic, OP_CODE_RESET);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Reset request sent");
// The device will reset so we don't have to send Disconnect signal.
mService.waitUntilDisconnected();
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_INFO, "Disconnected by the remote device");
final BluetoothGattService gas = gatt.getService(GENERIC_ATTRIBUTE_SERVICE_UUID);
final boolean hasServiceChanged = gas != null && gas.getCharacteristic(SERVICE_CHANGED_UUID) != null;
mService.refreshDeviceCache(gatt, !hasServiceChanged);
// Close the device
mService.close(gatt);
logi("Restarting the service");
final Intent newIntent = new Intent();
newIntent.fillIn(intent, Intent.FILL_IN_COMPONENT | Intent.FILL_IN_PACKAGE);
restartService(newIntent, false);
} | [
"private",
"void",
"resetAndRestart",
"(",
"@",
"NonNull",
"final",
"BluetoothGatt",
"gatt",
",",
"@",
"NonNull",
"final",
"Intent",
"intent",
")",
"throws",
"DfuException",
",",
"DeviceDisconnectedException",
",",
"UploadAbortedException",
"{",
"mService",
".",
"se... | Sends Reset command to the target device to reset its state and restarts the DFU Service that will start again.
@param gatt the GATT device.
@param intent intent used to start the service.
@throws DeviceDisconnectedException Thrown when the device will disconnect in the middle of
the transmission.
@throws DfuException Thrown if DFU error occur.
@throws UploadAbortedException Thrown if DFU operation was aborted by user. | [
"Sends",
"Reset",
"command",
"to",
"the",
"target",
"device",
"to",
"reset",
"its",
"state",
"and",
"restarts",
"the",
"DFU",
"Service",
"that",
"will",
"start",
"again",
"."
] | ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/LegacyDfuImpl.java#L720-L744 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiObjectRef.java | JsiiObjectRef.parse | public static JsiiObjectRef parse(final JsonNode objRef) {
if (!objRef.has(TOKEN_REF)) {
throw new JsiiException("Malformed object reference. Expecting " + TOKEN_REF);
}
return new JsiiObjectRef(objRef.get(TOKEN_REF).textValue(), objRef);
} | java | public static JsiiObjectRef parse(final JsonNode objRef) {
if (!objRef.has(TOKEN_REF)) {
throw new JsiiException("Malformed object reference. Expecting " + TOKEN_REF);
}
return new JsiiObjectRef(objRef.get(TOKEN_REF).textValue(), objRef);
} | [
"public",
"static",
"JsiiObjectRef",
"parse",
"(",
"final",
"JsonNode",
"objRef",
")",
"{",
"if",
"(",
"!",
"objRef",
".",
"has",
"(",
"TOKEN_REF",
")",
")",
"{",
"throw",
"new",
"JsiiException",
"(",
"\"Malformed object reference. Expecting \"",
"+",
"TOKEN_REF... | Creates an object reference.
@param objRef The object reference.
@return A {@link JsiiObjectRef} object. | [
"Creates",
"an",
"object",
"reference",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiObjectRef.java#L50-L56 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiObjectRef.java | JsiiObjectRef.fromObjId | public static JsiiObjectRef fromObjId(final String objId) {
ObjectNode node = JsonNodeFactory.instance.objectNode();
node.put(TOKEN_REF, objId);
return new JsiiObjectRef(objId, node);
} | java | public static JsiiObjectRef fromObjId(final String objId) {
ObjectNode node = JsonNodeFactory.instance.objectNode();
node.put(TOKEN_REF, objId);
return new JsiiObjectRef(objId, node);
} | [
"public",
"static",
"JsiiObjectRef",
"fromObjId",
"(",
"final",
"String",
"objId",
")",
"{",
"ObjectNode",
"node",
"=",
"JsonNodeFactory",
".",
"instance",
".",
"objectNode",
"(",
")",
";",
"node",
".",
"put",
"(",
"TOKEN_REF",
",",
"objId",
")",
";",
"ret... | Creates an object ref from an object ID.
@param objId Object ID.
@return The new object ref. | [
"Creates",
"an",
"object",
"ref",
"from",
"an",
"object",
"ID",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiObjectRef.java#L63-L67 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.loadModule | public void loadModule(final JsiiModule module) {
try {
String tarball = extractResource(module.getModuleClass(), module.getBundleResourceName(), null);
ObjectNode req = makeRequest("load");
req.put("tarball", tarball);
req.put("name", module.getModuleName());
req.put("version", module.getModuleVersion());
this.runtime.requestResponse(req);
} catch (IOException e) {
throw new JsiiException("Unable to extract resource " + module.getBundleResourceName(), e);
}
} | java | public void loadModule(final JsiiModule module) {
try {
String tarball = extractResource(module.getModuleClass(), module.getBundleResourceName(), null);
ObjectNode req = makeRequest("load");
req.put("tarball", tarball);
req.put("name", module.getModuleName());
req.put("version", module.getModuleVersion());
this.runtime.requestResponse(req);
} catch (IOException e) {
throw new JsiiException("Unable to extract resource " + module.getBundleResourceName(), e);
}
} | [
"public",
"void",
"loadModule",
"(",
"final",
"JsiiModule",
"module",
")",
"{",
"try",
"{",
"String",
"tarball",
"=",
"extractResource",
"(",
"module",
".",
"getModuleClass",
"(",
")",
",",
"module",
".",
"getBundleResourceName",
"(",
")",
",",
"null",
")",
... | Loads a JavaScript module into the remote sandbox.
@param module The module to load | [
"Loads",
"a",
"JavaScript",
"module",
"into",
"the",
"remote",
"sandbox",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L46-L57 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.deleteObject | public void deleteObject(final JsiiObjectRef objRef) {
ObjectNode req = makeRequest("del", objRef);
this.runtime.requestResponse(req);
} | java | public void deleteObject(final JsiiObjectRef objRef) {
ObjectNode req = makeRequest("del", objRef);
this.runtime.requestResponse(req);
} | [
"public",
"void",
"deleteObject",
"(",
"final",
"JsiiObjectRef",
"objRef",
")",
"{",
"ObjectNode",
"req",
"=",
"makeRequest",
"(",
"\"del\"",
",",
"objRef",
")",
";",
"this",
".",
"runtime",
".",
"requestResponse",
"(",
"req",
")",
";",
"}"
] | Deletes a remote object.
@param objRef The object reference. | [
"Deletes",
"a",
"remote",
"object",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L98-L101 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.getPropertyValue | public JsonNode getPropertyValue(final JsiiObjectRef objRef, final String property) {
ObjectNode req = makeRequest("get", objRef);
req.put("property", property);
return this.runtime.requestResponse(req).get("value");
} | java | public JsonNode getPropertyValue(final JsiiObjectRef objRef, final String property) {
ObjectNode req = makeRequest("get", objRef);
req.put("property", property);
return this.runtime.requestResponse(req).get("value");
} | [
"public",
"JsonNode",
"getPropertyValue",
"(",
"final",
"JsiiObjectRef",
"objRef",
",",
"final",
"String",
"property",
")",
"{",
"ObjectNode",
"req",
"=",
"makeRequest",
"(",
"\"get\"",
",",
"objRef",
")",
";",
"req",
".",
"put",
"(",
"\"property\"",
",",
"p... | Gets a value for a property from a remote object.
@param objRef The remote object reference.
@param property The property name.
@return The value of the property. | [
"Gets",
"a",
"value",
"for",
"a",
"property",
"from",
"a",
"remote",
"object",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L109-L114 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.setPropertyValue | public void setPropertyValue(final JsiiObjectRef objRef, final String property, final JsonNode value) {
ObjectNode req = makeRequest("set", objRef);
req.put("property", property);
req.set("value", value);
this.runtime.requestResponse(req);
} | java | public void setPropertyValue(final JsiiObjectRef objRef, final String property, final JsonNode value) {
ObjectNode req = makeRequest("set", objRef);
req.put("property", property);
req.set("value", value);
this.runtime.requestResponse(req);
} | [
"public",
"void",
"setPropertyValue",
"(",
"final",
"JsiiObjectRef",
"objRef",
",",
"final",
"String",
"property",
",",
"final",
"JsonNode",
"value",
")",
"{",
"ObjectNode",
"req",
"=",
"makeRequest",
"(",
"\"set\"",
",",
"objRef",
")",
";",
"req",
".",
"put... | Sets a value for a property in a remote object.
@param objRef The remote object reference.
@param property The name of the property.
@param value The new property value. | [
"Sets",
"a",
"value",
"for",
"a",
"property",
"in",
"a",
"remote",
"object",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L122-L128 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.getStaticPropertyValue | public JsonNode getStaticPropertyValue(final String fqn, final String property) {
ObjectNode req = makeRequest("sget");
req.put("fqn", fqn);
req.put("property", property);
return this.runtime.requestResponse(req).get("value");
} | java | public JsonNode getStaticPropertyValue(final String fqn, final String property) {
ObjectNode req = makeRequest("sget");
req.put("fqn", fqn);
req.put("property", property);
return this.runtime.requestResponse(req).get("value");
} | [
"public",
"JsonNode",
"getStaticPropertyValue",
"(",
"final",
"String",
"fqn",
",",
"final",
"String",
"property",
")",
"{",
"ObjectNode",
"req",
"=",
"makeRequest",
"(",
"\"sget\"",
")",
";",
"req",
".",
"put",
"(",
"\"fqn\"",
",",
"fqn",
")",
";",
"req",... | Gets a value of a static property.
@param fqn The FQN of the class
@param property The name of the static property
@return The value of the static property | [
"Gets",
"a",
"value",
"of",
"a",
"static",
"property",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L136-L141 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.setStaticPropertyValue | public void setStaticPropertyValue(final String fqn, final String property, final JsonNode value) {
ObjectNode req = makeRequest("sset");
req.put("fqn", fqn);
req.put("property", property);
req.set("value", value);
this.runtime.requestResponse(req);
} | java | public void setStaticPropertyValue(final String fqn, final String property, final JsonNode value) {
ObjectNode req = makeRequest("sset");
req.put("fqn", fqn);
req.put("property", property);
req.set("value", value);
this.runtime.requestResponse(req);
} | [
"public",
"void",
"setStaticPropertyValue",
"(",
"final",
"String",
"fqn",
",",
"final",
"String",
"property",
",",
"final",
"JsonNode",
"value",
")",
"{",
"ObjectNode",
"req",
"=",
"makeRequest",
"(",
"\"sset\"",
")",
";",
"req",
".",
"put",
"(",
"\"fqn\"",... | Sets the value of a mutable static property.
@param fqn The FQN of the class
@param property The property name
@param value The new value | [
"Sets",
"the",
"value",
"of",
"a",
"mutable",
"static",
"property",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L149-L155 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.callStaticMethod | public JsonNode callStaticMethod(final String fqn, final String method, final ArrayNode args) {
ObjectNode req = makeRequest("sinvoke");
req.put("fqn", fqn);
req.put("method", method);
req.set("args", args);
JsonNode resp = this.runtime.requestResponse(req);
return resp.get("result");
} | java | public JsonNode callStaticMethod(final String fqn, final String method, final ArrayNode args) {
ObjectNode req = makeRequest("sinvoke");
req.put("fqn", fqn);
req.put("method", method);
req.set("args", args);
JsonNode resp = this.runtime.requestResponse(req);
return resp.get("result");
} | [
"public",
"JsonNode",
"callStaticMethod",
"(",
"final",
"String",
"fqn",
",",
"final",
"String",
"method",
",",
"final",
"ArrayNode",
"args",
")",
"{",
"ObjectNode",
"req",
"=",
"makeRequest",
"(",
"\"sinvoke\"",
")",
";",
"req",
".",
"put",
"(",
"\"fqn\"",
... | Invokes a static method.
@param fqn The FQN of the class.
@param method The method name.
@param args The method arguments.
@return The return value. | [
"Invokes",
"a",
"static",
"method",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L164-L171 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.callMethod | public JsonNode callMethod(final JsiiObjectRef objRef, final String method, final ArrayNode args) {
ObjectNode req = makeRequest("invoke", objRef);
req.put("method", method);
req.set("args", args);
JsonNode resp = this.runtime.requestResponse(req);
return resp.get("result");
} | java | public JsonNode callMethod(final JsiiObjectRef objRef, final String method, final ArrayNode args) {
ObjectNode req = makeRequest("invoke", objRef);
req.put("method", method);
req.set("args", args);
JsonNode resp = this.runtime.requestResponse(req);
return resp.get("result");
} | [
"public",
"JsonNode",
"callMethod",
"(",
"final",
"JsiiObjectRef",
"objRef",
",",
"final",
"String",
"method",
",",
"final",
"ArrayNode",
"args",
")",
"{",
"ObjectNode",
"req",
"=",
"makeRequest",
"(",
"\"invoke\"",
",",
"objRef",
")",
";",
"req",
".",
"put"... | Calls a method on a remote object.
@param objRef The remote object reference.
@param method The name of the method.
@param args Method arguments.
@return The return value of the method. | [
"Calls",
"a",
"method",
"on",
"a",
"remote",
"object",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L180-L187 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.endAsyncMethod | public JsonNode endAsyncMethod(final JsiiPromise promise) {
ObjectNode req = makeRequest("end");
req.put("promiseid", promise.getPromiseId());
JsonNode resp = this.runtime.requestResponse(req);
if (resp == null) {
return null; // result is null
}
return resp.get("result");
} | java | public JsonNode endAsyncMethod(final JsiiPromise promise) {
ObjectNode req = makeRequest("end");
req.put("promiseid", promise.getPromiseId());
JsonNode resp = this.runtime.requestResponse(req);
if (resp == null) {
return null; // result is null
}
return resp.get("result");
} | [
"public",
"JsonNode",
"endAsyncMethod",
"(",
"final",
"JsiiPromise",
"promise",
")",
"{",
"ObjectNode",
"req",
"=",
"makeRequest",
"(",
"\"end\"",
")",
";",
"req",
".",
"put",
"(",
"\"promiseid\"",
",",
"promise",
".",
"getPromiseId",
"(",
")",
")",
";",
"... | Ends the execution of an async method.
@param promise The promise returned by beginAsyncMethod.
@return The method return value. | [
"Ends",
"the",
"execution",
"of",
"an",
"async",
"method",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L210-L218 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.pendingCallbacks | public List<Callback> pendingCallbacks() {
ObjectNode req = makeRequest("callbacks");
JsonNode resp = this.runtime.requestResponse(req);
JsonNode callbacksResp = resp.get("callbacks");
if (callbacksResp == null || !callbacksResp.isArray()) {
throw new JsiiException("Expecting a 'callbacks' key with an array in response");
}
ArrayNode callbacksArray = (ArrayNode) callbacksResp;
List<Callback> result = new ArrayList<>();
callbacksArray.forEach(node -> {
result.add(JsiiObjectMapper.treeToValue(node, Callback.class));
});
return result;
} | java | public List<Callback> pendingCallbacks() {
ObjectNode req = makeRequest("callbacks");
JsonNode resp = this.runtime.requestResponse(req);
JsonNode callbacksResp = resp.get("callbacks");
if (callbacksResp == null || !callbacksResp.isArray()) {
throw new JsiiException("Expecting a 'callbacks' key with an array in response");
}
ArrayNode callbacksArray = (ArrayNode) callbacksResp;
List<Callback> result = new ArrayList<>();
callbacksArray.forEach(node -> {
result.add(JsiiObjectMapper.treeToValue(node, Callback.class));
});
return result;
} | [
"public",
"List",
"<",
"Callback",
">",
"pendingCallbacks",
"(",
")",
"{",
"ObjectNode",
"req",
"=",
"makeRequest",
"(",
"\"callbacks\"",
")",
";",
"JsonNode",
"resp",
"=",
"this",
".",
"runtime",
".",
"requestResponse",
"(",
"req",
")",
";",
"JsonNode",
"... | Dequques all the currently pending callbacks.
@return A list of all pending callbacks. | [
"Dequques",
"all",
"the",
"currently",
"pending",
"callbacks",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L224-L241 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.completeCallback | public void completeCallback(final Callback callback, final String error, final JsonNode result) {
ObjectNode req = makeRequest("complete");
req.put("cbid", callback.getCbid());
req.put("err", error);
req.set("result", result);
this.runtime.requestResponse(req);
} | java | public void completeCallback(final Callback callback, final String error, final JsonNode result) {
ObjectNode req = makeRequest("complete");
req.put("cbid", callback.getCbid());
req.put("err", error);
req.set("result", result);
this.runtime.requestResponse(req);
} | [
"public",
"void",
"completeCallback",
"(",
"final",
"Callback",
"callback",
",",
"final",
"String",
"error",
",",
"final",
"JsonNode",
"result",
")",
"{",
"ObjectNode",
"req",
"=",
"makeRequest",
"(",
"\"complete\"",
")",
";",
"req",
".",
"put",
"(",
"\"cbid... | Completes a callback.
@param callback The callback to complete.
@param error Error information (or null).
@param result Result (or null). | [
"Completes",
"a",
"callback",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L249-L256 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.getModuleNames | public JsonNode getModuleNames(final String moduleName) {
ObjectNode req = makeRequest("naming");
req.put("assembly", moduleName);
JsonNode resp = this.runtime.requestResponse(req);
return resp.get("naming");
} | java | public JsonNode getModuleNames(final String moduleName) {
ObjectNode req = makeRequest("naming");
req.put("assembly", moduleName);
JsonNode resp = this.runtime.requestResponse(req);
return resp.get("naming");
} | [
"public",
"JsonNode",
"getModuleNames",
"(",
"final",
"String",
"moduleName",
")",
"{",
"ObjectNode",
"req",
"=",
"makeRequest",
"(",
"\"naming\"",
")",
";",
"req",
".",
"put",
"(",
"\"assembly\"",
",",
"moduleName",
")",
";",
"JsonNode",
"resp",
"=",
"this"... | Returns all names for a jsii module.
@param moduleName The name of the module.
@return The result (map from "lang" to language configuration). | [
"Returns",
"all",
"names",
"for",
"a",
"jsii",
"module",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L263-L269 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.makeRequest | private ObjectNode makeRequest(final String api) {
ObjectNode req = JSON.objectNode();
req.put("api", api);
return req;
} | java | private ObjectNode makeRequest(final String api) {
ObjectNode req = JSON.objectNode();
req.put("api", api);
return req;
} | [
"private",
"ObjectNode",
"makeRequest",
"(",
"final",
"String",
"api",
")",
"{",
"ObjectNode",
"req",
"=",
"JSON",
".",
"objectNode",
"(",
")",
";",
"req",
".",
"put",
"(",
"\"api\"",
",",
"api",
")",
";",
"return",
"req",
";",
"}"
] | Returns a request object for a specific API call.
@param api The api call (i.e "create", "del", "load", ....)
@return A JSON object | [
"Returns",
"a",
"request",
"object",
"for",
"a",
"specific",
"API",
"call",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L276-L280 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java | JsiiClient.makeRequest | private ObjectNode makeRequest(final String api, final JsiiObjectRef objRef) {
ObjectNode req = makeRequest(api);
req.set("objref", objRef.toJson());
return req;
} | java | private ObjectNode makeRequest(final String api, final JsiiObjectRef objRef) {
ObjectNode req = makeRequest(api);
req.set("objref", objRef.toJson());
return req;
} | [
"private",
"ObjectNode",
"makeRequest",
"(",
"final",
"String",
"api",
",",
"final",
"JsiiObjectRef",
"objRef",
")",
"{",
"ObjectNode",
"req",
"=",
"makeRequest",
"(",
"api",
")",
";",
"req",
".",
"set",
"(",
"\"objref\"",
",",
"objRef",
".",
"toJson",
"("... | Returns a new request object for a specific API and a specific object.
@param api The API call
@param objRef The object reference
@return A JSON object | [
"Returns",
"a",
"new",
"request",
"object",
"for",
"a",
"specific",
"API",
"and",
"a",
"specific",
"object",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L288-L292 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java | JsiiRuntime.requestResponse | JsonNode requestResponse(final JsonNode request) {
try {
// write request
String str = request.toString();
this.stdin.write(str + "\n");
this.stdin.flush();
// read response
JsonNode resp = readNextResponse();
// throw if this is an error response
if (resp.has("error")) {
return processErrorResponse(resp);
}
// process synchronous callbacks (which 'interrupt' the response flow).
if (resp.has("callback")) {
return processCallbackResponse(resp);
}
// null "ok" means undefined result (or void).
return resp.get("ok");
} catch (IOException e) {
throw new JsiiException("Unable to send request to jsii-runtime: " + e.toString(), e);
}
} | java | JsonNode requestResponse(final JsonNode request) {
try {
// write request
String str = request.toString();
this.stdin.write(str + "\n");
this.stdin.flush();
// read response
JsonNode resp = readNextResponse();
// throw if this is an error response
if (resp.has("error")) {
return processErrorResponse(resp);
}
// process synchronous callbacks (which 'interrupt' the response flow).
if (resp.has("callback")) {
return processCallbackResponse(resp);
}
// null "ok" means undefined result (or void).
return resp.get("ok");
} catch (IOException e) {
throw new JsiiException("Unable to send request to jsii-runtime: " + e.toString(), e);
}
} | [
"JsonNode",
"requestResponse",
"(",
"final",
"JsonNode",
"request",
")",
"{",
"try",
"{",
"// write request",
"String",
"str",
"=",
"request",
".",
"toString",
"(",
")",
";",
"this",
".",
"stdin",
".",
"write",
"(",
"str",
"+",
"\"\\n\"",
")",
";",
"this... | The main API of this class. Sends a JSON request to jsii-runtime and returns the JSON response.
@param request The JSON request
@return The JSON response
@throws JsiiException If the runtime returns an error response. | [
"The",
"main",
"API",
"of",
"this",
"class",
".",
"Sends",
"a",
"JSON",
"request",
"to",
"jsii",
"-",
"runtime",
"and",
"returns",
"the",
"JSON",
"response",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java#L71-L98 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java | JsiiRuntime.processErrorResponse | private JsonNode processErrorResponse(final JsonNode resp) {
String errorMessage = resp.get("error").asText();
if (resp.has("stack")) {
errorMessage += "\n" + resp.get("stack").asText();
}
throw new JsiiException(errorMessage);
} | java | private JsonNode processErrorResponse(final JsonNode resp) {
String errorMessage = resp.get("error").asText();
if (resp.has("stack")) {
errorMessage += "\n" + resp.get("stack").asText();
}
throw new JsiiException(errorMessage);
} | [
"private",
"JsonNode",
"processErrorResponse",
"(",
"final",
"JsonNode",
"resp",
")",
"{",
"String",
"errorMessage",
"=",
"resp",
".",
"get",
"(",
"\"error\"",
")",
".",
"asText",
"(",
")",
";",
"if",
"(",
"resp",
".",
"has",
"(",
"\"stack\"",
")",
")",
... | Handles an "error" response by extracting the message and stack trace
and throwing a JsiiException.
@param resp The response
@return Never | [
"Handles",
"an",
"error",
"response",
"by",
"extracting",
"the",
"message",
"and",
"stack",
"trace",
"and",
"throwing",
"a",
"JsiiException",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java#L106-L113 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java | JsiiRuntime.processCallbackResponse | private JsonNode processCallbackResponse(final JsonNode resp) {
if (this.callbackHandler == null) {
throw new JsiiException("Cannot process callback since callbackHandler was not set");
}
Callback callback = JsiiObjectMapper.treeToValue(resp.get("callback"), Callback.class);
JsonNode result = null;
String error = null;
try {
result = this.callbackHandler.handleCallback(callback);
} catch (Exception e) {
if (e.getCause() instanceof InvocationTargetException) {
error = e.getCause().getCause().getMessage();
} else {
error = e.getMessage();
}
}
ObjectNode completeResponse = JsonNodeFactory.instance.objectNode();
completeResponse.put("cbid", callback.getCbid());
if (error != null) {
completeResponse.put("err", error);
}
if (result != null) {
completeResponse.set("result", result);
}
ObjectNode req = JsonNodeFactory.instance.objectNode();
req.set("complete", completeResponse);
return requestResponse(req);
} | java | private JsonNode processCallbackResponse(final JsonNode resp) {
if (this.callbackHandler == null) {
throw new JsiiException("Cannot process callback since callbackHandler was not set");
}
Callback callback = JsiiObjectMapper.treeToValue(resp.get("callback"), Callback.class);
JsonNode result = null;
String error = null;
try {
result = this.callbackHandler.handleCallback(callback);
} catch (Exception e) {
if (e.getCause() instanceof InvocationTargetException) {
error = e.getCause().getCause().getMessage();
} else {
error = e.getMessage();
}
}
ObjectNode completeResponse = JsonNodeFactory.instance.objectNode();
completeResponse.put("cbid", callback.getCbid());
if (error != null) {
completeResponse.put("err", error);
}
if (result != null) {
completeResponse.set("result", result);
}
ObjectNode req = JsonNodeFactory.instance.objectNode();
req.set("complete", completeResponse);
return requestResponse(req);
} | [
"private",
"JsonNode",
"processCallbackResponse",
"(",
"final",
"JsonNode",
"resp",
")",
"{",
"if",
"(",
"this",
".",
"callbackHandler",
"==",
"null",
")",
"{",
"throw",
"new",
"JsiiException",
"(",
"\"Cannot process callback since callbackHandler was not set\"",
")",
... | Processes a "callback" response, which is a request to invoke a synchronous callback
and send back the result.
@param resp The response.
@return The next response in the req/res chain. | [
"Processes",
"a",
"callback",
"response",
"which",
"is",
"a",
"request",
"to",
"invoke",
"a",
"synchronous",
"callback",
"and",
"send",
"back",
"the",
"result",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java#L121-L153 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java | JsiiRuntime.startRuntimeIfNeeded | private void startRuntimeIfNeeded() {
if (childProcess != null) {
return;
}
// If JSII_DEBUG is set, enable traces.
String jsiiDebug = System.getenv("JSII_DEBUG");
if (jsiiDebug != null
&& !jsiiDebug.isEmpty()
&& !jsiiDebug.equalsIgnoreCase("false")
&& !jsiiDebug.equalsIgnoreCase("0")) {
traceEnabled = true;
}
// If JSII_RUNTIME is set, use it to find the jsii-server executable
// otherwise, we default to "jsii-runtime" from PATH.
String jsiiRuntimeExecutable = System.getenv("JSII_RUNTIME");
if (jsiiRuntimeExecutable == null) {
jsiiRuntimeExecutable = prepareBundledRuntime();
}
if (traceEnabled) {
System.err.println("jsii-runtime: " + jsiiRuntimeExecutable);
}
ProcessBuilder pb = new ProcessBuilder("node", jsiiRuntimeExecutable);
if (traceEnabled) {
pb.environment().put("JSII_DEBUG", "1");
}
pb.environment().put("JSII_AGENT", "Java/" + System.getProperty("java.version"));
try {
this.childProcess = pb.start();
} catch (IOException e) {
throw new JsiiException("Cannot find the 'jsii-runtime' executable (JSII_RUNTIME or PATH)");
}
try {
OutputStreamWriter stdinStream = new OutputStreamWriter(this.childProcess.getOutputStream(), "UTF-8");
InputStreamReader stdoutStream = new InputStreamReader(this.childProcess.getInputStream(), "UTF-8");
InputStreamReader stderrStream = new InputStreamReader(this.childProcess.getErrorStream(), "UTF-8");
this.stderr = new BufferedReader(stderrStream);
this.stdout = new BufferedReader(stdoutStream);
this.stdin = new BufferedWriter(stdinStream);
handshake();
this.client = new JsiiClient(this);
// if trace is enabled, start a thread that continuously reads from the child process's
// STDERR and prints to my STDERR.
if (traceEnabled) {
startPipeErrorStreamThread();
}
} catch (IOException e) {
throw new JsiiException(e);
}
} | java | private void startRuntimeIfNeeded() {
if (childProcess != null) {
return;
}
// If JSII_DEBUG is set, enable traces.
String jsiiDebug = System.getenv("JSII_DEBUG");
if (jsiiDebug != null
&& !jsiiDebug.isEmpty()
&& !jsiiDebug.equalsIgnoreCase("false")
&& !jsiiDebug.equalsIgnoreCase("0")) {
traceEnabled = true;
}
// If JSII_RUNTIME is set, use it to find the jsii-server executable
// otherwise, we default to "jsii-runtime" from PATH.
String jsiiRuntimeExecutable = System.getenv("JSII_RUNTIME");
if (jsiiRuntimeExecutable == null) {
jsiiRuntimeExecutable = prepareBundledRuntime();
}
if (traceEnabled) {
System.err.println("jsii-runtime: " + jsiiRuntimeExecutable);
}
ProcessBuilder pb = new ProcessBuilder("node", jsiiRuntimeExecutable);
if (traceEnabled) {
pb.environment().put("JSII_DEBUG", "1");
}
pb.environment().put("JSII_AGENT", "Java/" + System.getProperty("java.version"));
try {
this.childProcess = pb.start();
} catch (IOException e) {
throw new JsiiException("Cannot find the 'jsii-runtime' executable (JSII_RUNTIME or PATH)");
}
try {
OutputStreamWriter stdinStream = new OutputStreamWriter(this.childProcess.getOutputStream(), "UTF-8");
InputStreamReader stdoutStream = new InputStreamReader(this.childProcess.getInputStream(), "UTF-8");
InputStreamReader stderrStream = new InputStreamReader(this.childProcess.getErrorStream(), "UTF-8");
this.stderr = new BufferedReader(stderrStream);
this.stdout = new BufferedReader(stdoutStream);
this.stdin = new BufferedWriter(stdinStream);
handshake();
this.client = new JsiiClient(this);
// if trace is enabled, start a thread that continuously reads from the child process's
// STDERR and prints to my STDERR.
if (traceEnabled) {
startPipeErrorStreamThread();
}
} catch (IOException e) {
throw new JsiiException(e);
}
} | [
"private",
"void",
"startRuntimeIfNeeded",
"(",
")",
"{",
"if",
"(",
"childProcess",
"!=",
"null",
")",
"{",
"return",
";",
"}",
"// If JSII_DEBUG is set, enable traces.",
"String",
"jsiiDebug",
"=",
"System",
".",
"getenv",
"(",
"\"JSII_DEBUG\"",
")",
";",
"if"... | Starts jsii-server as a child process if it is not already started. | [
"Starts",
"jsii",
"-",
"server",
"as",
"a",
"child",
"process",
"if",
"it",
"is",
"not",
"already",
"started",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java#L184-L245 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java | JsiiRuntime.handshake | private void handshake() {
JsonNode helloResponse = this.readNextResponse();
if (!helloResponse.has("hello")) {
throw new JsiiException("Expecting 'hello' message from jsii-runtime");
}
String runtimeVersion = helloResponse.get("hello").asText();
assertVersionCompatible(JSII_RUNTIME_VERSION, runtimeVersion);
} | java | private void handshake() {
JsonNode helloResponse = this.readNextResponse();
if (!helloResponse.has("hello")) {
throw new JsiiException("Expecting 'hello' message from jsii-runtime");
}
String runtimeVersion = helloResponse.get("hello").asText();
assertVersionCompatible(JSII_RUNTIME_VERSION, runtimeVersion);
} | [
"private",
"void",
"handshake",
"(",
")",
"{",
"JsonNode",
"helloResponse",
"=",
"this",
".",
"readNextResponse",
"(",
")",
";",
"if",
"(",
"!",
"helloResponse",
".",
"has",
"(",
"\"hello\"",
")",
")",
"{",
"throw",
"new",
"JsiiException",
"(",
"\"Expectin... | Verifies the "hello" message and runtime version compatibility.
In the meantime, we require full version compatibility, but we should use semver eventually. | [
"Verifies",
"the",
"hello",
"message",
"and",
"runtime",
"version",
"compatibility",
".",
"In",
"the",
"meantime",
"we",
"require",
"full",
"version",
"compatibility",
"but",
"we",
"should",
"use",
"semver",
"eventually",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java#L251-L260 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java | JsiiRuntime.readNextResponse | JsonNode readNextResponse() {
try {
String responseLine = this.stdout.readLine();
if (responseLine == null) {
String error = this.stderr.lines().collect(Collectors.joining("\n\t"));
throw new JsiiException("Child process exited unexpectedly: " + error);
}
return JsiiObjectMapper.INSTANCE.readTree(responseLine);
} catch (IOException e) {
throw new JsiiException("Unable to read reply from jsii-runtime: " + e.toString(), e);
}
} | java | JsonNode readNextResponse() {
try {
String responseLine = this.stdout.readLine();
if (responseLine == null) {
String error = this.stderr.lines().collect(Collectors.joining("\n\t"));
throw new JsiiException("Child process exited unexpectedly: " + error);
}
return JsiiObjectMapper.INSTANCE.readTree(responseLine);
} catch (IOException e) {
throw new JsiiException("Unable to read reply from jsii-runtime: " + e.toString(), e);
}
} | [
"JsonNode",
"readNextResponse",
"(",
")",
"{",
"try",
"{",
"String",
"responseLine",
"=",
"this",
".",
"stdout",
".",
"readLine",
"(",
")",
";",
"if",
"(",
"responseLine",
"==",
"null",
")",
"{",
"String",
"error",
"=",
"this",
".",
"stderr",
".",
"lin... | Reads the next response from STDOUT of the child process.
@return The parsed JSON response.
@throws JsiiException if we couldn't parse the response. | [
"Reads",
"the",
"next",
"response",
"from",
"STDOUT",
"of",
"the",
"child",
"process",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java#L267-L278 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java | JsiiRuntime.startPipeErrorStreamThread | private void startPipeErrorStreamThread() {
Thread daemon = new Thread(() -> {
while (true) {
try {
String line = stderr.readLine();
System.err.println(line);
if (line == null) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
daemon.setDaemon(true);
daemon.start();
} | java | private void startPipeErrorStreamThread() {
Thread daemon = new Thread(() -> {
while (true) {
try {
String line = stderr.readLine();
System.err.println(line);
if (line == null) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
daemon.setDaemon(true);
daemon.start();
} | [
"private",
"void",
"startPipeErrorStreamThread",
"(",
")",
"{",
"Thread",
"daemon",
"=",
"new",
"Thread",
"(",
"(",
")",
"->",
"{",
"while",
"(",
"true",
")",
"{",
"try",
"{",
"String",
"line",
"=",
"stderr",
".",
"readLine",
"(",
")",
";",
"System",
... | Starts a thread that pipes STDERR from the child process to our STDERR. | [
"Starts",
"a",
"thread",
"that",
"pipes",
"STDERR",
"from",
"the",
"child",
"process",
"to",
"our",
"STDERR",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java#L283-L300 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java | JsiiRuntime.assertVersionCompatible | static void assertVersionCompatible(final String expectedVersion, final String actualVersion) {
final String shortActualVersion = actualVersion.replaceAll(VERSION_BUILD_PART_REGEX, "");
final String shortExpectedVersion = expectedVersion.replaceAll(VERSION_BUILD_PART_REGEX, "");
if (shortExpectedVersion.compareTo(shortActualVersion) != 0) {
throw new JsiiException("Incompatible jsii-runtime version. Expecting "
+ shortExpectedVersion
+ ", actual was " + shortActualVersion);
}
} | java | static void assertVersionCompatible(final String expectedVersion, final String actualVersion) {
final String shortActualVersion = actualVersion.replaceAll(VERSION_BUILD_PART_REGEX, "");
final String shortExpectedVersion = expectedVersion.replaceAll(VERSION_BUILD_PART_REGEX, "");
if (shortExpectedVersion.compareTo(shortActualVersion) != 0) {
throw new JsiiException("Incompatible jsii-runtime version. Expecting "
+ shortExpectedVersion
+ ", actual was " + shortActualVersion);
}
} | [
"static",
"void",
"assertVersionCompatible",
"(",
"final",
"String",
"expectedVersion",
",",
"final",
"String",
"actualVersion",
")",
"{",
"final",
"String",
"shortActualVersion",
"=",
"actualVersion",
".",
"replaceAll",
"(",
"VERSION_BUILD_PART_REGEX",
",",
"\"\"",
"... | Asserts that a peer runtimeVersion is compatible with this Java runtime version, which means
they share the same version components, with the possible exception of the build number.
@param expectedVersion The version this client expects from the runtime
@param actualVersion The actual version the runtime reports
@throws JsiiException if versions mismatch | [
"Asserts",
"that",
"a",
"peer",
"runtimeVersion",
"is",
"compatible",
"with",
"this",
"Java",
"runtime",
"version",
"which",
"means",
"they",
"share",
"the",
"same",
"version",
"components",
"with",
"the",
"possible",
"exception",
"of",
"the",
"build",
"number",... | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java#L330-L338 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java | JsiiRuntime.prepareBundledRuntime | private String prepareBundledRuntime() {
try {
String directory = Files.createTempDirectory("jsii-java-runtime").toString();
String entrypoint = extractResource(getClass(), "jsii-runtime.js", directory);
extractResource(getClass(), "jsii-runtime.js.map", directory);
extractResource(getClass(), "mappings.wasm", directory);
return entrypoint;
} catch (IOException e) {
throw new JsiiException("Unable to extract bundle of jsii-runtime.js from jar", e);
}
} | java | private String prepareBundledRuntime() {
try {
String directory = Files.createTempDirectory("jsii-java-runtime").toString();
String entrypoint = extractResource(getClass(), "jsii-runtime.js", directory);
extractResource(getClass(), "jsii-runtime.js.map", directory);
extractResource(getClass(), "mappings.wasm", directory);
return entrypoint;
} catch (IOException e) {
throw new JsiiException("Unable to extract bundle of jsii-runtime.js from jar", e);
}
} | [
"private",
"String",
"prepareBundledRuntime",
"(",
")",
"{",
"try",
"{",
"String",
"directory",
"=",
"Files",
".",
"createTempDirectory",
"(",
"\"jsii-java-runtime\"",
")",
".",
"toString",
"(",
")",
";",
"String",
"entrypoint",
"=",
"extractResource",
"(",
"get... | Extracts all files needed for jsii-runtime.js from JAR into a temp directory.
@return The full path for jsii-runtime.js | [
"Extracts",
"all",
"files",
"needed",
"for",
"jsii",
"-",
"runtime",
".",
"js",
"from",
"JAR",
"into",
"a",
"temp",
"directory",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java#L344-L355 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java | JsiiEngine.loadModule | public void loadModule(final Class<? extends JsiiModule> moduleClass) {
if (!JsiiModule.class.isAssignableFrom(moduleClass)) {
throw new JsiiException("Invalid module class "
+ moduleClass.getName()
+ ". It must be derived from JsiiModule");
}
JsiiModule module;
try {
module = moduleClass.newInstance();
} catch (IllegalAccessException | InstantiationException e) {
throw new JsiiException(e);
}
if (this.loadedModules.containsKey(module.getModuleName())) {
return;
}
// Load dependencies
for (Class<? extends JsiiModule> dep: module.getDependencies()) {
loadModule(dep);
}
this.getClient().loadModule(module);
// indicate that it was loaded
this.loadedModules.put(module.getModuleName(), module);
} | java | public void loadModule(final Class<? extends JsiiModule> moduleClass) {
if (!JsiiModule.class.isAssignableFrom(moduleClass)) {
throw new JsiiException("Invalid module class "
+ moduleClass.getName()
+ ". It must be derived from JsiiModule");
}
JsiiModule module;
try {
module = moduleClass.newInstance();
} catch (IllegalAccessException | InstantiationException e) {
throw new JsiiException(e);
}
if (this.loadedModules.containsKey(module.getModuleName())) {
return;
}
// Load dependencies
for (Class<? extends JsiiModule> dep: module.getDependencies()) {
loadModule(dep);
}
this.getClient().loadModule(module);
// indicate that it was loaded
this.loadedModules.put(module.getModuleName(), module);
} | [
"public",
"void",
"loadModule",
"(",
"final",
"Class",
"<",
"?",
"extends",
"JsiiModule",
">",
"moduleClass",
")",
"{",
"if",
"(",
"!",
"JsiiModule",
".",
"class",
".",
"isAssignableFrom",
"(",
"moduleClass",
")",
")",
"{",
"throw",
"new",
"JsiiException",
... | Loads a JavaScript module into the remote jsii-server.
No-op if the module is already loaded.
@param moduleClass The jsii module class. | [
"Loads",
"a",
"JavaScript",
"module",
"into",
"the",
"remote",
"jsii",
"-",
"server",
".",
"No",
"-",
"op",
"if",
"the",
"module",
"is",
"already",
"loaded",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java#L82-L109 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java | JsiiEngine.registerObject | public void registerObject(final JsiiObjectRef objRef, final Object obj) {
if (obj instanceof JsiiObject) {
((JsiiObject) obj).setObjRef(objRef);
}
this.objects.put(objRef.getObjId(), obj);
} | java | public void registerObject(final JsiiObjectRef objRef, final Object obj) {
if (obj instanceof JsiiObject) {
((JsiiObject) obj).setObjRef(objRef);
}
this.objects.put(objRef.getObjId(), obj);
} | [
"public",
"void",
"registerObject",
"(",
"final",
"JsiiObjectRef",
"objRef",
",",
"final",
"Object",
"obj",
")",
"{",
"if",
"(",
"obj",
"instanceof",
"JsiiObject",
")",
"{",
"(",
"(",
"JsiiObject",
")",
"obj",
")",
".",
"setObjRef",
"(",
"objRef",
")",
"... | Registers an object into the object cache.
@param objRef The object reference.
@param obj The object to register. | [
"Registers",
"an",
"object",
"into",
"the",
"object",
"cache",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java#L116-L121 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java | JsiiEngine.nativeFromObjRef | public Object nativeFromObjRef(final JsiiObjectRef objRef) {
Object obj = this.objects.get(objRef.getObjId());
if (obj == null) {
obj = createNative(objRef.getFqn());
this.registerObject(objRef, obj);
}
return obj;
} | java | public Object nativeFromObjRef(final JsiiObjectRef objRef) {
Object obj = this.objects.get(objRef.getObjId());
if (obj == null) {
obj = createNative(objRef.getFqn());
this.registerObject(objRef, obj);
}
return obj;
} | [
"public",
"Object",
"nativeFromObjRef",
"(",
"final",
"JsiiObjectRef",
"objRef",
")",
"{",
"Object",
"obj",
"=",
"this",
".",
"objects",
".",
"get",
"(",
"objRef",
".",
"getObjId",
"(",
")",
")",
";",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"obj",
... | Returns the native java object for a given jsii object reference.
If it already exists in our native objects cache, we return it.
If we can't find the object in the cache, it means it was created in javascript-land, so we need
to create a native wrapper with the correct type and add it to cache.
@param objRef The object reference.
@return The jsii object the represents this remote object. | [
"Returns",
"the",
"native",
"java",
"object",
"for",
"a",
"given",
"jsii",
"object",
"reference",
".",
"If",
"it",
"already",
"exists",
"in",
"our",
"native",
"objects",
"cache",
"we",
"return",
"it",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java#L133-L140 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java | JsiiEngine.nativeToObjRef | public JsiiObjectRef nativeToObjRef(final Object nativeObject) {
if (nativeObject instanceof JsiiObject) {
return ((JsiiObject) nativeObject).getObjRef();
}
for (String objid : this.objects.keySet()) {
Object obj = this.objects.get(objid);
if (obj == nativeObject) {
return JsiiObjectRef.fromObjId(objid);
}
}
// we don't know of an jsii object that represents this object, so we will need to create it.
return createNewObject(nativeObject);
} | java | public JsiiObjectRef nativeToObjRef(final Object nativeObject) {
if (nativeObject instanceof JsiiObject) {
return ((JsiiObject) nativeObject).getObjRef();
}
for (String objid : this.objects.keySet()) {
Object obj = this.objects.get(objid);
if (obj == nativeObject) {
return JsiiObjectRef.fromObjId(objid);
}
}
// we don't know of an jsii object that represents this object, so we will need to create it.
return createNewObject(nativeObject);
} | [
"public",
"JsiiObjectRef",
"nativeToObjRef",
"(",
"final",
"Object",
"nativeObject",
")",
"{",
"if",
"(",
"nativeObject",
"instanceof",
"JsiiObject",
")",
"{",
"return",
"(",
"(",
"JsiiObject",
")",
"nativeObject",
")",
".",
"getObjRef",
"(",
")",
";",
"}",
... | Returns the jsii object reference given a native object.
If the native object extends JsiiObject (directly or indirectly), we can grab the objref
from within the JsiiObject.
Otherwise, we have a "pure" native object on our hands, so we will first perform a reverse lookup in
the objects cache to see if it was already created, and if it wasn't, we create a new empty JS object.
Note that any native overrides will be applied by createNewObject().
@param nativeObject The native object to obtain the reference for
@return A jsii object reference | [
"Returns",
"the",
"jsii",
"object",
"reference",
"given",
"a",
"native",
"object",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java#L155-L169 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java | JsiiEngine.getObject | public Object getObject(final JsiiObjectRef objRef) {
Object obj = this.objects.get(objRef.getObjId());
if (obj == null) {
throw new JsiiException("Cannot find jsii object: " + objRef.getObjId());
}
return obj;
} | java | public Object getObject(final JsiiObjectRef objRef) {
Object obj = this.objects.get(objRef.getObjId());
if (obj == null) {
throw new JsiiException("Cannot find jsii object: " + objRef.getObjId());
}
return obj;
} | [
"public",
"Object",
"getObject",
"(",
"final",
"JsiiObjectRef",
"objRef",
")",
"{",
"Object",
"obj",
"=",
"this",
".",
"objects",
".",
"get",
"(",
"objRef",
".",
"getObjId",
"(",
")",
")",
";",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"throw",
"new"... | Gets an object by reference. Throws if the object cannot be found.
@param objRef The object reference
@return a JsiiObject
@throws JsiiException If the object is not found. | [
"Gets",
"an",
"object",
"by",
"reference",
".",
"Throws",
"if",
"the",
"object",
"cannot",
"be",
"found",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java#L178-L184 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java | JsiiEngine.resolveJavaClass | private Class<?> resolveJavaClass(final String fqn) throws ClassNotFoundException {
String[] parts = fqn.split("\\.");
if (parts.length < 2) {
throw new JsiiException("Malformed FQN: " + fqn);
}
String moduleName = parts[0];
JsonNode names = this.getClient().getModuleNames(moduleName);
if (!names.has("java")) {
throw new JsiiException("No java name for module " + moduleName);
}
final JsiiModule module = this.loadedModules.get(moduleName);
if (module == null) {
throw new JsiiException("No loaded module is named " + moduleName);
}
return module.resolveClass(fqn);
} | java | private Class<?> resolveJavaClass(final String fqn) throws ClassNotFoundException {
String[] parts = fqn.split("\\.");
if (parts.length < 2) {
throw new JsiiException("Malformed FQN: " + fqn);
}
String moduleName = parts[0];
JsonNode names = this.getClient().getModuleNames(moduleName);
if (!names.has("java")) {
throw new JsiiException("No java name for module " + moduleName);
}
final JsiiModule module = this.loadedModules.get(moduleName);
if (module == null) {
throw new JsiiException("No loaded module is named " + moduleName);
}
return module.resolveClass(fqn);
} | [
"private",
"Class",
"<",
"?",
">",
"resolveJavaClass",
"(",
"final",
"String",
"fqn",
")",
"throws",
"ClassNotFoundException",
"{",
"String",
"[",
"]",
"parts",
"=",
"fqn",
".",
"split",
"(",
"\"\\\\.\"",
")",
";",
"if",
"(",
"parts",
".",
"length",
"<",... | Given a jsii FQN, returns the Java class for it.
@param fqn The FQN.
@return The Java class name. | [
"Given",
"a",
"jsii",
"FQN",
"returns",
"the",
"Java",
"class",
"for",
"it",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java#L203-L221 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java | JsiiEngine.createNative | private JsiiObject createNative(final String fqn) {
try {
Class<?> klass = resolveJavaClass(fqn);
if (klass.isInterface() || Modifier.isAbstract(klass.getModifiers())) {
// "$" is used to represent inner classes in Java
klass = Class.forName(klass.getCanonicalName() + "$" + INTERFACE_PROXY_CLASS_NAME);
}
try {
Constructor<? extends Object> ctor = klass.getDeclaredConstructor(JsiiObject.InitializationMode.class);
ctor.setAccessible(true);
JsiiObject newObj = (JsiiObject) ctor.newInstance(JsiiObject.InitializationMode.Jsii);
ctor.setAccessible(false);
return newObj;
} catch (NoSuchMethodException e) {
throw new JsiiException("Cannot create native object of type "
+ klass.getName()
+ " without a constructor that accepts an InitializationMode argument", e);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
throw new JsiiException("Unable to instantiate a new object for FQN " + fqn + ": "
+ e.getMessage(), e);
}
} catch (ClassNotFoundException e) {
this.log("WARNING: Cannot find the class: %s. Defaulting to JsiiObject", fqn);
return new JsiiObject(JsiiObject.InitializationMode.Jsii);
}
} | java | private JsiiObject createNative(final String fqn) {
try {
Class<?> klass = resolveJavaClass(fqn);
if (klass.isInterface() || Modifier.isAbstract(klass.getModifiers())) {
// "$" is used to represent inner classes in Java
klass = Class.forName(klass.getCanonicalName() + "$" + INTERFACE_PROXY_CLASS_NAME);
}
try {
Constructor<? extends Object> ctor = klass.getDeclaredConstructor(JsiiObject.InitializationMode.class);
ctor.setAccessible(true);
JsiiObject newObj = (JsiiObject) ctor.newInstance(JsiiObject.InitializationMode.Jsii);
ctor.setAccessible(false);
return newObj;
} catch (NoSuchMethodException e) {
throw new JsiiException("Cannot create native object of type "
+ klass.getName()
+ " without a constructor that accepts an InitializationMode argument", e);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
throw new JsiiException("Unable to instantiate a new object for FQN " + fqn + ": "
+ e.getMessage(), e);
}
} catch (ClassNotFoundException e) {
this.log("WARNING: Cannot find the class: %s. Defaulting to JsiiObject", fqn);
return new JsiiObject(JsiiObject.InitializationMode.Jsii);
}
} | [
"private",
"JsiiObject",
"createNative",
"(",
"final",
"String",
"fqn",
")",
"{",
"try",
"{",
"Class",
"<",
"?",
">",
"klass",
"=",
"resolveJavaClass",
"(",
"fqn",
")",
";",
"if",
"(",
"klass",
".",
"isInterface",
"(",
")",
"||",
"Modifier",
".",
"isAb... | Given a jsii FQN, instantiates a Java JsiiObject.
NOTE: if a the Java class cannot be found, we will simply return a {@link JsiiObject}.
@param fqn The jsii FQN of the type
@return An object derived from JsiiObject. | [
"Given",
"a",
"jsii",
"FQN",
"instantiates",
"a",
"Java",
"JsiiObject",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java#L231-L257 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java | JsiiEngine.processAllPendingCallbacks | public void processAllPendingCallbacks() {
while (true) {
List<Callback> callbacks = this.getClient().pendingCallbacks();
if (callbacks.size() == 0) {
break;
}
callbacks.forEach(this::processCallback);
}
} | java | public void processAllPendingCallbacks() {
while (true) {
List<Callback> callbacks = this.getClient().pendingCallbacks();
if (callbacks.size() == 0) {
break;
}
callbacks.forEach(this::processCallback);
}
} | [
"public",
"void",
"processAllPendingCallbacks",
"(",
")",
"{",
"while",
"(",
"true",
")",
"{",
"List",
"<",
"Callback",
">",
"callbacks",
"=",
"this",
".",
"getClient",
"(",
")",
".",
"pendingCallbacks",
"(",
")",
";",
"if",
"(",
"callbacks",
".",
"size"... | Dequeues and processes pending jsii callbacks until there are no more callbacks to process. | [
"Dequeues",
"and",
"processes",
"pending",
"jsii",
"callbacks",
"until",
"there",
"are",
"no",
"more",
"callbacks",
"to",
"process",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java#L284-L293 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java | JsiiEngine.invokeCallbackGet | private JsonNode invokeCallbackGet(final GetRequest req) {
Object obj = this.getObject(req.getObjref());
String methodName = javaScriptPropertyToJavaPropertyName("get", req.getProperty());
try {
Method getter = obj.getClass().getMethod(methodName);
return JsiiObjectMapper.valueToTree(invokeMethod(obj, getter));
} catch (NoSuchMethodException e) {
throw new JsiiException(e);
}
} | java | private JsonNode invokeCallbackGet(final GetRequest req) {
Object obj = this.getObject(req.getObjref());
String methodName = javaScriptPropertyToJavaPropertyName("get", req.getProperty());
try {
Method getter = obj.getClass().getMethod(methodName);
return JsiiObjectMapper.valueToTree(invokeMethod(obj, getter));
} catch (NoSuchMethodException e) {
throw new JsiiException(e);
}
} | [
"private",
"JsonNode",
"invokeCallbackGet",
"(",
"final",
"GetRequest",
"req",
")",
"{",
"Object",
"obj",
"=",
"this",
".",
"getObject",
"(",
"req",
".",
"getObjref",
"(",
")",
")",
";",
"String",
"methodName",
"=",
"javaScriptPropertyToJavaPropertyName",
"(",
... | Invokes an override for a property getter.
@param req The get request
@return The override's return value. | [
"Invokes",
"an",
"override",
"for",
"a",
"property",
"getter",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java#L319-L328 | train |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java | JsiiEngine.invokeCallbackSet | private JsonNode invokeCallbackSet(final SetRequest req) {
final Object obj = this.getObject(req.getObjref());
String setterMethodName = javaScriptPropertyToJavaPropertyName("set", req.getProperty());
Method setter = null;
for (Method method: obj.getClass().getMethods()) {
if (method.getName().equals(setterMethodName)) {
setter = method;
break;
}
}
if (setter == null) {
throw new JsiiException("Unable to find property setter " + setterMethodName);
}
final Object arg = JsiiObjectMapper.treeToValue(req.getValue(), setter.getParameterTypes()[0]);
return JsiiObjectMapper.valueToTree(invokeMethod(obj, setter, arg));
} | java | private JsonNode invokeCallbackSet(final SetRequest req) {
final Object obj = this.getObject(req.getObjref());
String setterMethodName = javaScriptPropertyToJavaPropertyName("set", req.getProperty());
Method setter = null;
for (Method method: obj.getClass().getMethods()) {
if (method.getName().equals(setterMethodName)) {
setter = method;
break;
}
}
if (setter == null) {
throw new JsiiException("Unable to find property setter " + setterMethodName);
}
final Object arg = JsiiObjectMapper.treeToValue(req.getValue(), setter.getParameterTypes()[0]);
return JsiiObjectMapper.valueToTree(invokeMethod(obj, setter, arg));
} | [
"private",
"JsonNode",
"invokeCallbackSet",
"(",
"final",
"SetRequest",
"req",
")",
"{",
"final",
"Object",
"obj",
"=",
"this",
".",
"getObject",
"(",
"req",
".",
"getObjref",
"(",
")",
")",
";",
"String",
"setterMethodName",
"=",
"javaScriptPropertyToJavaProper... | Invokes an override for a property setter.
@param req The set request
@return The setter return value (an empty object) | [
"Invokes",
"an",
"override",
"for",
"a",
"property",
"setter",
"."
] | 6bbf743f5f65e98e5199ad31c93961533ffc40e5 | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java#L335-L353 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.